【贪吃蛇-----html实现(附源代码,熬夜肝完这份Framework笔记
以下是一个使用HTML和JavaScript实现的基本贪吃蛇游戏的示例代码。这个示例包括了游戏的核心功能,比如蛇的移动、食物生成和碰撞检测。
<!DOCTYPE html>
<html>
<head>
<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>
class SnakeGame {
constructor(container) {
this.container = container;
this.snake = [{ x: 100, y: 100 }];
this.food = { x: 150, y: 150 };
this.direction = 'right';
this.interval = 200;
setInterval(() => this.move(), this.interval);
document.addEventListener('keydown', (e) => this.changeDirection(e));
}
move() {
let head = this.snake[0];
let newHead = { x: head.x, y: head.y };
switch (this.direction) {
case 'right':
newHead.x += 10;
break;
case 'left':
newHead.x -= 10;
break;
case 'up':
newHead.y -= 10;
break;
case 'down':
newHead.y += 10;
break;
}
this.snake.unshift(newHead);
if (this.isFoodEaten()) {
this.food = this.generateFood();
} else {
this.snake.pop();
}
this.draw();
}
isFoodEaten() {
let head = this.snake[0];
return (
head.x === this.food.x &&
head.y === this.food.y
);
}
generateFood() {
let food = {
x: Math.round(Math.random() * 20) * 10,
y: Math.round(Math.random() * 20) * 10
};
return food;
}
changeDirection(e) {
let allowedDirections = {
'ArrowRight': 'right',
'ArrowLeft': 'left',
'ArrowUp': 'up',
'ArrowDown': 'down'
};
let newDirection = allowedDirections[e.key];
if (newDirection && newDirection !== this.oppositeDirection(this.direction)) {
this.direction = newDirection;
}
}
oppositeDirection(direction) {
switch (direction) {
case 'right': return 'left';
case 'left': return 'right';
case 'up': return 'down';
case 'down': return 'up';
}
}
draw() {
let gameContainer = document.getElementById('gameContainer
评论已关闭