使用单个HTML实现贪吃蛇游戏:方向键(左、上、右、下)控制,碰壁不会结束

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f0f0f0;
            margin: 0;
        }
        #score {
            font-size: 24px;
            color: #319403;
        }
        #gameCanvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <div id="score">得分: 0</div>
    <canvas id="gameCanvas" width="600" height="600"></canvas>
    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const box = 20;
        let snake = [];
        snake[0] = { x: 10 * box, y: 10 * box };
        let food = {
            x: Math.floor(Math.random() * 20) * box,
            y: Math.floor(Math.random() * 20) * box
        };
        let d;
        let score = 0; // 初始化得分
        const scoreElement = document.getElementById('score'); // 获取得分显示元素
        document.addEventListener('keydown', direction);
        function direction(event) {
            if (event.keyCode == 37 && d != 'RIGHT') {
                d = 'LEFT';
            } else if (event.keyCode == 38 && d != 'DOWN') {
                d = 'UP';
            } else if (event.keyCode == 39 && d != 'LEFT') {
                d = 'RIGHT';
            } else if (event.keyCode == 40 && d != 'UP') {
                d = 'DOWN';
            }
        }
        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            for (let i = 0; i < snake.length; i++) {
                ctx.fillStyle = i == 0 ? 'green' : 'white';
                ctx.fillRect(snake[i].x, snake[i].y, box, box);
                ctx.strokeStyle = 'black';
                ctx.strokeRect(snake[i].x, snake[i].y, box, box);
            }
            ctx.fillStyle = 'red';
            ctx.fillRect(food.x, food.y, box, box);
            let snakeX = snake[0].x;
            let snakeY = snake[0].y;
            if (d == 'LEFT') snakeX -= box;
            if (d == 'UP') snakeY -= box;
            if (d == 'RIGHT') snakeX += box;
            if (d == 'DOWN') snakeY += box;
            if (snakeX == food.x && snakeY == food.y) {
                food = {
                    x: Math.floor(Math.random() * 20) * box,
                    y: Math.floor(Math.random() * 20) * box
                };
                score += 1; // 每次吃到食物得分增加
                scoreElement.textContent = '得分: ' + score; // 更新得分显示
            } else {
                snake.pop();
            }
            if (snakeX < 0) {
                snakeX = canvas.width - box;
            } else if (snakeX >= canvas.width) {
                snakeX = 0;
            }
            if (snakeY < 0) {
                snakeY = canvas.height - box;
            } else if (snakeY >= canvas.height) {
                snakeY = 0;
            }
            let newHead = {
                x: snakeX,
                y: snakeY
            };
            snake.unshift(newHead);
        }
        function collision(head, array) {
            for (let i = 0; i < array.length; i++) {
                if (head.x == array[i].x && head.y == array[i].y) {
                    return true;
                }
            }
            return false;
        }
        let game = setInterval(draw, 200);
    </script>
</body>
</html>
相关推荐
ankleless16 分钟前
C语言(12)——进阶函数
前端·html
码码哈哈爱分享18 分钟前
Tauri 框架介绍
css·rust·vue·html
我是哈哈hh35 分钟前
【Node.js】ECMAScript标准 以及 npm安装
开发语言·前端·javascript·node.js
张元清1 小时前
电商 Feeds 流缓存策略:Temu vs 拼多多的技术选择
前端·javascript·面试
pepedd8641 小时前
浅谈js拷贝问题-解决拷贝数据难题
前端·javascript·trae
@大迁世界1 小时前
useCallback 的陷阱:当 React Hooks 反而拖了后腿
前端·javascript·react.js·前端框架·ecmascript
小高0071 小时前
📌React 路由超详解(2025 版):从 0 到 1 再到 100,一篇彻底吃透
前端·javascript·react.js
summer7771 小时前
GIS三维可视化-Cesium
前端·javascript·数据可视化
Sammyyyyy2 小时前
2025年,Javascript后端应该用 Bun、Node.js 还是 Deno?
开发语言·javascript·node.js
小高0073 小时前
面试官:npm run build 到底干了什么?从 package.json 到 dist 的 7 步拆解
前端·javascript·vue.js