【前端|JS实战】使用JS来实现属于自己的贪吃蛇游戏!
下面是一个简单的贪吃蛇游戏的实现示例,使用JavaScript和HTML。这个示例提供了游戏的核心功能,包括蛇的移动、食物生成和碰撞检测。
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
.game-container {
position: relative;
width: 200px;
height: 200px;
border: 1px solid #000;
}
.snake {
width: 10px;
height: 10px;
background-color: #000;
position: absolute;
}
.food {
width: 10px;
height: 10px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div class="game-container" id="gameContainer"></div>
<script>
const gameContainer = document.getElementById('gameContainer');
const snake = [{ x: 10, y: 10 }];
let food = { x: 30, y: 30 };
let dx = 10;
let dy = 0;
let interval = 200;
function createEl(className, x, y) {
const el = document.createElement('div');
el.className = className;
el.style.left = `${x}px`;
el.style.top = `${y}px`;
gameContainer.appendChild(el);
return el;
}
function createFood() {
food = { x: Math.floor(Math.random() * 20 + 1) * 10, y: Math.floor(Math.random() * 20 + 1) * 10 };
createEl('food', food.x, food.y);
}
function moveSnake() {
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
snake.unshift(head);
const el = document.querySelector('.snake');
if (el) {
el.style.left = `${head.x}px`;
el.style.top = `${head.y}px`;
} else {
createEl('snake', head.x, head.y);
}
if (food.x === head.x && food.y === head.y) {
createFood();
} else {
snake.pop();
const tail = document.querySelector('.snake:last-child');
gameContainer.removeChild(tail);
}
}
createFood();
setInterval(moveSnake, interval);
document.addEventListener('keydown', (e) => {
switch (e.key) {
case 'ArrowUp':
if (dy !== 10) {
dy = -10;
评论已关闭