MDN 2D 碰撞 H5 游戏完整代码

| Stephen Tseng | notes

参考:2D breakout game using pure JavaScript

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Gamedev Canvas Workshop</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        canvas {
            background: #eee;
            display: block;
            margin: 0 auto;
        }
    </style>
</head>

<body>

    <canvas id="myCanvas" width="480" height="320"></canvas>

    <script>
        // JavaScript code goes here

        var canvas = document.getElementById('myCanvas');

        // canvas 的 getContext 接口,用于获取 canvas 的上下文类型
        // 可能的类型有 2d / webgl / webgl2 / bitmaprender
        // ctx 是可以用来在 canvas 画布上绘制的工具
        var ctx = canvas.getContext('2d');

        // // 画一个红色实心正方形
        // ctx.beginPath();
        // ctx.rect(20, 40, 50, 50);  // 左边距 上边距 宽 高
        // ctx.fillStyle = "#FFFF00";
        // ctx.fill();
        // ctx.closePath();

        // // 画一个绿色的实心圆
        // ctx.beginPath();
        // ctx.arc(240, 160, 20, 0, Math.PI, false);
        // ctx.fillStyle = "green";
        // ctx.fill();
        // ctx.closePath();

        // // 浅蓝色空心长方形
        // ctx.beginPath();
        // ctx.rect(160, 10, 100, 40);
        // ctx.strokeStyle = "rgba(0, 0, 255, 0.5)";
        // ctx.stroke();
        // ctx.closePath();

        // Move the ball
        // 变量定义
        var x = canvas.width / 2;
        var y = canvas.height - 30;  // 设置初始坐标为 (240, 290)
        var dx = 2;
        var dy = -2;  // 设置初始移动方向为 45°
        var ballRadius = 10;  // 设置小球半径为 10
        var paddleHeight = 10;
        var paddleWidth = 75;  // 设置挡板宽高
        var paddleX = (canvas.width - paddleWidth) / 2; // 设置挡板初始 x 值
        var rightPressed = false;
        var leftPressed = false;  // 设置左右按键状态存储变量
        var brickRowCount = 3;
        var brickColumnCount = 5;
        var brickWidth = 75;
        var brickHeight = 20;
        var brickPadding = 10;
        var brickOffsetTop = 30;
        var brickOffsetLeft = 30;  // 砖块组合变量定义
        var score = 0; // 游戏得分数
        var lives = 3; // 游戏生命数

        // 将砖块放入一个二维数组
        var bricks = [];
        for (var c = 0; c < brickColumnCount; c++) {
            bricks[c] = [];
            for (var r = 0; r < brickRowCount; r++) {
                bricks[c][r] = { x: 0, y: 0, status: 1 };
            }
        }
        // 砖块绘制函数
        function drawBricks() {
            for (var c = 0; c < brickColumnCount; c++) {
                for (var r = 0; r < brickRowCount; r++) {
                    if (bricks[c][r].status == 1) {
                        var brickX = (c * (brickWidth + brickPadding)) + brickOffsetLeft;
                        var brickY = (r * (brickHeight + brickPadding)) + brickOffsetTop;
                        bricks[c][r].x = brickX;
                        bricks[c][r].y = brickY;
                        ctx.beginPath();
                        ctx.rect(brickX, brickY, brickWidth, brickHeight);
                        ctx.fillStyle = "#0095DD";
                        ctx.fill();
                        ctx.closePath();
                    }
                }
            }
        }
        // 监听键盘左右键动作
        document.addEventListener("keydown", keyDownHandler, false);
        document.addEventListener("keyup", keyUpHandler, false);
        document.addEventListener("mousemove", mouseMoveHandler, false);
        function keyDownHandler(e) {
            if (e.keyCode == 39) {
                rightPressed = true;
            }
            else if (e.keyCode == 37) {
                leftPressed = true;
            }
        }
        function keyUpHandler(e) {
            if (e.keyCode == 39) {
                rightPressed = false;
            }
            else if (e.keyCode == 37) {
                leftPressed = false;
            }
        }
        function mouseMoveHandler(e) {
            var relativeX = e.clientX - canvas.offsetLeft;
            if (relativeX > 0 && relativeX < canvas.width) {
                paddleX = relativeX - paddleWidth / 2;
            }
        }
        // 碰撞检测函数
        function collisionDetection() {
            for (var c = 0; c < brickColumnCount; c++) {
                for (var r = 0; r < brickRowCount; r++) {
                    var b = bricks[c][r];
                    if (b.status == 1) {
                        if (x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight) {
                            dy = -dy;
                            b.status = 0;
                            score++;
                            if (score == brickRowCount * brickColumnCount) {
                                alert("YOU WIN, CONGRATULATIONS!");
                                document.location.reload();
                                // clearInterval(interval); // Needed for Chrome to end game
                            }
                        }
                    }
                }
            }
        }
        // 分数绘制函数
        function drawScore() {
            ctx.font = "16px Arial";
            ctx.fillStyle = "#0095DD";
            ctx.fillText("Score: " + score, 8, 20);
        }
        // 生命绘制函数
        function drawLives() {
            ctx.font = "16px Arial";
            ctx.fillStyle = "#0095DD";
            ctx.fillText("Lives: " + lives, canvas.width - 65, 20);
        }
        // 小球的绘制函数,变量为 x y ballRadius
        function drawBall() {
            ctx.beginPath();
            ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
            ctx.fillStyle = "#0095DD";
            ctx.fill();
            ctx.closePath();
        }
        // 挡板的绘制函数
        function drawPaddle() {
            ctx.beginPath();
            ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
            ctx.fillStyle = "#0095DD";
            ctx.fill();
            ctx.closePath();
        }
        // 主绘制函数
        function draw() {
            // 小球关键帧
            if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
                dx = -dx;
            }
            if (y + dy < ballRadius) {
                dy = -dy;
            } else if (y + dy > canvas.height - ballRadius - paddleHeight) {
                if (x + ballRadius > paddleX && x - ballRadius < paddleX + paddleWidth) {
                    dy = -dy;
                } else {
                    lives--;
                    if (!lives) {
                        alert("GAME OVER");
                        document.location.reload();
                        // clearInterval(interval); // Needed for Chrome to end game
                    }
                    else {
                        x = canvas.width / 2;
                        y = canvas.height - 30;
                        dx = 2;
                        dy = -2;
                        paddleX = (canvas.width - paddleWidth) / 2;
                    }
                }
                // alert("GAME OVER");
                // document.location.reload();
                // clearInterval(interval); // Needed for Chrome to end game
            }
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            drawBricks();
            drawBall();
            x += dx;
            y += dy;

            // paddle 执行函数
            if (rightPressed && paddleX < canvas.width - paddleWidth) {
                paddleX += 7;
            }
            else if (leftPressed && paddleX > 0) {
                paddleX -= 7;
            }
            drawPaddle();
            collisionDetection();
            drawScore();
            drawLives();
            requestAnimationFrame(draw);
        }
        // 主执行函数
        draw();
    </script>

</body>

</html>