贪吃蛇的html源代码
以下是一个简单的贪吃蛇游戏的HTML源代码示例:
html<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
#game-board {
width: 400px;
height: 400px;
border: 1px solid #000;
position: relative;
}
.snake {
width: 20px;
height: 20px;
background-color: #000;
position: absolute;
}
.food {
width: 20px;
height: 20px;
background-color: #f00;
position: absolute;
}
</style>
<script>
var snake = [{x: 5, y: 0}, {x: 4, y: 0}, {x: 3, y: 0}];
var food = {x: 2, y: 2};
var direction = "right";
var gameBoard = document.getElementById("game-board");
var snakeElement = document.createElement("div");
var foodElement = document.createElement("div");
snakeElement.className = "snake";
foodElement.className = "food";
gameBoard.appendChild(snakeElement);
gameBoard.appendChild(foodElement);
function moveSnake() {
var head = snake[0];
var newSnakeElement = document.createElement("div");
newSnakeElement.className = "snake";
newSnakeElement.style.left = head.x + "px";
newSnakeElement.style.top = head.y + "px";
gameBoard.appendChild(newSnakeElement);
snakeElement.remove();
snakeElement = newSnakeElement;
snake.unshift(head);
if (head.x == food.x && head.y == food.y) {
food = getRandomFood();
} else {
snake.pop();
}
}
function getRandomFood() {
var x = Math.floor(Math.random() * (gameBoard.offsetWidth / 20)) * 20;
var y = Math.floor(Math.random() * (gameBoard.offsetHeight / 20)) * 20;
return {x: x, y: y};
}
function changeDirection() {
if (direction == "up" && snake[0].y > 0) {
direction = "down";
} else if (direction == "down" && snake[0].y < gameBoard.offsetHeight - 20) {
direction = "up";
} else if (direction == "left" && snake[0].x > 0) {
direction = "right";
} else if (direction == "right" && snake[0].x < gameBoard.offsetWidth - 20) {
direction = "left";
}
}
function moveSnakeAutomatically() {
var head = snake[0];
if (direction == "up") {
head.y--;
} else if (direction == "down") {
head.y++;
} else if (direction == "left") {
head.x--;
} else if (direction == "right") {
head.x++;
}
moveSnake();
changeDirection();
}
setInterval(moveSnakeAutomatically, 100);
</script>
</head>
本文由设计学习网整理发布,不代表设计学习网立场,转载联系作者并注明出处:https://ffjianzhan.cn/wangjs/qianduan/12067.html