写一个贪吃蛇小游戏
时间: 2024-01-05 07:03:37 浏览: 73
贪吃蛇小游戏..
好的,以下是一个简单的贪吃蛇小游戏的代码示例,使用HTML、CSS和JavaScript编写。
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>贪吃蛇小游戏</title>
<style>
#game-board {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
.snake {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
}
.food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<h1>贪吃蛇小游戏</h1>
<div id="game-board"></div>
<script src="snake.js"></script>
</body>
</html>
```
JavaScript代码:
```javascript
// 获取游戏面板元素和其宽度和高度
const gameBoard = document.getElementById('game-board');
const width = gameBoard.offsetWidth;
const height = gameBoard.offsetHeight;
// 初始化贪吃蛇和食物
let snake = [{x: 0, y: 0}];
let food = {x: 0, y: 0};
let direction = '';
// 创建贪吃蛇和食物的元素并添加到游戏面板中
function render() {
gameBoard.innerHTML = '';
snake.forEach((segment, index) => {
const snakeElement = document.createElement('div');
snakeElement.classList.add('snake');
snakeElement.style.left = segment.x + 'px';
snakeElement.style.top = segment.y + 'px';
gameBoard.appendChild(snakeElement);
});
const foodElement = document.createElement('div');
foodElement.classList.add('food');
foodElement.style.left = food.x + 'px';
foodElement.style.top = food.y + 'px';
gameBoard.appendChild(foodElement);
}
// 生成随机位置的食物
function generateFood() {
food.x = Math.floor(Math.random() * (width - 20));
food.y = Math.floor(Math.random() * (height - 20));
}
// 监听键盘事件,控制贪吃蛇的移动方向
document.addEventListener('keydown', event => {
if (event.key === 'ArrowUp') {
direction = 'up';
} else if (event.key === 'ArrowDown') {
direction = 'down';
} else if (event.key === 'ArrowLeft') {
direction = 'left';
} else if (event.key === 'ArrowRight') {
direction = 'right';
}
});
// 定时器控制贪吃蛇的移动
setInterval(() => {
// 根据方向移动贪吃蛇
if (direction === 'up') {
snake.unshift({x: snake[0].x, y: snake[0].y - 20});
} else if (direction === 'down') {
snake.unshift({x: snake[0].x, y: snake[0].y + 20});
} else if (direction === 'left') {
snake.unshift({x: snake[0].x - 20, y: snake[0].y});
} else if (direction === 'right') {
snake.unshift({x: snake[0].x + 20, y: snake[0].y});
}
// 判断是否吃到了食物,是则加分并生成新的食物
if (snake[0].x === food.x && snake[0].y === food.y) {
generateFood();
} else {
snake.pop();
}
// 判断是否撞墙或撞到自己,是则游戏结束
if (snake[0].x < 0 || snake[0].x >= width ||
snake[0].y < 0 || snake[0].y >= height ||
snake.slice(1).some(segment => segment.x === snake[0].x && segment.y === snake[0].y)) {
alert('游戏结束!');
location.reload();
}
// 更新游戏面板
render();
}, 100);
```
以上是一个简单的贪吃蛇小游戏的代码示例,你可以根据自己的需要进行修改和优化,添加更多的游戏功能和特效。
阅读全文