<!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(&quot;keydown&quot;, 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(&quot;div&quot;);
foodUnit.className = &quot;food-unit&quot;;
foodUnit.style.left = x + &quot;px&quot;;
foodUnit.style.top = y + &quot;px&quot;;
gameBoard.appendChild(foodUnit);
}</p>
<p>function moveSnake() {
var head = Object.assign({}, snake[0]);
switch (direction) {
case &quot;up&quot;:
head.y -= 20;
break;
case &quot;down&quot;:
head.y += 20;
break;
case &quot;left&quot;:
head.x -= 20;
break;
case &quot;right&quot;:
head.x += 20;
break;
}
snake.unshift(head);</p>
<p>if (head.x === food.x &amp;&amp; head.y === food.y) {
score++;
gameBoard.removeChild(gameBoard.lastChild);
createFood();
} else {
snake.pop();
}</p>
<p>if (head.x &lt; 0 || head.x &gt;= 400 || head.y &lt; 0 || head.y &gt;= 400) {
gameOver();
}</p>
<p>for (var i = 1; i &lt; snake.length; i++) {
if (head.x === snake[i].x &amp;&amp; head.y === snake[i].y) {
gameOver();
}
}</p>
<p>updateGameBoard();
}</p>
<p>function changeDirection(event) {
switch (event.keyCode) {
case 87: // W
if (direction !== &quot;down&quot;) {
direction = &quot;up&quot;;
}
break;
case 83: // S
if (direction !== &quot;up&quot;) {
direction = &quot;down&quot;;
}
break;
case 65: // A
if (direction !== &quot;right&quot;) {
direction = &quot;left&quot;;
}
break;
case 68: // D
if (direction !== &quot;left&quot;) {
direction = &quot;right&quot;;
}
break;
}
}</p>
<p>function updateGameBoard() {
gameBoard.innerHTML = &quot;&quot;;
for (var i = 0; i &lt; snake.length; i++) {
var snakeUnit = document.createElement(&quot;div&quot;);
snakeUnit.className = &quot;snake-unit&quot;;
snakeUnit.style.left = snake[i].x + &quot;px&quot;;
snakeUnit.style.top = snake[i].y + &quot;px&quot;;
gameBoard.appendChild(snakeUnit);
}
}</p>
<p>function gameOver() {
clearInterval();
alert(&quot;游戏结束,得分:&quot; + score);
resetGame();
}</p>
<p>function resetGame() {
score = 0;
snake = [{x: 200, y: 200}];
direction = &quot;up&quot;;
gameBoard.innerHTML = &quot;&quot;;
}
</script></p>
</body>
</html>
PHP贪吃蛇小游戏:网页版,即开即玩!

原文地址: https://www.cveoy.top/t/topic/nxlt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录