HTML简单贪吃蛇游戏

1.功能说明:

游戏网格:一个20x20的网格,每个格子的大小为20x20像素。
蛇的移动:玩家可以通过方向键(左、上、右、下)控制蛇的移动。
食物生成:食物会在随机位置生成,当蛇吃到食物时,蛇会变长。
碰撞检测:如果蛇撞到墙壁或自身,游戏结束并提示“游戏结束!”。
速度控制:通过滑动条可以调整游戏的速度。

HTML部分:定义了游戏的基本结构,包括画布和速度控制滑动条。
CSS部分:设置了游戏容器、画布和控件的样式。
JavaScript部分:
变量初始化:定义了游戏所需的各种变量,如蛇的位置、方向、食物的位置等。
startGame函数:初始化游戏状态并启动游戏循环。
update函数:更新游戏状态,包括移动蛇、检查碰撞和绘制游戏画面。
moveSnake函数:根据当前方向移动蛇,并处理吃到食物的情况。
checkCollision函数:检查蛇是否撞到墙壁或自身。
draw函数:在画布上绘制蛇和食物。
placeFood函数:随机放置食物,并确保食物不在蛇身上。
gameOver函数:处理游戏结束的情况,提示玩家并重新开始游戏。
changeDirection函数:根据按键改变蛇的方向。
updateSpeed函数:根据滑动条调整游戏速度。

2.代码展示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单贪吃蛇游戏</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .game-container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        canvas {
            border: 1px solid black;
            background-color: #fff;
        }
        .controls {
            margin-top: 20px;
        }
        .controls label {
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h2>简单贪吃蛇游戏</h2>
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        <div class="controls">
            <label for="speed">速度:</label>
            <input type="range" id="speed" min="50" max="500" value="200" oninput="updateSpeed()">
        </div>
    </div>

    <script>
        // 获取画布元素和绘图上下文
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');

        // 定义网格大小和单元格数量
        const gridSize = 20;
        const tileCount = canvas.width / gridSize;

        // 初始化蛇的位置和方向,以及食物的位置
        let snake = [{ x: 10, y: 10 }];
        let direction = { x: 0, y: 0 };
        let food = { x: 15, y: 15 };
        let speed = 200; // 初始速度
        let gameInterval; // 游戏循环定时器

        // 开始游戏函数
        function startGame() {
            clearInterval(gameInterval); // 清除之前的定时器
            snake = [{ x: 10, y: 10 }]; // 重置蛇的位置
            direction = { x: 0, y: 0 }; // 重置方向
            placeFood(); // 放置食物
            gameInterval = setInterval(update, speed); // 启动游戏循环
        }

        // 更新游戏状态函数
        function update() {
            moveSnake(); // 移动蛇
            checkCollision(); // 检查碰撞
            draw(); // 绘制游戏画面
        }

        // 移动蛇的函数
        function moveSnake() {
            const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y }; // 计算新头部位置
            snake.unshift(head); // 将新头部添加到蛇的前面

            // 如果蛇头吃到食物,增长蛇身;否则移除蛇尾
            if (head.x === food.x && head.y === food.y) {
                placeFood();
            } else {
                snake.pop();
            }
        }

        // 检查碰撞的函数
        function checkCollision() {
            const head = snake[0];

            // 检查是否撞到墙壁
            if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
                gameOver();
                return;
            }

            // 检查是否撞到自身
            for (let i = 1; i < snake.length; i++) {
                if (snake[i].x === head.x && snake[i].y === head.y) {
                    gameOver();
                    return;
                }
            }
        }

        // 绘制游戏画面的函数
        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布

            // 绘制蛇
            snake.forEach(segment => {
                ctx.fillStyle = 'green';
                ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
            });

            // 绘制食物
            ctx.fillStyle = 'red';
            ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
        }

        // 放置食物的函数
        function placeFood() {
            food = {
                x: Math.floor(Math.random() * tileCount),
                y: Math.floor(Math.random() * tileCount)
            };

            // 确保食物不在蛇身上
            while (snake.some(segment => segment.x === food.x && segment.y === food.y)) {
                food = {
                    x: Math.floor(Math.random() * tileCount),
                    y: Math.floor(Math.random() * tileCount)
                };
            }
        }

        // 游戏结束的函数
        function gameOver() {
            clearInterval(gameInterval); // 停止游戏循环
            alert('游戏结束!'); // 提示游戏结束
            startGame(); // 重新开始游戏
        }

        // 根据按键改变蛇的方向
        function changeDirection(event) {
            const keyPressed = event.keyCode;

            // 左箭头键
            if (keyPressed === 37 && direction.x === 0) {
                direction = { x: -1, y: 0 };
            }
            // 上箭头键
            else if (keyPressed === 38 && direction.y === 0) {
                direction = { x: 0, y: -1 };
            }
            // 右箭头键
            else if (keyPressed === 39 && direction.x === 0) {
                direction = { x: 1, y: 0 };
            }
            // 下箭头键
            else if (keyPressed === 40 && direction.y === 0) {
                direction = { x: 0, y: 1 };
            }
        }

        // 根据滑动条更新速度
        function updateSpeed() {
            const speedInput = document.getElementById('speed');
            speed = parseInt(speedInput.value, 10); // 获取新的速度值
            clearInterval(gameInterval); // 清除旧的定时器
            gameInterval = setInterval(update, speed); // 设置新的定时器
        }

        // 监听键盘事件以改变蛇的方向
        document.addEventListener('keydown', changeDirection);

        // 开始游戏
        startGame();
    </script>
</body>
</html>

3.展示效果图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

编织幻境的妖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值