科学教育
标题:
贪吃蛇游戏
[打印本页]
作者:
QianJY
时间:
2025-9-30 09:41
标题:
贪吃蛇游戏
帮我生成一个贪吃蛇游戏的网页代码
作者:
kaia
时间:
2025-9-30 09:41
当我们创建一个贪吃蛇游戏网页时,通常会使用 HTML、CSS 和 JavaScript 来实现游戏的界面和逻辑。下面是一个简单的贪吃蛇游戏的网页代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
<div id="game-board"></div>
<script>
const board = document.getElementById('game-board');
let snake = [{ x: 200, y: 200 }];
let food = { x: 0, y: 0 };
let direction = 'right';
function createSnake() {
snake.forEach(segment => {
const snakeElement = document.createElement('div');
snakeElement.style.left = segment.x + 'px';
snakeElement.style.top = segment.y + 'px';
snakeElement.classList.add('snake');
board.appendChild(snakeElement);
});
}
function updateSnake() {
const head = { x: snake[0].x, y: snake[0].y };
switch (direction) {
case 'up':
head.y -= 20;
break;
case 'down':
head.y += 20;
break;
case 'left':
head.x -= 20;
break;
case 'right':
head.x += 20;
break;
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
generateFood();
} else {
snake.pop();
}
}
function generateFood() {
food.x = Math.floor(Math.random() * 20) * 20;
food.y = Math.floor(Math.random() * 20) * 20;
const foodElement = document.createElement('div');
foodElement.style.left = food.x + 'px';
foodElement.style.top = food.y + 'px';
foodElement.classList.add('food');
board.appendChild(foodElement);
}
function gameLoop() {
updateSnake();
render();
}
function render() {
const boardChildren = Array.from(board.children);
boardChildren.forEach(child => child.remove());
createSnake();
}
generateFood();
createSnake();
setInterval(gameLoop, 100);
</script>
</body>
</html>
复制代码
这段代码创建了一个简单的贪吃蛇游戏界面,玩家可以控制蛇的移动方向,吃到食物会变长。游戏会定时更新蛇的位置并重新渲染在页面上。你可以把这段代码复制粘贴到一个新建的 HTML 文件中,用浏览器打开就可以看到这个简单的贪吃蛇游戏了。如果想要添加更多功能和特效,可以继续扩展这个基础版本。希望你能享受编程的乐趣!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2