写出一款网页贪吃蛇游戏的代码
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
#game-board {
width: 600px;
height: 600px;
border: 1px solid black;
}
<pre><code> .snake {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
}
.food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</code></pre>
</head>
<body>
<h1>贪吃蛇游戏</h1>
<p>使用方向键控制蛇的移动,吃到食物可以增加长度</p>
<div id="game-board"></div>
<script>
const board = document.getElementById("game-board");
const blockWidth = 20;
const blockHeight = 20;
const boardWidth = board.offsetWidth;
const boardHeight = board.offsetHeight;
const snake = [{ x: 0, y: 0 }];
let food = null;
let direction = "right";
let intervalId = null;
<pre><code> function createBlock(x, y, className) {
const block = document.createElement("div");
block.className = className;
block.style.left = `${x}px`;
block.style.top = `${y}px`;
board.appendChild(block);
return block;
}
function createSnake() {
snake.forEach((block) => {
createBlock(block.x, block.y, "snake");
});
}
function createFood() {
const x = Math.floor(Math.random() * boardWidth);
const y = Math.floor(Math.random() * boardHeight);
food = createBlock(x, y, "food");
}
function updateSnake() {
for (let i = snake.length - 1; i > 0; i--) {
snake[i].x = snake[i - 1].x;
snake[i].y = snake[i - 1].y;
}
switch (direction) {
case "up":
snake[0].y -= blockHeight;
break;
case "down":
snake[0].y += blockHeight;
break;
case "left":
snake[0].x -= blockWidth;
break;
case "right":
snake[0].x += blockWidth;
break;
}
}
function checkCollision() {
if (
snake[0].x < 0 ||
snake[0].x >= boardWidth ||
snake[0].y < 0 ||
snake[0].y >= boardHeight
) {
clearInterval(intervalId);
alert("游戏结束");
}
if (snake.slice(1).some((block) => block.x === snake[0].x && block.y === snake[0].y)) {
clearInterval(intervalId);
alert("游戏结束");
}
if (snake[0].x === food.offsetLeft && snake[0].y === food.offsetTop) {
food.remove();
createFood();
snake.push({ x: snake[snake.length - 1].x, y: snake[snake.length - 1].y });
}
}
function render() {
board.innerHTML = "";
createSnake();
if (!food) {
createFood();
}
}
function gameLoop() {
updateSnake();
checkCollision();
render();
}
document.addEventListener("keydown", (event) => {
switch (event.keyCode) {
case 38:
if (direction !== "down") {
direction = "up";
}
break;
case 40:
if (direction !== "up") {
direction = "down";
}
break;
case 37:
if (direction !== "right") {
direction = "left";
}
break;
case 39:
if (direction !== "left") {
direction = "right";
}
break;
}
});
intervalId = setInterval(gameLoop, 200);
</script>
</code></pre>
</body>
</html>
原文地址: http://www.cveoy.top/t/topic/bipf 著作权归作者所有。请勿转载和采集!