科学教育
标题:
贪吃蛇代码
[打印本页]
作者:
13758623687
时间:
2024-7-17 11:20
标题:
贪吃蛇代码
请生成一个贪吃蛇游戏的代码
作者:
kaia
时间:
2024-7-17 11:21
当然可以!贪吃蛇游戏是一个很有趣的项目,我们可以用HTML、CSS和JavaScript来实现。下面我会一步一步地给你讲解每一部分代码。
### 1. HTML 部分
首先,我们需要一个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>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
复制代码
### 2. CSS 部分
接下来,我们写一些简单的CSS来让画布看起来更好看一些。
/* style.css */
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
canvas {
border: 1px solid #000;
}
复制代码
### 3. JavaScript 部分
最后,这是我们的主要部分,也就是贪吃蛇的逻辑部分。
// script.js
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 设置常量
const unit = 20;
let snake = [{ x: 80, y: 80 }];
let food = { x: 160, y: 160 };
let direction = 'RIGHT';
let changingDirection = false;
let score = 0;
// 控制方向
document.addEventListener('keydown', changeDirection);
function main() {
if (checkGameOver()) return;
changingDirection = false;
setTimeout(() => {
clearCanvas();
drawFood();
moveSnake();
drawSnake();
main();
}, 100);
}
function clearCanvas() {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawSnake() {
ctx.fillStyle = 'lightgreen';
ctx.strokeStyle = 'darkgreen';
snake.forEach(segment => {
ctx.fillRect(segment.x, segment.y, unit, unit);
ctx.strokeRect(segment.x, segment.y, unit, unit);
});
}
function drawFood() {
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, unit, unit);
}
function moveSnake() {
const head = { x: snake[0].x, y: snake[0].y };
switch (direction) {
case 'UP':
head.y -= unit;
break;
case 'DOWN':
head.y += unit;
break;
case 'LEFT':
head.x -= unit;
break;
case 'RIGHT':
head.x += unit;
break;
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score += 10;
generateFood();
} else {
snake.pop();
}
}
function changeDirection(event) {
if (changingDirection) return;
changingDirection = true;
const keyPressed = event.keyCode;
const UP_KEY = 38;
const DOWN_KEY = 40;
const LEFT_KEY = 37;
const RIGHT_KEY = 39;
const goingUp = direction === 'UP';
const goingDown = direction === 'DOWN';
const goingRight = direction === 'RIGHT';
const goingLeft = direction === 'LEFT';
if (keyPressed === UP_KEY && !goingDown) {
direction = 'UP';
}
if (keyPressed === DOWN_KEY && !goingUp) {
direction = 'DOWN';
}
if (keyPressed === LEFT_KEY && !goingRight) {
direction = 'LEFT';
}
if (keyPressed === RIGHT_KEY && !goingLeft) {
direction = 'RIGHT';
}
}
function checkGameOver() {
for (let i = 4; i < snake.length; i++) {
if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) return true;
}
const hitLeftWall = snake[0].x < 0;
const hitRightWall = snake[0].x >= canvas.width;
const hitToptWall = snake[0].y < 0;
const hitBottomWall = snake[0].y >= canvas.height;
return hitLeftWall || hitRightWall || hitToptWall || hitBottomWall;
}
function generateFood() {
food.x = Math.floor(Math.random() * canvas.width / unit) * unit;
food.y = Math.floor(Math.random() * canvas.height / unit) * unit;
snake.forEach(segment => {
if (segment.x === food.x && segment.y === food.y) {
generateFood();
}
});
}
main();
复制代码
### 总结
1. **HTML**定义了画布,用来显示游戏。
2. **CSS**简单地美化了画布。
3. **JavaScript**负责游戏的逻辑,包括蛇的移动、食物的生成、碰撞检测等。
你可以将这些代码分别保存到不同的文件中:`index.html`、`style.css`、`script.js`。打开`index.html`,就能在浏览器中玩这个简单的贪吃蛇游戏了!
希望你能喜欢这个游戏,祝你编程愉快!如果有任何问题,请随时问我哦!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2