这是HTML代码,用来描述贪吃蛇小游戏页面的结构和内容
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<link rel="stylesheet" type="text/css" href="style-tanchise.css">
</head>
<body>
<div id="game-board">
<div id="snake"></div>
<div id="food"></div>
</div>
<script src="script-tanchishe.js"></script>
</body>
</html>
这是CSS代码,为游戏页面的样式和布局进行描述,这里只做了简单的样式,可以根据自己的需求添加样式
#game-board {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
#snake {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
left: 0;
top: 0;
}
#food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
left: 200px;
top: 200px;
}
这是JS代码,用来设小蛇的动态效果和数据处理等功能,代码上有解析和注释
// 获取游戏区域和蛇、食物元素
const gameBoard = document.getElementById('game-board');
const snakeElement = document.getElementById('snake');
const foodElement = document.getElementById('food');
// 定义蛇的初始位置和移动方向
let snakeX = 0;
let snakeY = 0;
let snakeDirection = 'right';
// 定义食物的初始位置
let foodX = 200;
let foodY = 200;
// 更新蛇的位置
function updateSnake() {
if (snakeDirection === 'right') {
snakeX += 20;
} else if (snakeDirection === 'left') {
snakeX -= 20;
} else if (snakeDirection === 'up') {
snakeY -= 20;
} else if (snakeDirection === 'down') {
snakeY += 20;
}
snakeElement.style.left = snakeX + 'px';
snakeElement.style.top = snakeY + 'px';
}
// 更新食物的位置
//随机数 默认1-10 包头不包围
function updateFood() {
foodX = Math.floor(Math.random() * 20) * 20;
foodY = Math.floor(Math.random() * 20) * 20;
foodElement.style.left = foodX + 'px';
foodElement.style.top = foodY + 'px';
}
// 检查蛇是否吃到了食物
function checkFood() {
if (snakeX === foodX && snakeY === foodY) {
updateFood();
}
}
// 检查蛇是否撞墙或撞到自己
function checkCollision() {
if (snakeX < 0 || snakeX >= 400 || snakeY < 0 || snakeY >= 400) {
clearInterval(gameLoop);
alert('游戏结束!');
}
}
// 处理键盘事件,改变蛇的移动方向
document.addEventListener('keydown', event => {
if (event.key === 'ArrowRight' && snakeDirection !== 'left') {
snakeDirection = 'right';
} else if (event.key === 'ArrowLeft' && snakeDirection !== 'right') {
snakeDirection = 'left';
} else if (event.key === 'ArrowUp' && snakeDirection !== 'down') {
snakeDirection = 'up';
} else if (event.key === 'ArrowDown' && snakeDirection !== 'up') {
snakeDirection = 'down';
}
});
// 游戏循环,每隔一定时间更新蛇和食物的位置,并检查是否吃到食物或撞墙
const gameLoop = setInterval(() => {
updateSnake();
checkFood();
checkCollision();
}, 100);