使用 Canvas 實現貪吃蛇小游戲
在這篇博客中,我們將介紹如何使用 HTML5 Canvas 和 JavaScript 實現一個簡單的貪吃蛇(Snake)小游戲。這個項目是一個基礎的游戲開發練習,它可以幫助你理解如何在 Canvas 上繪圖、如何處理用戶輸入以及如何管理游戲狀態。
項目結構
在開始之前,確保你的項目文件結構如下:
index.html
index.css
index.js
HTML 部分
首先,我們在 index.html
中定義 Canvas 和一個重新開始按鈕。
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>貪吃蛇游戲</title><link rel="stylesheet" href="index.css">
</head>
<body><canvas id="gameCanvas" width="400" height="400"></canvas><button id="restartButton" style="display: none;" onclick="restartGame()">重新開始</button><script src="index.js"></script>
</body>
</html>
CSS 部分
在 index.css
中,我們可以設置 Canvas 和按鈕的樣式。
/* styles.css */
body {display: flex;flex-direction: column;justify-content: center;align-items: center;height: 100vh;margin: 0;background-color: #f0f0f0;
}canvas {border: 1px solid #000;background-color: #fff;
}button {display: none;margin-top: 20px;padding: 10px 20px;font-size: 16px;cursor: pointer;position: absolute;
}
JavaScript 部分
接下來,我們在 script.js
中編寫游戲的主要邏輯。
1. 初始化 Canvas 和變量
我們首先獲取 Canvas 元素及其上下文,并定義游戲所需的一些變量。
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const restartButton = document.getElementById("restartButton");const gridSize = 20; // 格子大小
const rows = canvas.height / gridSize;
const cols = canvas.width / gridSize;
2. 初始化游戲
創建 initGame
函數來初始化游戲狀態:
function initGame() {snake = [{ x: cols / 2, y: rows / 2 }, { x: cols / 2 + 1, y: rows / 2 }];food = {x: Math.floor(Math.random() * cols),y: Math.floor(Math.random() * rows),};direction = { x: 1, y: 0 };lastDirection = { x: 1, y: 0 };gameOver = false;restartButton.style.display = "none";gameLoop();
}
3. 繪制游戲元素
我們需要兩個函數來繪制蛇和食物:
function drawCell(x, y, color) {ctx.fillStyle = color;ctx.fillRect(x * gridSize, y * gridSize, gridSize, gridSize);ctx.strokeStyle = "#000";ctx.lineWidth = 2; // 可以根據需要調整ctx.strokeRect(x * gridSize, y * gridSize, gridSize, gridSize);
}function drawSnake() {snake.forEach((part) => drawCell(part.x, part.y, "#409EFF"));
}function drawFood() {drawCell(food.x, food.y, "#E6A23C");
}
4. 更新蛇的位置
創建 updateSnake
函數來更新蛇的位置,并檢查它是否吃到食物或撞到墻及自身:
function updateSnake() {const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };if (head.x === food.x && head.y === food.y) {food = {x: Math.floor(Math.random() * cols),y: Math.floor(Math.random() * rows),};} else {snake.pop();}snake.unshift(head);// 撞墻或撞到自己if (head.x < 0 ||head.x >= cols ||head.y < 0 ||head.y >= rows ||snake.slice(1).some((part) => part.x === head.x && part.y === head.y)) {gameOver = true;}lastDirection = direction;
}
5. 游戲循環
創建 gameLoop
函數來處理游戲的繪制和更新:
function gameLoop() {if (!gameOver) {ctx.clearRect(0, 0, canvas.width, canvas.height);drawFood();updateSnake();drawSnake();setTimeout(gameLoop, 100);} else {ctx.font = "100px Arial";ctx.fillStyle = "#F56C6C";ctx.fillText("Game Over", canvas.width / 4, canvas.height / 2);restartButton.style.display = "block"; // 顯示重新開始按鈕}
}
6. 處理用戶輸入
添加鍵盤事件監聽來控制蛇的移動方向:
window.addEventListener("keydown", (event) => {switch (event.key) {case "ArrowUp":if (lastDirection.y === 0) direction = { x: 0, y: -1 };break;case "ArrowDown":if (lastDirection.y === 0) direction = { x: 0, y: 1 };break;case "ArrowLeft":if (lastDirection.x === 0) direction = { x: -1, y: 0 };break;case "ArrowRight":if (lastDirection.x === 0) direction = { x: 1, y: 0 };break;}
});
7. 重新開始游戲
最后,創建一個函數用于重新啟動游戲:
function restartGame() {initGame(); // 重新啟動游戲
}initGame(); // 啟動游戲
總結
通過這篇博客,你學習了如何使用 HTML5 Canvas 和 JavaScript 來實現一個簡單的貪吃蛇小游戲。我們展示了如何繪制游戲元素,處理用戶輸入,并管理游戲狀態。希望這個項目能幫助你對游戲開發有更深入的理解,并激發你進行更多有趣的項目開發!