开发一个简单的Flappy Bird游戏可以帮助你学习HTML5 Canvas和JavaScript游戏开发的基础知识。在这个示例中,我将提供一个简化版的Flappy Bird游戏框架,包含鸟的飞行和障碍物的生成,你可以在此基础上扩展和优化你的游戏。
准备工作:
- 创建一个HTML文件,命名为
index.html
,并添加一个<canvas>
元素和引入JS文件的标签。 - 创建一个JavaScript文件,命名为
script.js
,用于编写游戏逻辑。
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Flappy Bird游戏</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script src="script.js"></script>
</body>
</html>
script.js:
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 600;
const bird = {
x: 50,
y: canvas.height / 2,
width: 30,
height: 30,
velocity: 0,
gravity: 0.2,
jump: -5
};
const obstacles = [];
function drawBird() {
ctx.fillStyle = 'yellow';
ctx.fillRect(bird.x, bird.y, bird.width, bird.height);
}
function drawObstacles() {
ctx.fillStyle = 'green';
obstacles.forEach((obstacle) => {
ctx.fillRect(obstacle.x, 0, obstacle.width, obstacle.heightTop);
ctx.fillRect(obstacle.x, obstacle.yBottom, obstacle.width, obstacle.heightBottom);
});
}
function createObstacle() {
const gapHeight = 150;
const minHeight = 50;
const maxHeight = canvas.height - gapHeight - minHeight;
const heightTop = Math.floor(Math.random() * (maxHeight - minHeight + 1)) + minHeight;
const heightBottom = canvas.height - heightTop - gapHeight;
const obstacle = {
x: canvas.width,
heightTop,
heightBottom,
width: 50,
yBottom: canvas.height - heightBottom
};
obstacles.push(obstacle);
}
function handleJump(event) {
if (event.code === 'Space') {
bird.velocity = bird.jump;
}
}
document.addEventListener('keydown', handleJump);
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
bird.velocity += bird.gravity;
bird.y += bird.velocity;
drawBird();
drawObstacles();
obstacles.forEach((obstacle) => {
obstacle.x -= 2;
if (obstacle.x + obstacle.width < 0) {
obstacles.shift();
}
// 检测碰撞
if (
bird.x + bird.width > obstacle.x && bird.x < obstacle.x + obstacle.width &&
(bird.y < obstacle.heightTop || bird.y + bird.height > obstacle.yBottom)
) {
alert('游戏结束!');
bird.y = canvas.height / 2;
obstacles.length = 0;
}
});
if (bird.y < 0 || bird.y + bird.height > canvas.height) {
alert('游戏结束!');
bird.y = canvas.height / 2;
obstacles.length = 0;
}
if (obstacles.length === 0 || obstacles[obstacles.length - 1].x < canvas.width - 200) {
createObstacle();
}
requestAnimationFrame(update);
}
update();
在这个简化的示例中,我们创建了鸟和障碍物,通过键盘的空格键来控制鸟的跳跃。障碍物会在画布上不断生成,并且障碍物的位置和高度都是随机的。当鸟与障碍物发生碰撞或触碰到画布的上下边界时,游戏结束,并且鸟的位置重置。
请注意,这只是一个基础的Flappy Bird游戏框架,真正的游戏中还可以增加更多功能,如计分、音效、游戏界面等等。希望这个示例能为你提供一个开始,帮助你进一步扩展和优化你的Flappy Bird游戏!