给我生成一个网页版的贪食蛇
时间: 2024-03-17 11:43:56 浏览: 15
好的,您可以参考以下代码实现一个简单的网页版贪吃蛇游戏:
HTML 代码:
```
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body>
<h1>贪吃蛇游戏</h1>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>
```
JavaScript 代码(snake.js):
```
// 获取 canvas 元素
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 定义贪吃蛇的属性
var snake = {
x: 10,
y: 10,
size: 20,
dx: 0,
dy: 0,
cells: [],
maxCells: 4
};
// 定义食物的属性
var food = {
x: Math.floor(Math.random() * 20),
y: Math.floor(Math.random() * 20),
size: 20
};
// 定义游戏的属性
var score = 0;
var gameOver = false;
// 监听键盘事件
document.addEventListener("keydown", function(e) {
if (e.keyCode === 37 && snake.dx === 0) {
snake.dx = -snake.size;
snake.dy = 0;
}
else if (e.keyCode === 38 && snake.dy === 0) {
snake.dy = -snake.size;
snake.dx = 0;
}
else if (e.keyCode === 39 && snake.dx === 0) {
snake.dx = snake.size;
snake.dy = 0;
}
else if (e.keyCode === 40 && snake.dy === 0) {
snake.dy = snake.size;
snake.dx = 0;
}
});
// 游戏循环
function loop() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 移动贪吃蛇
snake.x += snake.dx;
snake.y += snake.dy;
// 判断是否撞墙
if (snake.x < 0 || snake.x > canvas.width - snake.size || snake.y < 0 || snake.y > canvas.height - snake.size) {
gameOver = true;
}
// 添加新的贪吃蛇身体
snake.cells.unshift({x: snake.x, y: snake.y});
// 移除多余的贪吃蛇身体
if (snake.cells.length > snake.maxCells) {
snake.cells.pop();
}
// 绘制食物
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, food.size, food.size);
// 绘制贪吃蛇
ctx.fillStyle = "green";
snake.cells.forEach(function(cell, index) {
ctx.fillRect(cell.x, cell.y, snake.size, snake.size);
// 判断是否吃到食物
if (cell.x === food.x && cell.y === food.y) {
score++;
snake.maxCells++;
food.x = Math.floor(Math.random() * 20);
food.y = Math.floor(Math.random() * 20);
}
// 判断是否撞到自己
for (var i = index + 1; i < snake.cells.length; i++) {
if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
gameOver = true;
}
}
});
// 绘制分数
ctx.fillStyle = "black";
ctx.fillText("Score: " + score, 10, canvas.height - 10);
// 判断游戏是否结束
if (gameOver) {
clearInterval(intervalId);
ctx.fillStyle = "red";
ctx.fillText("Game Over", canvas.width/2 - 30, canvas.height/2);
}
}
// 启动游戏
var intervalId = setInterval(loop, 100);
```
您可以将以上代码保存为 `index.html` 和 `snake.js`,然后在浏览器中打开 `index.html` 文件即可开始游戏。