|
|
<!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>
const gameBoard = document.getElementById('game-board');
let snake = [{x: 10, y: 10}];
let food = {x: 200, y: 200};
function drawSnake() {
gameBoard.innerHTML = '';
snake.forEach(segment => {
const snakeElement = document.createElement('div');
snakeElement.style.left = segment.x + 'px';
snakeElement.style.top = segment.y + 'px';
snakeElement.classList.add('snake');
gameBoard.appendChild(snakeElement);
});
}
function drawFood() {
const foodElement = document.createElement('div');
foodElement.style.left = food.x + 'px';
foodElement.style.top = food.y + 'px';
foodElement.classList.add('food');
gameBoard.appendChild(foodElement);
}
function moveSnake() {
const head = {x: snake[0].x + 10, y: snake[0].y};
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
food.x = Math.floor(Math.random() * 39) * 10;
food.y = Math.floor(Math.random() * 39) * 10;
} else {
snake.pop();
}
}
drawSnake();
drawFood();
setInterval(() => {
moveSnake();
drawSnake();
}, 100);
</script>
</body>
</html>
帮我改成红色字体
|
|