用js写一个贪吃蛇
时间: 2023-07-16 09:14:25 浏览: 49
好的,以下是一个简单的 JavaScript 贪吃蛇游戏:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
#game-board {
width: 400px;
height: 400px;
border: 1px solid black;
}
.snake {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
}
.food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script src="snake.js"></script>
</body>
</html>
```
JavaScript 代码:
```javascript
// 定义常量
const boardWidth = 20; // 游戏区域宽度
const boardHeight = 20; // 游戏区域高度
const cellWidth = 20; // 蛇身格子宽度
const cellHeight = 20; // 蛇身格子高度
const initialSnakeLength = 3; // 蛇初始长度
const moveInterval = 100; // 蛇移动时间间隔(毫秒)
// 获取游戏区域元素和分数元素
const gameBoard = document.querySelector("#game-board");
const scoreElement = document.createElement("div");
scoreElement.innerText = "分数:0";
gameBoard.appendChild(scoreElement);
// 定义变量
let snake = []; // 蛇的身体,数组中的元素为坐标对象 {x, y}
let food = null; // 食物的坐标对象 {x, y}
let direction = "right"; // 移动方向
let score = 0; // 分数
// 初始化游戏区域
for (let i = 0; i < boardHeight; i++) {
for (let j = 0; j < boardWidth; j++) {
const cell = document.createElement("div");
cell.style.width = cellWidth + "px";
cell.style.height = cellHeight + "px";
cell.style.position = "absolute";
cell.style.top = i * cellHeight + "px";
cell.style.left = j * cellWidth + "px";
gameBoard.appendChild(cell);
}
}
// 初始化蛇
for (let i = 0; i < initialSnakeLength; i++) {
snake.push({ x: i, y: 0 });
}
// 初始化食物
generateFood();
// 开始游戏循环
setInterval(() => {
// 移动蛇
const head = getNextHead();
if (isDead(head)) {
alert("游戏结束,分数:" + score);
location.reload();
return;
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score += 10;
scoreElement.innerText = "分数:" + score;
generateFood();
} else {
snake.pop();
}
// 更新蛇身体的位置
const snakeElements = document.querySelectorAll(".snake");
snake.forEach((cell, index) => {
const snakeElement = snakeElements[index];
snakeElement.style.top = cell.y * cellHeight + "px";
snakeElement.style.left = cell.x * cellWidth + "px";
});
// 更新食物的位置
const foodElement = document.querySelector(".food");
foodElement.style.top = food.y * cellHeight + "px";
foodElement.style.left = food.x * cellWidth + "px";
}, moveInterval);
// 监听键盘事件,控制蛇的移动方向
document.addEventListener("keydown", (event) => {
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;
}
});
// 生成食物的随机位置
function generateFood() {
while (true) {
const x = Math.floor(Math.random() * boardWidth);
const y = Math.floor(Math.random() * boardHeight);
if (!snake.some((cell) => cell.x === x && cell.y === y)) {
food = { x, y };
const foodElement = document.createElement("div");
foodElement.className = "food";
foodElement.style.top = y * cellHeight + "px";
foodElement.style.left = x * cellWidth + "px";
gameBoard.appendChild(foodElement);
break;
}
}
}
// 获取蛇下一步的头部坐标
function getNextHead() {
const currentHead = snake[0];
let nextHead;
switch (direction) {
case "up":
nextHead = { x: currentHead.x, y: currentHead.y - 1 };
break;
case "down":
nextHead = { x: currentHead.x, y: currentHead.y + 1 };
break;
case "left":
nextHead = { x: currentHead.x - 1, y: currentHead.y };
break;
case "right":
nextHead = { x: currentHead.x + 1, y: currentHead.y };
break;
}
return nextHead;
}
// 判断蛇是否死亡
function isDead(head) {
return (
head.x < 0 ||
head.x >= boardWidth ||
head.y < 0 ||
head.y >= boardHeight ||
snake.some((cell) => cell.x === head.x && cell.y === head.y)
);
}
```
现在你可以在浏览器中打开 HTML 文件运行游戏了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)