使用js实现一个贪吃蛇
时间: 2024-01-07 14:02:19 浏览: 33
由于本AI不支持图形界面,因此我提供的是一个控制台版本的贪吃蛇游戏。
```javascript
const readline = require('readline');
// 定义方向常量
const UP = 0;
const RIGHT = 1;
const DOWN = 2;
const LEFT = 3;
// 定义游戏配置
const ROWS = 30; // 行数
const COLS = 50; // 列数
const SPEED = 200; // 蛇移动速度(毫秒)
// 定义游戏变量
let snake = [[1, 1], [1, 2], [1, 3]]; // 蛇的初始位置
let direction = RIGHT; // 蛇的初始方向
let food = null; // 食物位置
// 定义游戏状态
let isGameOver = false;
let score = 0;
// 初始化游戏
function init() {
// 随机放置食物
food = [Math.floor(Math.random() * ROWS), Math.floor(Math.random() * COLS)];
// 清空控制台
console.clear();
// 输出游戏界面
console.log(`Score: ${score}`);
for (let i = 0; i < ROWS; i++) {
let row = '';
for (let j = 0; j < COLS; j++) {
if (i === food[0] && j === food[1]) {
row += 'F'; // 食物
} else if (isSnake(i, j)) {
row += 'S'; // 蛇
} else {
row += '.'; // 空地
}
}
console.log(row);
}
}
// 判断一个位置是否是蛇身
function isSnake(row, col) {
for (let i = 0; i < snake.length; i++) {
if (snake[i][0] === row && snake[i][1] === col) {
return true;
}
}
return false;
}
// 处理用户输入
function handleInput(input) {
switch (input) {
case 'w':
if (direction !== DOWN) {
direction = UP;
}
break;
case 'd':
if (direction !== LEFT) {
direction = RIGHT;
}
break;
case 's':
if (direction !== UP) {
direction = DOWN;
}
break;
case 'a':
if (direction !== RIGHT) {
direction = LEFT;
}
break;
}
}
// 移动蛇
function moveSnake() {
// 根据方向移动蛇头
let head = [...snake[0]];
switch (direction) {
case UP:
head[0]--;
break;
case RIGHT:
head[1]++;
break;
case DOWN:
head[0]++;
break;
case LEFT:
head[1]--;
break;
}
// 如果撞到墙或自己的身体,游戏结束
if (head[0] < 0 || head[0] >= ROWS || head[1] < 0 || head[1] >= COLS || isSnake(head[0], head[1])) {
isGameOver = true;
return;
}
// 如果吃到食物,蛇变长
if (head[0] === food[0] && head[1] === food[1]) {
score++;
snake.unshift(head);
food = [Math.floor(Math.random() * ROWS), Math.floor(Math.random() * COLS)];
} else {
// 否则蛇移动一格
snake.pop();
snake.unshift(head);
}
}
// 主循环
async function mainLoop() {
while (!isGameOver) {
// 等待用户输入
let input = await new Promise(resolve => {
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.once('keypress', (_, key) => {
resolve(key.name);
});
});
handleInput(input);
moveSnake();
init();
await new Promise(resolve => setTimeout(resolve, SPEED));
}
console.log(`Game over! Score: ${score}`);
}
// 启动游戏
mainLoop();
```