贪吃蛇游戏edit icon

作者:
lynn-ssk
Fork(复制)
下载
嵌入
设置
BUG反馈
index.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 {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }

        .game-container {
            text-align: center;
        }

        .game-board {
            border: 2px solid #333;
            background-color: #000;
            display: block;
            margin: 0 auto;
        }

        .game-info {
            margin: 10px 0;
            font-size: 18px;
            color: #333;
        }

        .controls {
            margin: 10px 0;
        }

        button {
            padding: 10px 20px;
            font-size: 16px;
            margin: 5px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }

        button:hover {
            background-color: #45a049;
        }

        .game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            display: none;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1>贪吃蛇游戏</h1>
        <div class="game-info">
            <div>得分: <span id="score">0</span></div>
            <div>长度: <span id="length">3</span></div>
        </div>
        <canvas id="gameBoard" class="game-board" width="400" height="400"></canvas>
        <div class="controls">
            <button onclick="startGame()">开始游戏</button>
            <button onclick="pauseGame()">暂停/继续</button>
            <button onclick="resetGame()">重新开始</button>
        </div>
        <div class="instructions">
            <p>使用方向键控制蛇的移动</p>
        </div>
    </div>

    <div id="gameOver" class="game-over">
        <h2>游戏结束!</h2>
        <p>最终得分: <span id="finalScore">0</span></p>
        <button onclick="resetGame()">再玩一次</button>
    </div>

    <script>
        // 游戏变量
        const canvas = document.getElementById('gameBoard');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const lengthElement = document.getElementById('length');
        const gameOverElement = document.getElementById('gameOver');
        const finalScoreElement = document.getElementById('finalScore');

        // 游戏设置
        const gridSize = 20;
        const gridWidth = canvas.width / gridSize;
        const gridHeight = canvas.height / gridSize;

        // 游戏状态
        let snake = [];
        let food = {};
        let direction = 'right';
        let nextDirection = 'right';
        let score = 0;
        let gameSpeed = 150; // 毫秒
        let gameRunning = false;
        let gameLoop;

        // 初始化游戏
        function initGame() {
            // 初始化蛇
            snake = [
                {x: 5, y: 10},
                {x: 4, y: 10},
                {x: 3, y: 10}
            ];

            // 生成食物
            generateFood();

            // 重置游戏状态
            direction = 'right';
            nextDirection = 'right';
            score = 0;
            scoreElement.textContent = score;
            lengthElement.textContent = snake.length;

            // 隐藏游戏结束界面
            gameOverElement.style.display = 'none';
        }

        // 生成食物
        function generateFood() {
            food = {
                x: Math.floor(Math.random() * gridWidth),
                y: Math.floor(Math.random() * gridHeight)
            };

            // 确保食物不会生成在蛇身上
            for (let segment of snake) {
                if (segment.x === food.x && segment.y === food.y) {
                    return generateFood();
                }
            }
        }

        // 绘制游戏
        function draw() {
            // 清空画布
            ctx.fillStyle = '#000';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 绘制蛇
            snake.forEach((segment, index) => {
                if (index === 0) {
                    // 蛇头
                    ctx.fillStyle = '#4CAF50';
                } else {
                    // 蛇身
                    ctx.fillStyle = '#8BC34A';
                }
                ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
                
                // 添加边框
                ctx.strokeStyle = '#333';
                ctx.strokeRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
            });

            // 绘制食物
            ctx.fillStyle = '#FF5252';
            ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
            
            // 添加食物边框
            ctx.strokeStyle = '#D32F2F';
            ctx.strokeRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
        }

        // 更新游戏状态
        function update() {
            // 更新方向
            direction = nextDirection;

            // 计算新的头部位置
            const head = {x: snake[0].x, y: snake[0].y};

            switch (direction) {
                case 'up':
                    head.y--;
                    break;
                case 'down':
                    head.y++;
                    break;
                case 'left':
                    head.x--;
                    break;
                case 'right':
                    head.x++;
                    break;
            }

            // 检查碰撞边界
            if (head.x < 0 || head.x >= gridWidth || head.y < 0 || head.y >= gridHeight) {
                gameOver();
                return;
            }

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

            // 将新头部添加到蛇
            snake.unshift(head);

            // 检查是否吃到食物
            if (head.x === food.x && head.y === food.y) {
                // 增加分数
                score += 10;
                scoreElement.textContent = score;
                lengthElement.textContent = snake.length;
                
                // 生成新食物
                generateFood();
                
                // 增加速度(可选)
                if (gameSpeed > 50) {
                    gameSpeed -= 2;
                }
            } else {
                // 如果没有吃到食物,移除尾部
                snake.pop();
            }
        }

        // 游戏主循环
        function gameStep() {
            update();
            draw();
        }

        // 开始游戏
        function startGame() {
            if (!gameRunning) {
                gameRunning = true;
                gameLoop = setInterval(gameStep, gameSpeed);
            }
        }

        // 暂停/继续游戏
        function pauseGame() {
            if (gameRunning) {
                clearInterval(gameLoop);
                gameRunning = false;
            } else {
                startGame();
            }
        }

        // 重新开始游戏
        function resetGame() {
            clearInterval(gameLoop);
            gameRunning = false;
            initGame();
            draw();
        }

        // 游戏结束
        function gameOver() {
            clearInterval(gameLoop);
            gameRunning = false;
            finalScoreElement.textContent = score;
            gameOverElement.style.display = 'block';
        }

        // 键盘控制
        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowUp':
                    if (direction !== 'down') nextDirection = 'up';
                    break;
                case 'ArrowDown':
                    if (direction !== 'up') nextDirection = 'down';
                    break;
                case 'ArrowLeft':
                    if (direction !== 'right') nextDirection = 'left';
                    break;
                case 'ArrowRight':
                    if (direction !== 'left') nextDirection = 'right';
                    break;
            }
        });

        // 初始化游戏
        initGame();
        draw();
    </script>
</body>
</html>
        
预览
控制台