帮我写个贪吃蛇小游戏,要求可以使用浏览器运行
时间: 2024-01-01 15:06:25 浏览: 142
好的,我可以给你一个简单的贪吃蛇小游戏代码,使用 HTML、CSS 和 JavaScript 编写,可以在浏览器中运行。
HTML 代码:
```
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇小游戏</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="snake" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>
```
CSS 代码:
```
canvas {
border: 1px solid #000;
}
```
JavaScript 代码:
```
var canvas = document.getElementById("snake");
var context = canvas.getContext("2d");
var grid = 16;
var count = 0;
var snake = {
x: 160,
y: 160,
dx: grid,
dy: 0,
cells: [],
maxCells: 4,
};
var apple = {
x: 320,
y: 320,
};
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function loop() {
requestAnimationFrame(loop);
if (++count < 4) {
return;
}
count = 0;
context.clearRect(0, 0, canvas.width, canvas.height);
snake.x += snake.dx;
snake.y += snake.dy;
if (snake.x < 0) {
snake.x = canvas.width - grid;
} else if (snake.x >= canvas.width) {
snake.x = 0;
}
if (snake.y < 0) {
snake.y = canvas.height - grid;
} else if (snake.y >= canvas.height) {
snake.y = 0;
}
snake.cells.unshift({ x: snake.x, y: snake.y });
if (snake.cells.length > snake.maxCells) {
snake.cells.pop();
}
context.fillStyle = "green";
context.fillRect(apple.x, apple.y, grid - 1, grid - 1);
context.fillStyle = "yellow";
snake.cells.forEach(function (cell, index) {
context.fillRect(cell.x, cell.y, grid - 1, grid - 1);
if (cell.x === apple.x && cell.y === apple.y) {
snake.maxCells++;
apple.x = getRandomInt(0, 25) * grid;
apple.y = getRandomInt(0, 25) * grid;
}
for (var i = index + 1; i < snake.cells.length; i++) {
if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
snake.x = 160;
snake.y = 160;
snake.cells = [];
snake.maxCells = 4;
snake.dx = grid;
snake.dy = 0;
apple.x = getRandomInt(0, 25) * grid;
apple.y = getRandomInt(0, 25) * grid;
}
}
});
}
document.addEventListener("keydown", function (e) {
if (e.which === 37 && snake.dx === 0) {
snake.dx = -grid;
snake.dy = 0;
} else if (e.which === 38 && snake.dy === 0) {
snake.dy = -grid;
snake.dx = 0;
} else if (e.which === 39 && snake.dx === 0) {
snake.dx = grid;
snake.dy = 0;
} else if (e.which === 40 && snake.dy === 0) {
snake.dy = grid;
snake.dx = 0;
}
});
requestAnimationFrame(loop);
```
你可以将以上代码保存在同一目录下的三个文件中:`index.html`、`style.css` 和 `snake.js`。然后在浏览器中打开 `index.html` 文件,就可以开始玩贪吃蛇小游戏了。
阅读全文