科学教育
标题:
叶梦昕贪吃蛇
[打印本页]
作者:
叶梦昕
时间:
2025-9-30 15:27
标题:
叶梦昕贪吃蛇
帮我生成一个贪吃蛇网页代码,用html.css.js
作者:
kaia
时间:
2025-9-30 15:28
当我们创建一个简单的贪吃蛇游戏,需要使用HTML、CSS和JavaScript来实现。下面是一个简单的示例代码:
首先是HTML代码(index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇游戏</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="gameArea">
<div id="snake"></div>
<div id="food"></div>
</div>
<script src="script.js"></script>
</body>
</html>
复制代码
接着是CSS代码(style.css):
#gameArea {
width: 400px;
height: 400px;
border: 1px solid #000;
position: relative;
}
#snake, #food {
width: 10px;
height: 10px;
background-color: green;
position: absolute;
}
#snake {
background-color: green;
}
#food {
background-color: red;
}
复制代码
最后是JavaScript代码(script.js):
let snake = [{x: 200, y: 200}];
let direction = 'right';
function createFood() {
let x = Math.floor(Math.random() * 40) * 10;
let y = Math.floor(Math.random() * 40) * 10;
let food = document.getElementById('food');
food.style.left = x + 'px';
food.style.top = y + 'px';
}
function updateSnake() {
let head = { x: snake[0].x, y: snake[0].y };
if (direction === 'right') {
head.x += 10;
} else if (direction === 'left') {
head.x -= 10;
} else if (direction === 'up') {
head.y -= 10;
} else if (direction === 'down') {
head.y += 10;
}
snake.unshift(head);
snake.pop();
let snakeElement = document.getElementById('snake');
snakeElement.style.left = snake[0].x + 'px';
snakeElement.style.top = snake[0].y + 'px';
}
createFood();
setInterval(updateSnake, 100);
复制代码
这个示例只包含了基本的贪吃蛇游戏功能,你可以根据自己的需求对游戏进行扩展和优化。希望对你有帮助!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2