PHP贪吃蛇小游戏:网页版,即开即玩!
<!DOCTYPE html>
<html>
<head>
<title>PHP贪吃蛇小游戏</title>
<style>
#game-board {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
.snake-unit {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
}
.food-unit {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<button onclick="startGame()">开始游戏</button>
<div id="game-board"></div>
<script>
var gameBoard = document.getElementById("game-board");
var score = 0;
var snake = [{x: 200, y: 200}]; // 蛇初始位置
var direction = "up";
var food = {x: 0, y: 0};
<p>function startGame() {
createFood();
document.addEventListener("keydown", changeDirection);
setInterval(moveSnake, 200);
}</p>
<p>function createFood() {
var x = Math.floor(Math.random() * 20) * 20;
var y = Math.floor(Math.random() * 20) * 20;
food = {x: x, y: y};
var foodUnit = document.createElement("div");
foodUnit.className = "food-unit";
foodUnit.style.left = x + "px";
foodUnit.style.top = y + "px";
gameBoard.appendChild(foodUnit);
}</p>
<p>function moveSnake() {
var head = Object.assign({}, snake[0]);
switch (direction) {
case "up":
head.y -= 20;
break;
case "down":
head.y += 20;
break;
case "left":
head.x -= 20;
break;
case "right":
head.x += 20;
break;
}
snake.unshift(head);</p>
<p>if (head.x === food.x && head.y === food.y) {
score++;
gameBoard.removeChild(gameBoard.lastChild);
createFood();
} else {
snake.pop();
}</p>
<p>if (head.x < 0 || head.x >= 400 || head.y < 0 || head.y >= 400) {
gameOver();
}</p>
<p>for (var i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver();
}
}</p>
<p>updateGameBoard();
}</p>
<p>function changeDirection(event) {
switch (event.keyCode) {
case 87: // W
if (direction !== "down") {
direction = "up";
}
break;
case 83: // S
if (direction !== "up") {
direction = "down";
}
break;
case 65: // A
if (direction !== "right") {
direction = "left";
}
break;
case 68: // D
if (direction !== "left") {
direction = "right";
}
break;
}
}</p>
<p>function updateGameBoard() {
gameBoard.innerHTML = "";
for (var i = 0; i < snake.length; i++) {
var snakeUnit = document.createElement("div");
snakeUnit.className = "snake-unit";
snakeUnit.style.left = snake[i].x + "px";
snakeUnit.style.top = snake[i].y + "px";
gameBoard.appendChild(snakeUnit);
}
}</p>
<p>function gameOver() {
clearInterval();
alert("游戏结束,得分:" + score);
resetGame();
}</p>
<p>function resetGame() {
score = 0;
snake = [{x: 200, y: 200}];
direction = "up";
gameBoard.innerHTML = "";
}
</script></p>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/nxlt 著作权归作者所有。请勿转载和采集!