html贪吃蛇游戏
时间: 2023-07-05 21:16:12 浏览: 101
好的,HTML贪吃蛇游戏可以通过HTML、CSS和JavaScript实现。以下是一个简单的实现:
HTML部分:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>贪吃蛇游戏</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
```
CSS部分:
```
body {
background-color: black;
}
canvas {
margin: 0 auto;
display: block;
background-color: white;
}
```
JavaScript部分:
```
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var snake = [{x: 10, y: 10}];
var direction = "right";
var food = {x: Math.floor(Math.random() * 40), y: Math.floor(Math.random() * 40)};
var score = 0;
document.addEventListener("keydown", function(event) {
if (event.keyCode === 37 && direction !== "right") {
direction = "left";
} else if (event.keyCode === 38 && direction !== "down") {
direction = "up";
} else if (event.keyCode === 39 && direction !== "left") {
direction = "right";
} else if (event.keyCode === 40 && direction !== "up") {
direction = "down";
}
});
function drawSnake() {
ctx.fillStyle = "green";
ctx.fillRect(snake[0].x * 10, snake[0].y * 10, 10, 10);
for (var i = 1; i < snake.length; i++) {
ctx.fillStyle = "lightgreen";
ctx.fillRect(snake[i].x * 10, snake[i].y * 10, 10, 10);
}
}
function moveSnake() {
var head = snake[0];
if (direction === "right") {
var newHead = {x: head.x + 1, y: head.y};
} else if (direction === "left") {
var newHead = {x: head.x - 1, y: head.y};
} else if (direction === "up") {
var newHead = {x: head.x, y: head.y - 1};
} else if (direction === "down") {
var newHead = {x: head.x, y: head.y + 1};
}
snake.unshift(newHead);
if (newHead.x === food.x && newHead.y === food.y) {
score++;
food = {x: Math.floor(Math.random() * 40), y: Math.floor(Math.random() * 40)};
} else {
snake.pop();
}
}
function drawFood() {
ctx.fillStyle = "red";
ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
}
function drawScore() {
ctx.fillStyle = "white";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, 30);
}
function gameOver() {
clearInterval(game);
ctx.fillStyle = "white";
ctx.font = "40px Arial";
ctx.fillText("Game Over", 100, 200);
}
function checkCollision() {
var head = snake[0];
if (head.x < 0 || head.x > 39 || head.y < 0 || head.y > 39) {
gameOver();
}
for (var i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver();
}
}
}
function gameLoop() {
ctx.clearRect(0, 0, 400, 400);
drawSnake();
moveSnake();
drawFood();
drawScore();
checkCollision();
}
var game = setInterval(gameLoop, 100);
```
这个实现中,canvas元素被用来绘制游戏画面,JavaScript代码实现了贪吃蛇的移动、食物的生成和得分的计算。通过keydown事件监听用户的按键操作,控制贪吃蛇的方向。如果发生碰撞,游戏结束,通过clearInterval函数停止游戏循环。
阅读全文