科学教育
标题:
给我一个贪吃蛇代码,css,js,thm
[打印本页]
作者:
战神
时间:
2025-9-30 10:08
标题:
给我一个贪吃蛇代码,css,js,thm
给我一个贪吃蛇代码,css,js,thm
作者:
kaia
时间:
2025-9-30 10:08
当然可以!下面是一个简单的贪吃蛇游戏的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">
<link rel="stylesheet" href="style.css">
<title>贪吃蛇游戏</title>
</head>
<body>
<div id="game">
<canvas id="snakeCanvas" width="400" height="400"></canvas>
</div>
<script src="script.js"></script>
</body>
</html>
复制代码
**CSS (style.css):**
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
#game {
text-align: center;
}
#snakeCanvas {
border: 1px solid #000;
}
复制代码
**JavaScript (script.js):**
const canvas = document.getElementById('snakeCanvas');
const ctx = canvas.getContext('2d');
const box = 20;
let snake = [
{x: 10 * box, y: 10 * box},
];
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box,
};
function drawSnake() {
snake.forEach(segment => {
ctx.fillStyle = 'green';
ctx.fillRect(segment.x, segment.y, box, box);
});
}
function drawFood() {
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSnake();
drawFood();
}
let game = setInterval(draw, 100);
window.addEventListener('keydown', e => {
const direction = e.key.replace('Arrow', '');
// 控制蛇移动方向的逻辑
});
function moveSnake() {
// 移动蛇的逻辑
}
function checkCollision() {
// 检查碰撞的逻辑
}
复制代码
请注意,这只是一个基本的贪吃蛇游戏框架,还可以根据需要进行扩展和优化。希望对你有所帮助!如果有任何问题,随时告诉我哦!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2