```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
// Get the canvas and its context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Snake initial position and direction
let snake = [{ x: 200, y: 200 }];
let dx = 10;
let dy = 0;
// Apple initial position
let apple = { x: 100, y: 100 };
// Game loop interval and speed
let gameLoop;
// Initialize game
function init() {
// Reset snake position and direction
snake = [{ x: 200, y: 200 }];
dx = 10;
dy = 0;
// Reset apple position
apple = { x: 100, y: 100 };
// Start game loop
gameLoop = setInterval(game, 100);
}
// Handle game logic
function game() {
// Move snake
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
snake.unshift(head);
// Check if snake eats apple
if (head.x === apple.x && head.y === apple.y) {
// Generate new apple
apple.x = Math.floor(Math.random() * canvas.width / 10) * 10;
apple.y = Math.floor(Math.random() * canvas.height / 10) * 10;
} else {
// Remove tail
snake.pop();
}
// Check if snake hits wall
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
clearInterval(gameLoop);
alert('Game Over!');
init();
}
// Check if snake eats itself
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
clearInterval(gameLoop);
alert('Game Over!');
init();
}
}
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw snake
ctx.fillStyle = 'green';
snake.forEach(part => {
ctx.fillRect(part.x, part.y, 10, 10);
});
// Draw apple
ctx.fillStyle = 'red';
ctx.fillRect(apple.x, apple.y, 10, 10);
}
// Handle keyboard input
document.addEventListener('keydown', e => {
// Prevent snake from reversing
if (e.key === 'ArrowLeft' && dx === 0) {
dx = -10;
dy = 0;
}
if (e.key === 'ArrowRight' && dx === 0) {
dx = 10;
dy = 0;
}
if (e.key === 'ArrowUp' && dy === 0) {
dx = 0;
dy = -10;
}
if (e.key === 'ArrowDown' && dy === 0) {
dx = 0;
dy = 10;
}
});
// Start the game
init();
</script>
</body>
</html>
```
### 解释:
- **HTML结构:**
- 使用 `<canvas>` 元素创建游戏画布。
- **CSS:**
- 简单的样式设置,使游戏画布居中并具有黑色边框。
- **JavaScript:**
- 初始化snake和apple的位置。
- 设置游戏循环(game loop),每100毫秒执行一次游戏逻辑。
- 处理蛇的移动、吃苹果、碰壁和碰撞自身的情况。
- 绘制蛇和苹果,使用 `ctx.fillRect()` 方法在canvas上绘制矩形。
通过方向键控制蛇的移动方向。游戏在蛇碰到墙壁或者碰到自身时会结束,并重新开始。
Html贪吃蛇小游戏
最新推荐文章于 2024-08-26 23:00:55 发布