记事本编程贪吃蛇
时间: 2025-06-21 15:57:18 浏览: 5
### 用记事本编写贪吃蛇游戏代码
使用记事本编写贪吃蛇游戏是一种简单且直接的方式。以下是一个基于JavaScript和HTML的实现方案,用户可以将代码复制到记事本中,并保存为`.html`文件以运行游戏。
#### HTML与JavaScript结合实现贪吃蛇游戏
以下代码展示了如何使用63行HTML5和JavaScript代码实现一个简单的贪吃蛇游戏[^3]。此代码可以在任何支持HTML5的浏览器中运行。
```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>
canvas {
display: block;
margin: 0 auto;
background: #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: 10, y: 10}];
let food = {x: 15, y: 15};
let dx = 0, dy = 0;
function drawSnake() {
ctx.fillStyle = '#fff';
snake.forEach(part => {
ctx.fillRect(part.x * 10, part.y * 10, 10, 10);
});
}
function drawFood() {
ctx.fillStyle = 'red';
ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
}
function moveSnake() {
const head = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
food = {x: Math.floor(Math.random() * 40), y: Math.floor(Math.random() * 40)};
} else {
snake.pop();
}
}
function checkCollision() {
const head = snake[0];
if (head.x < 0 || head.x >= 40 || head.y < 0 || head.y >= 40) {
alert('游戏结束!');
clearInterval(interval);
}
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSnake();
drawFood();
moveSnake();
checkCollision();
}
document.addEventListener('keydown', event => {
switch (event.key) {
case 'ArrowUp': dx = 0; dy = -1; break;
case 'ArrowDown': dx = 0; dy = 1; break;
case 'ArrowLeft': dx = -1; dy = 0; break;
case 'ArrowRight': dx = 1; dy = 0; break;
}
});
const interval = setInterval(gameLoop, 100);
</script>
</body>
</html>
```
#### 使用步骤
1. 将上述代码复制到记事本中。
2. 点击记事本左上角的“文件”菜单,选择“另存为”。
3. 在保存类型中选择“所有文件”,并将文件名命名为`youxi.html`。
4. 保存后,双击生成的HTML文件即可运行游戏[^1]。
#### 注意事项
- 确保计算机已安装支持HTML5的现代浏览器(如Chrome、Firefox等)。
- 如果需要扩展功能,例如增加计分板或更复杂的逻辑,可以参考Python中的函数设计思路[^2]。
###
阅读全文
相关推荐
















