js实现一个高级难度的贪吃蛇游戏
时间: 2024-01-20 14:03:31 浏览: 25
好的,下面是一个使用 JavaScript 实现的高级难度的贪吃蛇游戏:
```html
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
body {
background-color: #f5f5f5;
text-align: center;
}
canvas {
border: 1px solid #000;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script>
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
// 设置游戏区域大小
canvas.width = 600;
canvas.height = 600;
// 定义常量
const CELL_SIZE = 20; // 单元格大小
const GRID_SIZE = canvas.width / CELL_SIZE; // 网格大小
const FPS = 10; // 帧率
// 初始化贪吃蛇
var snake = {
body: [{x: 10, y: 10}],
direction: "right",
length: 1
};
// 初始化食物
var food = {
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE)
};
// 绘制贪吃蛇
function drawSnake() {
ctx.fillStyle = "#000";
for (var i = 0; i < snake.body.length; i++) {
ctx.fillRect(snake.body[i].x * CELL_SIZE, snake.body[i].y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
// 绘制食物
function drawFood() {
ctx.fillStyle = "#f00";
ctx.fillRect(food.x * CELL_SIZE, food.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
// 移动贪吃蛇
function moveSnake() {
// 根据方向移动蛇头
var headX = snake.body[0].x;
var headY = snake.body[0].y;
switch (snake.direction) {
case "up":
headY--;
break;
case "down":
headY++;
break;
case "left":
headX--;
break;
case "right":
headX++;
break;
}
// 判断是否撞墙或撞到自己
if (headX < 0 || headX >= GRID_SIZE || headY < 0 || headY >= GRID_SIZE || isCollide(headX, headY, snake.body)) {
// 游戏结束
clearInterval(gameInterval);
alert("游戏结束!");
} else {
// 判断是否吃到食物
if (headX == food.x && headY == food.y) {
// 增加蛇的长度
snake.length++;
// 重新生成食物
food.x = Math.floor(Math.random() * GRID_SIZE);
food.y = Math.floor(Math.random() * GRID_SIZE);
} else {
// 移动蛇尾
snake.body.pop();
}
// 移动蛇头
snake.body.unshift({x: headX, y: headY});
}
}
// 判断是否撞到自己
function isCollide(x, y, body) {
for (var i = 0; i < body.length; i++) {
if (x == body[i].x && y == body[i].y) {
return true;
}
}
return false;
}
// 监听键盘事件
document.addEventListener("keydown", function(event) {
switch (event.keyCode) {
case 38: // Up
if (snake.direction != "down") {
snake.direction = "up";
}
break;
case 40: // Down
if (snake.direction != "up") {
snake.direction = "down";
}
break;
case 37: // Left
if (snake.direction != "right") {
snake.direction = "left";
}
break;
case 39: // Right
if (snake.direction != "left") {
snake.direction = "right";
}
break;
}
});
// 游戏循环
var gameInterval = setInterval(function() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制贪吃蛇
drawSnake();
// 绘制食物
drawFood();
// 移动贪吃蛇
moveSnake();
// 显示分数
ctx.fillStyle = "#000";
ctx.fillText("分数:" + (snake.length - 1), 10, 20);
}, 1000 / FPS);
</script>
</body>
</html>
```
这个游戏实现了以下功能:
- 可以使用键盘控制蛇的方向
- 蛇撞墙或撞到自己会游戏结束
- 吃到食物可以增加蛇的长度并重新生成食物
- 显示当前分数