科学教育
标题:
应妍欣贪吃蛇
[打印本页]
作者:
yyx603
时间:
2025-9-30 09:56
标题:
应妍欣贪吃蛇
帮我生成一个贪吃蛇的网页代码
作者:
kaia
时间:
2025-9-30 09:56
当然可以帮你生成一个简单的贪吃蛇游戏的网页代码。以下是一个基础的示例:
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
body {
background-color: black;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
#game-board {
width: 400px;
height: 400px;
border: 1px solid white;
}
.snake {
width: 20px;
height: 20px;
background-color: green;
}
#food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script>
const gameBoard = document.getElementById('game-board');
let snake = [{x: 200, y: 200}];
let food = {x: 0, y: 0};
function draw() {
gameBoard.innerHTML = '';
snake.forEach(segment => {
const snakeElement = document.createElement('div');
snakeElement.style.gridColumn = `${segment.x / 20}`;
snakeElement.style.gridRow = `${segment.y / 20}`;
snakeElement.classList.add('snake');
gameBoard.appendChild(snakeElement);
});
const foodElement = document.createElement('div');
foodElement.style.gridColumn = `${food.x / 20}`;
foodElement.style.gridRow = `${food.y / 20}`;
foodElement.setAttribute('id', 'food');
gameBoard.appendChild(foodElement);
}
function getRandomPosition() {
return Math.floor(Math.random() * 20) * 20;
}
function update() {
const head = { ...snake[0] };
if (head.x === food.x && head.y === food.y) {
snake.push({});
food.x = getRandomPosition();
food.y = getRandomPosition();
}
for (let i = snake.length - 1; i >= 0; i--) {
if (i === 0) {
if (direction === 'up') head.y -= 20;
if (direction === 'down') head.y += 20;
if (direction === 'left') head.x -= 20;
if (direction === 'right') head.x += 20;
} else {
snake[i] = { ...snake[i - 1] };
}
}
draw();
}
document.addEventListener('keydown', e => {
if (e.key === 'ArrowUp' && direction !== 'down') direction = 'up';
if (e.key === 'ArrowDown' && direction !== 'up') direction = 'down';
if (e.key === 'ArrowLeft' && direction !== 'right') direction = 'left';
if (e.key === 'ArrowRight' && direction !== 'left') direction = 'right';
});
let direction = 'right';
setInterval(update, 100);
</script>
</body>
</html>
复制代码
这个代码创建了一个简单的贪吃蛇游戏,玩家可通过方向键控制蛇的移动。在游戏中,绿色方块代表蛇身,红色方块代表食物。当蛇吃到食物时,会增加长度。希望你玩得开心!记得在浏览器中打开这个网页来尽情玩耍。如果有任何问题,都可以继续问我哦!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2