创建一个贪吃蛇游戏涉及到很多步骤,以下是一个简化版的贪吃蛇游戏实现方案,使用HTML5的<canvas>
元素。
HTML
首先,在HTML中创建一个<canvas>
元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>贪吃蛇游戏</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>
JavaScript (snake.js)
然后,在snake.js
中实现游戏逻辑。
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const boxSize = 20;
let snake = [{ x: 10, y: 10 }];
let food = { x: 5, y: 5 };
let direction = 'right';
let changingDirection = false;
document.addEventListener('keydown', changeDirection);
function changeDirection(event) {
if (changingDirection) return;
changingDirection = true;
switch (event.key) {
case 'ArrowUp':
if (direction !== 'down') direction = 'up';
break;
case 'ArrowDown':
if (direction !== 'up') direction = 'down';
break;
case 'ArrowLeft':
if (direction !== 'right') direction = 'left';
break;
case 'ArrowRight':
if (direction !== 'left') direction = 'right';
break;
}
setTimeout(() => changingDirection = false, 100);
}
function placeFood() {
food.x = Math.floor(Math.random() * canvas.width / boxSize);
food.y = Math.floor(Math.random() * canvas.height / boxSize);
for (let cell of snake) {
if (food.x === cell.x && food.y === cell.y) placeFood();
}
}
function moveSnake() {
const head = { ...snake[0] };
switch (direction) {
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
case 'left':
head.x--;
break;
case 'right':
head.x++;
break;
}
snake.unshift(head);
if (snake[0].x === food.x && snake[0].y === food.y) {
placeFood();
} else {
snake.pop();
}
}
function drawGame() {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'green';
for (let cell of snake) {
ctx.fillRect(cell.x * boxSize, cell.y * boxSize, boxSize, boxSize);
}
ctx.fillStyle = 'red';
ctx.fillRect(food.x * boxSize, food.y * boxSize, boxSize, boxSize);
}
function updateGame() {
moveSnake();
drawGame();
}
function gameLoop() {
updateGame();
requestAnimationFrame(gameLoop);
}
placeFood();
gameLoop();
这段代码实现了一个简单的贪吃蛇游戏,包括蛇的移动、食物的生成和游戏画面的绘制。你可以通过箭头键来控制蛇的移动方向。当蛇吃到食物时,食物会重新生成在一个随机的位置,并且蛇的长度会增加。如果蛇没有吃到食物,它的尾部会缩短,保持蛇的总长度不变。
标签:canvas,food,direction,boxSize,break,小游戏,snake,贪吃蛇 From: https://www.cnblogs.com/ai888/p/18621812