科学教育
标题:
关于贪吃蛇代码
[打印本页]
作者:
admin
时间:
2024-7-16 20:23
标题:
关于贪吃蛇代码
可以为我写一个贪吃蛇代码吗?
作者:
kaia
时间:
2024-7-16 20:23
当然可以!让我们一起来写一个简单的贪吃蛇游戏吧。为了让你更好地理解,我们会用HTML、CSS和JavaScript这三种语言来完成这个小项目。
1. **HTML部分(index.html)**:
首先,我们需要一个基本的结构,包含一个画布(canvas),用来绘制我们的游戏。请将以下代码保存为 `index.html` 文件。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>贪吃蛇</title>
<style>
canvas {
background-color: #000;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>
复制代码
2. **CSS部分**:
CSS部分已经在上面的HTML文件里包含了,用于给我们的画布(canvas)一个背景颜色,让它看起来更像是个游戏界面。
3. **JavaScript部分(snake.js)**:
这是最重要的部分,在这里我们将实现在画布上绘制贪吃蛇和控制它运动的逻辑。请将以下代码保存为 `snake.js` 文件。
let canvas = document.getElementById('gameCanvas');
let ctx = canvas.getContext('2d');
const gridSize = 20; // 每个方格的大小
const gridCount = 20; // 网格数量
let snake = [ {x: 10, y: 10} ]; // 蛇的初始位置
let snakeLength = 1; // 蛇的初始长度
let food = {x: 15, y: 15}; // 食物的初始位置
let direction = 'RIGHT'; // 蛇的初始方向
// 绘制游戏场景
function drawGame() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制食物
ctx.fillStyle = 'red';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
// 绘制蛇
ctx.fillStyle = 'lime';
for (let part of snake) {
ctx.fillRect(part.x * gridSize, part.y * gridSize, gridSize, gridSize);
}
// 移动蛇
let head = { x: snake[0].x, y: snake[0].y }; // 获取蛇头的位置
if (direction == 'LEFT') head.x--;
if (direction == 'UP') head.y--;
if (direction == 'RIGHT') head.x++;
if (direction == 'DOWN') head.y++;
// 检查蛇是否吃到食物
if (head.x === food.x && head.y === food.y) {
snakeLength++; // 增加蛇的长度
food = { // 生成新的食物位置
x: Math.floor(Math.random() * gridCount),
y: Math.floor(Math.random() * gridCount)
};
}
// 把新的头部加到蛇上
snake.unshift(head);
// 保持蛇的长度
if (snake.length > snakeLength) {
snake.pop();
}
// 检查蛇是否撞到自己或墙壁
if (head.x < 0 || head.x >= gridCount || head.y < 0 || head.y >= gridCount || isSnakeCollideSelf(snake)) {
alert("游戏结束!");
resetGame();
}
requestAnimationFrame(drawGame); // 不断调用drawGame
}
// 检查蛇是否撞到自己
function isSnakeCollideSelf(snake) {
for (let i = 1; i < snake.length; i++) {
if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
return true;
}
}
return false;
}
// 处理键盘输入
document.addEventListener('keydown', function (event) {
if (event.key === 'ArrowLeft' && direction !== 'RIGHT') direction = 'LEFT';
if (event.key === 'ArrowUp' && direction !== 'DOWN') direction = 'UP';
if (event.key === 'ArrowRight' && direction !== 'LEFT') direction = 'RIGHT';
if (event.key === 'ArrowDown' && direction !== 'UP') direction = 'DOWN';
});
// 重置游戏
function resetGame() {
snake = [ {x: 10, y: 10} ];
snakeLength = 1;
direction = 'RIGHT';
food = {
x: Math.floor(Math.random() * gridCount),
y: Math.floor(Math.random() * gridCount)
};
}
requestAnimationFrame(drawGame); // 开始游戏
复制代码
看,这就是一个简单的贪吃蛇游戏代码。你可以把这些文件放在同一个目录下,然后用浏览器打开 `index.html` 文件,就可以玩这个游戏啦!
有不明白的地方随时问我哦!祝你玩的开心!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2