贪吃蛇小游戏—使用html实现,可直接复制来玩

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snake Game</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }

        canvas {
            border: 1px solid black;
            background-color: #fff;
        }

        #controls {
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <div style="text-align: center;">
        <h1>贪吃蛇游戏</h1>
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        <div id="controls">
            <label for="speed">移动速度:</label>
            <input type="number" id="speed" value="100" min="50" max="500">
            <button id="startButton">开始</button>
        </div>
    </div>

    <script>
        // 获取画布和相关元素
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const startButton = document.getElementById('startButton');
        const speedInput = document.getElementById('speed');

        // 游戏状态
        let gameRunning = false;
        let snake = [{ x: 20, y: 20 }];
        let food = { x: 0, y: 0 };
        let dx = 1;
        let dy = 0;
        let score = 0;

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

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

        // 移动蛇
        function moveSnake() {
            const head = { x: snake[0].x + dx, y: snake[0].y + dy };
            snake.unshift(head);

            // 检查与食物碰撞
            if (head.x === food.x && head.y === food.y) {
                score++;
                generateFood();
            } else {
                snake.pop();
            }

            // 检查边界碰撞
            if (head.x < 0 || head.x >= canvas.width / 10 || head.y < 0 || head.y >= canvas.height / 10) {
                gameOver();
            }

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

        // 生成食物
        function generateFood() {
            food = {
                x: Math.floor(Math.random() * (canvas.width / 10)),
                y: Math.floor(Math.random() * (canvas.height / 10))
            };
        }

        // 游戏结束
        function gameOver() {
            gameRunning = false;
            alert('游戏结束,得分: ' + score);
            snake = [{ x: 20, y: 20 }];
            score = 0;
            dx = 1;
            dy = 0;
        }

        // 游戏循环
        function gameLoop() {
            if (gameRunning) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                drawSnake();
                drawFood();
                moveSnake();
                setTimeout(gameLoop, parseInt(speedInput.value));
            }
        }

        // 开始按钮点击事件
        startButton.addEventListener('click', function () {
            gameRunning = true;
            generateFood();
            gameLoop();
        });

        // 监听速度输入框的变化
        speedInput.addEventListener('input', function () {
            if (gameRunning) {
                clearTimeout(gameLoopTimeout);
                gameLoopTimeout = setTimeout(gameLoop, parseInt(speedInput.value));
            }
        });

        // 监听键盘事件
        document.addEventListener('keydown', function (event) {
            const keyPressed = event.keyCode;

            const goingUp = dy === -1;
            const goingDown = dy === 1;
            const goingRight = dx === 1;
            const goingLeft = dx === -1;

            if (keyPressed === 37 && !goingRight) {
                dx = -1;
                dy = 0;
            }

            if (keyPressed === 38 && !goingDown) {
                dx = 0;
                dy = -1;
            }

            if (keyPressed === 39 && !goingLeft) {
                dx = 1;
                dy = 0;
            }

            if (keyPressed === 40 && !goingUp) {
                dx = 0;
                dy = 1;
            }
        });
    </script>
</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值