用js写个贪吃蛇
时间: 2023-09-15 14:21:30 浏览: 45
好的,以下是用 JavaScript 写的贪吃蛇游戏的代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
var box = 20;
var snake = [];
snake[0] = {x: 9 * box, y: 10 * box};
var food = {x: Math.floor(Math.random() * 20) * box, y: Math.floor(Math.random() * 20) * box};
var score = 0;
var d;
document.addEventListener("keydown", direction);
function direction(event) {
if (event.keyCode == 37 && d != "RIGHT") {
d = "LEFT";
} else if (event.keyCode == 38 && d != "DOWN") {
d = "UP";
} else if (event.keyCode == 39 && d != "LEFT") {
d = "RIGHT";
} else if (event.keyCode == 40 && d != "UP") {
d = "DOWN";
}
}
function collision(head, array) {
for (var i = 0; i < array.length; i++) {
if (head.x == array[i].x && head.y == array[i].y) {
return true;
}
}
return false;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "green";
for (var i = 0; i < snake.length; i++) {
ctx.fillRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
var snakeX = snake[0].x;
var snakeY = snake[0].y;
if (d == "LEFT") snakeX -= box;
if (d == "UP") snakeY -= box;
if (d == "RIGHT") snakeX += box;
if (d == "DOWN") snakeY += box;
if (snakeX == food.x && snakeY == food.y) {
score++;
food = {x: Math.floor(Math.random() * 20) * box, y: Math.floor(Math.random() * 20) * box};
} else {
snake.pop();
}
var newHead = {x: snakeX, y: snakeY};
if (snakeX < 0 || snakeX >= canvas.width || snakeY < 0 || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
}
snake.unshift(newHead);
ctx.fillStyle = "white";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, 30);
}
var game = setInterval(draw, 100);
</script>
</body>
</html>
```
你可以将这段代码复制到你的本地计算机上,然后用浏览器打开它,就可以玩这个 JavaScript 贪吃蛇游戏了。