當然可以!以下是一個簡單的貪吃蛇遊戲的 JavaScript 實現,使用 HTML5 的 <canvas> 元素來繪製遊戲畫面。你可以將以下代碼複製到一個 HTML 文件中,然後在瀏覽器中打開它來玩遊戲。
<!DOCTYPE html>
<html lang="zh-Hant">
<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;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20; // 每個方塊的大小
let snake = [{ x: 9 * box, y: 9 * box }]; // 蛇的初始位置
let direction = 'RIGHT'; // 初始方向
let food = { x: Math.floor(Math.random() * 20) * box, y: Math.floor(Math.random() * 20) * box }; // 食物位置
let score = 0;
// 繪製遊戲畫面
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空畫布
// 繪製食物
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
// 繪製蛇
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? 'green' : 'lightgreen'; // 蛇頭和身體的顏色
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = 'darkgreen';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
// 更新蛇的位置
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction === 'LEFT') snakeX -= box;
if (direction === 'UP') snakeY -= box;
if (direction === 'RIGHT') snakeX += box;
if (direction === 'DOWN') snakeY += box;
// 檢查是否吃到食物
if (snakeX === food.x && snakeY === food.y) {
score++;
food = { x: Math.floor(Math.random() * 20) * box, y: Math.floor(Math.random() * 20) * box }; // 重新生成食物
} else {
snake.pop(); // 移除蛇尾
}
// 檢查蛇是否撞牆或撞到自己
if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(snakeX, snakeY, snake)) {
clearInterval(game);
alert('遊戲結束!你的分數是:' + score);
}
// 在蛇的頭部添加新位置
const newHead = { x: snakeX, y: snakeY };
snake.unshift(newHead);
}
// 檢查蛇是否撞到自己
function collision(headX, headY, array) {
for (let i = 1; i < array.length; i++) {
if (headX === array[i].x && headY === array[i].y) {
return true;
}
}
return false;
}
// 控制蛇的方向
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowLeft' && direction !== 'RIGHT') {
direction = 'LEFT';
} else if (event.key === 'ArrowUp' && direction !== 'DOWN') {
direction = 'UP';
} else if (event.key === 'ArrowRight' && direction !== 'LEFT') {
direction = 'RIGHT';
} else if (event.key === 'ArrowDown' && direction !== 'UP') {
direction = 'DOWN';
}
});
const game = setInterval(draw, 100); // 每100毫秒更新一次畫面
</script>
</body>
</html>
如何使用這段代碼:
- 創建一個新的 HTML 文件,例如
snake_game.html。
- 將上面的代碼複製並粘貼到該文件中。
- 在瀏覽器中打開該文件,你就可以開始玩貪吃蛇遊戲了!
控制方式:
希望你喜歡這個遊戲!如果你有任何問題或需要進一步的功能,隨時告訴我!