利用canvas完成贪吃蛇游戏

在这里插入图片描述

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container {
            margin: 50px auto;
            width: 800px;
            height: 800px;
        }
        
        body {
            background-color: slategray;
        }
    </style>
</head>

<body>
    <h2>w:上 s:下 a:左 d:</h2>
    <div class="container">
        <canvas id="canvas"></canvas>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <script>
        const canvas = document.getElementById('canvas');
        canvas.width = 800;
        canvas.height = 800;
        // canvas.style.border = '1px solid red';

        const pen = canvas.getContext('2d');
        for (let i = 0; i <= 800; i += 50) {
            paint(i, i);
        }
        // 模拟数据
        let obj = [
            [0, 0]
        ];
        // 未改变前的方向
        let direction = 'w';
        // let directionY = 'w';
        // 改变后的方向
        let changeDirection = 's';
        let i;
        let shiftIs = true;
        let flag = true;
        let time = 600;
        let result = randomPosition();
        let timer = setInterval(() => {
            i = obj.length;
            // 清空加重新画页面
            pen.clearRect(0, 0, 800, 800);
            for (let m = 0; m <= 800; m += 50) {
                paint(m, m);
            }
            // 重画随机格子
            if (flag) {
                paintSingle(result[0], result[1], result[2]);
            }

            // 清空定时器
            if (obj[obj.length - 1][0] < 0 || obj[obj.length - 1][1] < 0 || obj[obj.length - 1][0] >= 800 || obj[obj.length - 1][1] >= 800) {
                clearInterval(timer);
                alert('游戏结束');
            }
            // 咬到自己的尾巴,结束游戏
            if (obj.length > 4) {
                for (let n = 0; n < i - 1; n++) {
                    if (obj[i - 1][0] == obj[n][0] && obj[i - 1][1] == obj[n][1]) {
                        clearInterval(timer);
                        alert('游戏结束');
                    }
                }
            }
            // 下,排除前一个状态为上
            if (changeDirection == 's') {
                if (direction != 's') {
                    obj.push([obj[i - 1][0], obj[i - 1][1] + 50]);
                    direction = 'w';
                } else {
                    obj.push([obj[i - 1][0], obj[i - 1][1] - 50]);
                    direction = 's';
                }
            }
            // 上,排除前一个状态为下
            if (changeDirection == 'w') {
                if (direction != 'w') {
                    obj.push([obj[i - 1][0], obj[i - 1][1] - 50]);
                    direction = 's';
                } else {
                    obj.push([obj[i - 1][0], obj[i - 1][1] + 50]);
                    direction = 'w';
                }
            }
            // 左,排除前一个状态为右
            if (changeDirection == 'l') {
                if (direction != 'l') {
                    obj.push([obj[i - 1][0] - 50, obj[i - 1][1]]);
                    direction = 'r';
                } else {
                    obj.push([obj[i - 1][0] + 50, obj[i - 1][1]]);
                    direction = 'l';
                }
            }
            // 右,排除前一个状态为左
            if (changeDirection == 'r') {
                if (direction != 'r') {
                    obj.push([obj[i - 1][0] + 50, obj[i - 1][1]]);
                    direction = 'l'
                } else {
                    obj.push([obj[i - 1][0] - 50, obj[i - 1][1]]);
                    direction = 'r';
                }
            }
            // 判断蛇是否吃到格子
            if (obj[i - 1][0] == result[0] && obj[i - 1][1] == result[1]) {
                shiftIs = false;
                result = randomPosition();
            }
            if (shiftIs) {
                obj.shift();
            } else {
                shiftIs = true;
            }
            for (let n = 0; n < obj.length - 1; n++) {
                if (result[0] == obj[n][0] && result[1] == obj[n][1]) {
                    flag = false;
                    result = randomPosition();
                } else {
                    flag = true;
                }
            }
            // 画蛇
            for (let y = 0; y < obj.length; y++) {
                paintSingle(obj[y][0], obj[y][1], obj[y][2]);
            }
            // 速度改变
            if (i >= 10) {
                time = 500;
            } else if (i >= 20) {
                time = 400;
            } else if (i >= 30) {
                time = 250;
            } else if (i >= 40) {
                time = 100;
            } else if (i >= 50) {
                time = 50;
            } else if (i >= 60) {
                time = 30;
            }
        }, time);
        // 方向改变
        $(window).keydown(function(event) {
            switch (event.keyCode) {
                case 87:
                    changeDirection = 'w';
                    break;
                case 83:
                    changeDirection = 's';
                    break;
                case 65:
                    changeDirection = 'l';
                    break;
                case 68:
                    changeDirection = 'r';
                    break;
                default:
                    break;
            }
        });
        // 随机生成一个坐标
        function randomPosition() {
            let position = [Math.floor(Math.random() * 16) * 50, Math.floor(Math.random() * 16) * 50, 'orange'];
            return position;
        }
        // 画单个格子(矩形)
        function paintSingle(x, y, color = 'green') {
            pen.beginPath();
            pen.fillStyle = color;
            pen.fillRect(x, y, 50, 50);
            pen.closePath();
        }

        function paint(x, y) {
            pen.beginPath();
            pen.strokeStyle = 'black';
            pen.moveTo(y, 0);
            pen.lineTo(y, 800);
            pen.stroke();
            pen.closePath();
            pen.beginPath();
            pen.strokeStyle = 'black';
            pen.moveTo(0, x);
            pen.lineTo(800, x);
            pen.stroke();
            pen.closePath();
        }
    </script>
</body>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值