js贪吃蛇小游戏源代码
时间: 2024-09-11 12:01:27 浏览: 85
贪吃蛇小游戏是经典的游戏之一,其基本原理是玩家控制一个不断移动的蛇,吃掉屏幕上出现的食物,每吃掉一个食物,蛇的身体就会变长。游戏的目标是尽可能长时间地生存下去,同时避免蛇头撞到自己的身体或游戏边界。
以下是一个简单的JavaScript实现贪吃蛇游戏的源代码示例,使用了HTML和JavaScript。这段代码中,我们使用了`<canvas>`标签来绘制游戏,JavaScript用于处理游戏逻辑。
HTML部分:
```html
<!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):
```javascript
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20; // 每个格子的大小
let snake = [];
snake[0] = { x: 9 * box, y: 10 * box };
let food = {
x: Math.floor(Math.random() * 17 + 1) * box,
y: Math.floor(Math.random() * 15 + 3) * box
};
let score = 0;
let d;
document.addEventListener("keydown", direction);
function direction(event) {
let key = event.keyCode;
if (key == 37 && d != "RIGHT") {
d = "LEFT";
} else if (key == 38 && d != "DOWN") {
d = "UP";
} else if (key == 39 && d != "LEFT") {
d = "RIGHT";
} else if (key == 40 && d != "UP") {
d = "DOWN";
}
}
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x == array[i].x && head.y == array[i].y) {
return true;
}
}
return false;
}
function draw() {
ctx.fillStyle = 'lightgreen';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i == 0) ? "green" : "white";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "red";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (d == "LEFT") snakeX -= box;
if (d == "UP") snakeY -= box;
if (d == "RIGHT") snakeX += box;
if (d == "DOWN") snakeY += box;
if (snakeX == food.x && snakeY == food.y) {
score++;
food = {
x: Math.floor(Math.random() * 17 + 1) * box,
y: Math.floor(Math.random() * 15 + 3) * box
};
} else {
snake.pop();
}
let newHead = {
x: snakeX,
y: snakeY
};
if (snakeX < 0 || snakeY < 0 || snakeX >= canvas.width || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
}
snake.unshift(newHead);
ctx.fillStyle = "white";
ctx.font = "45px Changa one";
ctx.fillText(score, 2 * box, 1.6 * box);
}
let game = setInterval(draw, 100);
```
这段代码实现了贪吃蛇游戏的基本功能,包括:
- 初始化游戏画布和蛇的起始位置。
- 随机生成食物位置。
- 控制蛇的移动方向。
- 检测蛇头是否与食物或自身或边界发生碰撞。
- 绘制分数。
阅读全文