制作一个贪吃蛇游戏使用HTML5的Canvas API是一个很好的练习来熟悉前端开发中的图形操作。以下是一个简单的贪吃蛇游戏实现的步骤和代码示例:

步骤 1: 设置HTML结构

创建一个HTML文件,添加一个<canvas>元素用于绘制游戏。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        canvas {
            border: 1px solid black;
            display: block;
            margin: 0 auto;
            background-color: #f4f4f4;
        }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <script src="game.js"></script>
</body>
</html>

步骤 2: 编写JavaScript逻辑 (game.js)

game.js文件中,我们将实现游戏的主要逻辑。

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const boxSize = 20; // 每个格子的大小
let snake = [{ x: 10, y: 10 }]; // 初始蛇的位置和长度
let food = { x: Math.floor(Math.random() * 20), y: Math.floor(Math.random() * 20) }; // 初始食物的位置
let dx = 1, dy = 0; // 蛇的移动方向

document.addEventListener('keydown', (event) => {
    switch (event.key) {
        case 'ArrowUp': if (dy === 0) { dy = -1; dx = 0; } break;
        case 'ArrowDown': if (dy === 0) { dy = 1; dx = 0; } break;
        case 'ArrowLeft': if (dx === 0) { dx = -1; dy = 0; } break;
        case 'ArrowRight': if (dx === 0) { dx = 1; dy = 0; } break;
    }
});

function drawGame() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布

    // 画蛇
    ctx.fillStyle = 'green';
    snake.forEach(part => {
        ctx.fillRect(part.x * boxSize, part.y * boxSize, boxSize, boxSize);
    });

    // 画食物
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x * boxSize, food.y * boxSize, boxSize, boxSize);

    // 移动蛇
    const head = { x: snake[0].x + dx, y: snake[0].y + dy };
    snake.unshift(head); // 添加新的头部

    // 检查蛇是否吃到食物
    if (snake[0].x === food.x && snake[0].y === food.y) {
        food = { x: Math.floor(Math.random() * 20), y: Math.floor(Math.random() * 20) }; // 生成新食物
    } else {
        snake.pop(); // 移除尾部
    }

    // 检查蛇是否撞到墙或自己
    if (snake[0].x < 0 || snake[0].x >= 20 || snake[0].y < 0 || snake[0].y >= 20 || checkCollision(snake, head)) {
        snake = [{ x: 10, y: 10 }]; // 重置游戏
        food = { x: Math.floor(Math.random() * 20), y: Math.floor(Math.random() * 20) }; // 重置食物位置
    }
}

function checkCollision(snake, head) {
    for (let i = 1; i < snake.length; i++) {
        if (snake[i].x === head.x && snake[i].y === head.y) {
            return true;
        }
    }
    return false;
}

// 运行游戏循环
setInterval(drawGame, 150); // 每150ms更新一次游戏状态

步骤 3: 运行和测试游戏

保存HTML和JavaScript文件,并在浏览器中打开HTML文件。你应该能够看到一个简单的贪吃蛇游戏,可以使用箭头键来控制蛇的移动方向。当蛇吃到食物时,食物会重新出现在一个随机位置,并且蛇会变长。如果蛇撞到墙或自己的身体,游戏会重置。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐