科学教育
标题:
陈宇硕贪吃蛇
[打印本页]
作者:
金陈宇硕
时间:
2025-9-30 15:27
标题:
陈宇硕贪吃蛇
帮我生成一个贪吃蛇游戏
作者:
kaia
时间:
2025-9-30 15:27
当我们创建一个贪吃蛇游戏时,需要用到HTML、CSS和JavaScript。在HTML中,我们会创建一个画布(<canvas>元素),在CSS中设置一些样式,比如画布的大小和颜色,最后在JavaScript中编写游戏逻辑。
首先,在HTML文件中添加以下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇游戏</title>
<style>
canvas {
border: 1px solid #333;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>
复制代码
然后,在同一目录下创建一个名为`snake.js`的JavaScript文件,并添加以下代码:
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20;
let snake = [{ x: 10 * box, y: 10 * box }];
let food = { x: Math.floor(Math.random() * 19) * box, y: Math.floor(Math.random() * 19) * box };
let direction = 'right';
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制蛇身
ctx.fillStyle = 'green';
snake.forEach(p => ctx.fillRect(p.x, p.y, box, box));
// 绘制食物
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
// 移动蛇头
let newX = snake[0].x;
let newY = snake[0].y;
if (direction === 'left') newX -= box;
if (direction === 'right') newX += box;
if (direction === 'up') newY -= box;
if (direction === 'down') newY += box;
// 判断是否吃到食物
if (newX === food.x && newY === food.y) {
snake.unshift({ x: newX, y: newY });
food = { x: Math.floor(Math.random() * 19) * box, y: Math.floor(Math.random() * 19) * box };
} else {
snake.pop();
snake.unshift({ x: newX, y: newY });
}
}
function changeDirection(event) {
const key = event.keyCode;
if (key === 37 && direction !== 'right') direction = 'left';
if (key === 38 && direction !== 'down') direction = 'up';
if (key === 39 && direction !== 'left') direction = 'right';
if (key === 40 && direction !== 'up') direction = 'down';
}
document.addEventListener('keydown', changeDirection);
setInterval(draw, 100);
复制代码
这段代码实现了基本的贪吃蛇游戏功能,包括蛇的移动、吃食物等。你可以打开浏览器,加载HTML文件,就可以看到生成的贪吃蛇游戏了。尝试控制蛇的方向,让蛇吃到食物,看看能得多少分吧!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2