在现代互联网技术中,HTML5与JavaScript的结合为开发者提供了丰富的可能性。今天,我们将通过一段代码来实现一款经典的像素风格小鸟小游戏,既是对经典游戏玩法的致敬,也是对前端开发技能的一次实践。
首先,我们需要创建一个简单的HTML结构,用于承载我们的游戏界面:
```html
canvas {
display: block;
margin: 0 auto;
background-color: 87CEEB; / 天空蓝 /
}
<script src="pixelBird.js"></script>
```
接下来,在`pixelBird.js`文件中编写JavaScript逻辑。这部分代码将包括游戏的主要功能,如小鸟的跳跃、管道的生成以及碰撞检测等。
```javascript
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 小鸟属性
let bird = { x: 50, y: 300, dy: 0, height: 20, width: 20 };
let gravity = 0.6;
let jumpStrength = -12;
// 管道属性
let pipes = [];
let pipeFrequency = 150;
let pipeSpeed = 2;
function drawBird() {
ctx.fillStyle = 'yellow';
ctx.fillRect(bird.x, bird.y, bird.width, bird.height);
}
function updateBird() {
bird.dy += gravity;
bird.y += bird.dy;
if (bird.y + bird.height > canvas.height) {
bird.y = canvas.height - bird.height;
bird.dy = 0;
}
}
function jump() {
bird.dy = jumpStrength;
}
document.addEventListener('keydown', (event) => {
if (event.code === 'Space') {
jump();
}
});
function drawPipes() {
ctx.fillStyle = 'green';
for (let i = 0; i < pipes.length; i++) {
let pipe = pipes[i];
ctx.fillRect(pipe.x, 0, pipe.width, pipe.top);
ctx.fillRect(pipe.x, canvas.height - pipe.bottom, pipe.width, pipe.bottom);
}
}
function updatePipes() {
for (let i = 0; i < pipes.length; i++) {
let pipe = pipes[i];
pipe.x -= pipeSpeed;
if (pipe.x + pipe.width < 0) {
pipes.splice(i, 1);
}
}
}
function generatePipe() {
let top = Math.random() (canvas.height / 2);
let bottom = canvas.height - top - pipeFrequency;
pipes.push({ x: canvas.width, y: 0, width: 50, top: top, bottom: bottom });
}
setInterval(() => {
generatePipe();
}, pipeFrequency 1000);
function checkCollision() {
for (let i = 0; i < pipes.length; i++) {
let pipe = pipes[i];
if (bird.x < pipe.x + pipe.width &&
bird.x + bird.width > pipe.x &&
(bird.y < pipe.top || bird.y + bird.height > canvas.height - pipe.bottom)) {
alert('游戏结束!');
location.reload();
}
}
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBird();
drawPipes();
updateBird();
updatePipes();
checkCollision();
requestAnimationFrame(gameLoop);
}
gameLoop();
```
以上就是利用JavaScript制作的一款简单但有趣的像素小鸟小游戏的核心代码。玩家可以通过按下空格键让小鸟上升,同时避免撞到从屏幕右侧不断出现的管道。这款游戏不仅能够帮助理解基本的物理模拟和事件处理,还非常适合用来学习如何构建动态的网页应用程序。