用html+css+javascript写一个贪吃蛇游戏
时间: 2023-05-14 07:05:18 浏览: 182
好的,我可以为您提供一个基于 HTML、CSS 和 JavaScript 的贪吃蛇游戏的代码示例。以下是代码:
HTML:
```
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
#game-board {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
.snake {
width: 10px;
height: 10px;
background-color: green;
position: absolute;
}
.food {
width: 10px;
height: 10px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script src="snake.js"></script>
</body>
</html>
```
JavaScript:
```
var gameBoard = document.getElementById("game-board");
var snake = [{x: 10, y: 10}];
var direction = "right";
var food = {x: 0, y: 0};
function drawSnake() {
for (var i = 0; i < snake.length; i++) {
var snakeElement = document.createElement("div");
snakeElement.className = "snake";
snakeElement.style.left = snake[i].x + "px";
snakeElement.style.top = snake[i].y + "px";
gameBoard.appendChild(snakeElement);
}
}
function drawFood() {
var foodElement = document.createElement("div");
foodElement.className = "food";
foodElement.style.left = food.x + "px";
foodElement.style.top = food.y + "px";
gameBoard.appendChild(foodElement);
}
function moveSnake() {
var head = snake[0];
var newHead = {x: head.x, y: head.y};
if (direction === "right") {
newHead.x += 10;
} else if (direction === "left") {
newHead.x -= 10;
} else if (direction === "up") {
newHead.y -= 10;
} else if (direction === "down") {
newHead.y += 10;
}
snake.unshift(newHead);
snake.pop();
}
function checkCollision() {
var head = snake[0];
if (head.x < 0 || head.x >= 400 || head.y < 0 || head.y >= 400) {
return true;
}
for (var i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
return true;
}
}
return false;
}
function checkFood() {
var head = snake[0];
if (head.x === food.x && head.y === food.y) {
snake.push(snake[snake.length - 1]);
food.x = Math.floor(Math.random() * 40) * 10;
food.y = Math.floor(Math.random() * 40) * 10;
}
}
function update() {
moveSnake();
if (checkCollision()) {
clearInterval(intervalId);
alert("游戏结束!");
return;
}
checkFood();
gameBoard.innerHTML = "";
drawSnake();
drawFood();
}
function handleKeyDown(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";
}
}
document.addEventListener("keydown", handleKeyDown);
food.x = Math.floor(Math.random() * 40) * 10;
food.y = Math.floor(Math.random() * 40) * 10;
drawSnake();
drawFood();
var intervalId = setInterval(update, 100);
```
请注意,此代码仅供参考,可能存在错误或不完整之处。
阅读全文