科学教育
标题:
汪义博贪吃蛇
[打印本页]
作者:
汪义博
时间:
2025-10-14 13:59
标题:
汪义博贪吃蛇
帮我生成一个贪吃蛇网页代码
作者:
kaia
时间:
2025-10-14 13:59
当你玩贪吃蛇游戏时,其实是一个小蛇在地图上不断移动,吃食物,长大。我们可以使用HTML、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>
#gameCanvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>
复制代码
接下来,创建一个JavaScript文件`snake.js`,在里面编写贪吃蛇的游戏逻辑:
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const box = 20;
let snake = [{x: 10, y: 10}];
let food = {x: Math.floor(Math.random() * 20) * box, y: Math.floor(Math.random() * 20) * box};
let score = 0;
let dir = "right";
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制蛇
snake.forEach(segment => {
ctx.fillStyle = "green";
ctx.fillRect(segment.x, segment.y, box, box);
});
// 绘制食物
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
// 绘制得分
ctx.fillStyle = "black";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, 30);
}
function moveSnake() {
const head = {x: snake[0].x, y: snake[0].y};
// 根据方向移动蛇头
if (dir === "up") head.y -= box;
if (dir === "down") head.y += box;
if (dir === "left") head.x -= box;
if (dir === "right") head.x += box;
// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
score++;
food = {x: Math.floor(Math.random() * 20) * box, y: Math.floor(Math.random() * 20) * box};
} else {
snake.pop(); // 移除蛇尾
}
// 添加新的蛇头
snake.unshift(head);
// 检查游戏结束条件
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height || checkCollision()) {
clearInterval(game);
alert("Game Over! Your score: " + score);
}
}
function checkCollision() {
return snake.slice(1).some(segment => segment.x === snake[0].x && segment.y === snake[0].y);
}
document.addEventListener("keydown", event => {
const key = event.keyCode;
if (key === 37 && dir !== "right") dir = "left";
if (key === 38 && dir !== "down") dir = "up";
if (key === 39 && dir !== "left") dir = "right";
if (key === 40 && dir !== "up") dir = "down";
});
let game = setInterval(() => {
moveSnake();
draw();
}, 100);
复制代码
以上代码实现了一个简单的贪吃蛇游戏,游戏会不断运行,玩家可以使用键盘上的方向键来控制蛇的移动方向,吃到食物后蛇会变长,当蛇头碰到墙壁或自身时,游戏结束并弹出得分提示。
你可以将这段代码保存为`index.html`和`snake.js`文件,然后用浏览器打开`index.html`文件,就可以开始玩自己生成的贪吃蛇游戏啦!希望你玩得开心!如果有什么问题,再来问我哦!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2