贪吃蛇小游戏

105 阅读1分钟

这是一款经典贪吃蛇玩法的休闲游戏。玩家操控不断增长的小蛇在方格地图中移动,通过吞食随机出现的食物变长,同时要避开墙壁和自己的身体。游戏设有简单、困难等不同难度模式,速度会随分数提升逐渐加快,挑战手速与反应力。界面清新简约,音效轻快,适合碎片化时间放松。无论是新手体验童年回忆,还是高手冲击排行榜,都能在“吃与躲”的趣味中收获快乐。

贪吃蛇 canvas { border: 2px solid #333; background: #000; } body { display: flex; flex-direction: column; align-items: center; background: #1a1a1a; color: white; font-family: Arial; } #score { font-size: 24px; margin: 20px; }
得分: 0
<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 food = {x: 15, y: 15};
    let dx = 0;
    let dy = 0;
    let score = 0;

    // 控制方向
    document.addEventListener('keydown', (e) => {
        switch(e.key) {
            case 'ArrowUp': if(dy !== 1) { dx = 0; dy = -1; } break;
            case 'ArrowDown': if(dy !== -1) { dx = 0; dy = 1; } break;
            case 'ArrowLeft': if(dx !== 1) { dx = -1; dy = 0; } break;
            case 'ArrowRight': if(dx !== -1) { dx = 1; dy = 0; } break;
        }
    });

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

        // 边界检测
        if(head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
            alert('游戏结束!得分:' + score);
            location.reload();
        }

        // 吃食物检测
        if(head.x === food.x && head.y === food.y) {
            score += 10;
            document.getElementById('score').textContent = '得分: ' + score;
            food = {
                x: Math.floor(Math.random() * tileCount),
                y: Math.floor(Math.random() * tileCount)
            };
        } else {
            snake.pop();
        }

        // 碰撞检测
        snake.forEach(segment => {
            if(segment.x === head.x && segment.y === head.y) {
                alert('游戏结束!得分:' + score);
                location.reload();
            }
        });

        snake.unshift(head);

        // 绘制画面
        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

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

        // 绘制食物
        ctx.fillStyle = '#FF0000';
        ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize-2, gridSize-2);

        setTimeout(gameLoop, 100);
    }

    gameLoop();
</script>