科学教育
标题:
生成贪吃蛇代码
[打印本页]
作者:
13093851253
时间:
2024-7-22 10:36
标题:
生成贪吃蛇代码
生成贪吃蛇代码
作者:
kaia
时间:
2024-7-22 10:37
好的,小朋友!我们今天来做一个简单的网页贪吃蛇游戏,这个游戏会利用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>
<style>
/* 我们将样式也写在这里 */
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
// 这里是我们的游戏代码
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 游戏的一些变量
let snake = [{x: 50, y: 50}];
let direction = 'RIGHT';
let food = {x: 100, y: 100};
const box = 10;
function drawSnake(){
ctx.fillStyle = 'green';
snake.forEach(part => {
ctx.fillRect(part.x, part.y, box, box);
});
}
function drawFood(){
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
}
function moveSnake(){
let head = {...snake[0]};
if(direction == 'UP') head.y -= box;
if(direction == 'DOWN') head.y += box;
if(direction == 'LEFT') head.x -= box;
if(direction == 'RIGHT') head.x += box;
// 将新头添加到蛇前面
snake.unshift(head);
// 如果吃到食物,就生成新的食物
if(head.x == food.x && head.y == food.y){
food = {
x: Math.floor(Math.random() * (canvas.width / box)) * box,
y: Math.floor(Math.random() * (canvas.height / box)) * box
};
} else {
// 没有吃到食物就移除蛇的最后一节
snake.pop();
}
}
function gameLoop(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSnake();
drawFood();
moveSnake();
setTimeout(gameLoop, 100);
}
// 监听键盘事件,改变蛇的方向
document.addEventListener('keydown', event => {
if(event.keyCode == 37 && direction != 'RIGHT') direction = 'LEFT';
if(event.keyCode == 38 && direction != 'DOWN') direction = 'UP';
if(event.keyCode == 39 && direction != 'LEFT') direction = 'RIGHT';
if(event.keyCode == 40 && direction != 'UP') direction = 'DOWN';
});
// 开始游戏
gameLoop();
</script>
</body>
</html>
复制代码
### 解释一下代码:
1. **HTML部分**:这部分定义了网页的基础结构,包括标题和一个名为`gameCanvas`的画布元素,这个画布是我们绘制贪吃蛇世界的地方。
2. **CSS部分**:这里我们简单设置了一下页面和画布的样式,使画布居中并且添加了一个边框。
3. **JavaScript部分**:
- **变量定义**:`canvas`和`ctx`是用来操作画布的,`snake`是一个数组,记录了每一节蛇的位置,`food`是食物的位置,`box`是每一个小方块的尺寸。
- **绘制函数**:`drawSnake`函数会把蛇画出来,`drawFood`函数会把食物画出来。
- **移动函数**:`moveSnake`函数会根据按键的方向移动蛇,还会判断蛇是否吃到了食物。
- **游戏循环**:`gameLoop`函数会不断调用自己,用来刷新画布上的内容。
- **键盘事件监听**:这部分监听键盘的方向键,改变蛇的移动方向。
你可以把这些代码复制到一个文件里,然后用浏览器打开看看,是不是就能玩到简单的贪吃蛇游戏啦!
希望你玩得开心,有问题的话记得随时来问我哦!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2