用JavaScript写一个贪吃蛇
时间: 2023-03-27 22:04:36 浏览: 78
好的,我可以给你一个JavaScript贪吃蛇的示例代码:
```
<!DOCTYPE html>
<html>
<head>
<style>
#game-board {
width: 500px;
height: 500px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script>
const board = document.getElementById("game-board");
const ctx = board.getContext("2d");
let snake = [];
let food = {};
let score = 0;
let direction = "right";
for (let i = 0; i < 5; i++) {
snake.push({x: i, y: 0});
}
function createFood() {
food = {
x: Math.floor(Math.random() * (board.width / 10)),
y: Math.floor(Math.random() * (board.height / 10)),
};
for (let i = 0; i < snake.length; i++) {
if (food.x === snake[i].x && food.y === snake[i].y) {
createFood();
}
}
}
function drawSnake() {
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? "red" : "green";
ctx.fillRect(
snake[i].x * 10,
snake[i].y * 10,
10,
10
);
}
}
function updateSnake() {
let x = snake[0].x;
let y = snake[0].y;
if (direction === "right") {
x++;
} else if (direction === "left") {
x--;
} else if (direction === "up") {
y--;
} else if (direction === "down") {
y++;
}
if (x < 0 || x >= board.width / 10 || y < 0 || y >= board.height / 10) {
alert("Game Over");
window.location.reload();
}
if (x === food.x && y === food.y) {
score++;
createFood();
} else {
snake.pop();
}
snake.unshift({x: x, y: y});
}
function drawFood() {
ctx.fillStyle = "yellow";
ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
}
function drawScore() {
ctx.fillStyle = "black";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, board.height - 10);
}
document.onkeydown = function (e) {
if (e.keyCode === 37 && direction !== "right") {
direction = "left";
}
阅读全文