canvas 贪吃蛇


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas id="canvas" width="1000px" height="800px" style="border: 1px solid #ccc;"></canvas>
    <script>
        // 定义画布和格子大小
        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        let cellSize = 20;

        // 定义颜色常量
        const BLACK = "#000000";
        const WHITE = "#FFFFFF";
        const GREEN = "#00FF00";
        const RED = "#FF0000";

        // 定义贪吃蛇类
        class Snake {
            constructor() {
                this.length = 1;
                this.positions = [{ x: canvas.width / 2, y: canvas.height / 2 }];
                this.direction = randomChoice([38, 39, 40, 37]); // 上下左右对应键码
                this.color = GREEN;
            }

            getHeadPosition() {
                return this.positions[0];
            }

            move() {
                let cur = this.getHeadPosition();
                let x = cur.x;
                let y = cur.y;

                if (this.direction === 38) {
                    y -= cellSize;
                } else if (this.direction === 40) {
                    y += cellSize;
                } else if (this.direction === 37) {
                    x -= cellSize;
                } else if (this.direction === 39) {
                    x += cellSize;
                }

                this.positions.unshift({ x: x, y: y });

                if (this.positions.length > this.length) {
                    this.positions.pop();
                }
            }

            changeDirection(direction) {
                if (direction === 38 && this.direction !== 40) {
                    this.direction = direction;
                } else if (direction === 40 && this.direction !== 38) {
                    this.direction = direction;
                } else if (direction === 37 && this.direction !== 39) {
                    this.direction = direction;
                } else if (direction === 39 && this.direction !== 37) {
                    this.direction = direction;
                }
            }

            draw() {
                for (let i = 0; i < this.positions.length; i++) {
                    let p = this.positions[i];
                    ctx.fillStyle = this.color;
                    ctx.fillRect(p.x, p.y, cellSize, cellSize);
                    ctx.strokeStyle = BLACK;
                    ctx.strokeRect(p.x, p.y, cellSize, cellSize);
                }
            }

            collideWithApple(applePosition) {
                return this.getHeadPosition().x === applePosition.x && this.getHeadPosition().y === applePosition.y;
            }

            grow() {
                this.length += 1;
            }
        }

        // 定义苹果类
        class Apple {
            constructor() {
                this.position = {};
                this.color = RED;
                this.randomizePosition();
            }

            randomizePosition() {
                this.position = {
                    x: Math.floor(Math.random() * (canvas.width / cellSize)) * cellSize,
                    y: Math.floor(Math.random() * (canvas.height / cellSize)) * cellSize
                };
            }

            draw() {
                ctx.fillStyle = this.color;
                ctx.beginPath();
                ctx.arc(this.position.x + cellSize / 2, this.position.y + cellSize / 2, cellSize / 2, 0, 2 * Math.PI, true);
                ctx.fill();
            }
        }

        // 创建贪吃蛇和苹果对象
        let snake = new Snake();
        let apple = new Apple();

        // 监听键盘事件
        document.addEventListener("keydown", function (event) {
            snake.changeDirection(event.keyCode);
        });

        // 随机选择一个元素
        function randomChoice(choices) {
            let index = Math.floor(Math.random() * choices.length);
            return choices[index];
        }

        // 游戏循环
        let gameLoop = setInterval(function () {
            // 移动贪吃蛇
            snake.move();

            // 如果贪吃蛇碰到苹果,增加长度并重新生成苹果位置
            if (snake.collideWithApple(apple.position)) {
                snake.grow();
                apple.randomizePosition();
            }

            // 绘制游戏界面
            ctx.fillStyle = WHITE;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            snake.draw();
            apple.draw();

        }, 100); // 控制游戏速度

    </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web修理工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值