Untitled
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flappy Bird</title> <style> body { margin: 0; overflow: hidden; background-color: #70c5ce; } canvas { display: block; margin: 0 auto; } </style> </head> <body> <canvas id="gameCanvas" width="320" height="480"></canvas> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const bird = { x: 50, y: canvas.height / 2, width: 20, height: 20, gravity: 0.6, lift: -12, velocity: 0, draw() { ctx.fillStyle = 'yellow'; ctx.fillRect(this.x, this.y, this.width, this.height); }, update() { this.velocity += this.gravity; this.y += this.velocity; if (this.y + this.height > canvas.height) { this.y = canvas.height - this.height; this.velocity = 0; } else if (this.y < 0) { this.y = 0; this.velocity = 0; } }, flap() { this.velocity = this.lift; } }; const pipes = []; const pipeWidth = 40; const pipeGap = 100; const pipeSpeed = 2; let frame = 0; function drawPipes() { for (const pipe of pipes) { ctx.fillStyle = 'green'; ctx.fillRect(pipe.x, 0, pipeWidth, pipe.top); ctx.fillRect(pipe.x, canvas.height - pipe.bottom, pipeWidth, pipe.bottom); } } function updatePipes() { if (frame % 60 === 0) { const top = Math.random() * (canvas.height / 2 - pipeGap) + 20; const bottom = canvas.height - top - pipeGap; pipes.push({ x: canvas.width, top, bottom }); } for (let i = pipes.length - 1; i >= 0; i--) { pipes[i].x -= pipeSpeed; if (pipes[i].x + pipeWidth < 0) { pipes.splice(i, 1); } } } function checkCollision() { for (const pipe of pipes) { if (bird.x + bird.width > pipe.x && bird.x < pipe.x + pipeWidth) { if (bird.y < pipe.top || bird.y + bird.height > canvas.height - pipe.bottom) { return true; } } } return false; } function drawScore() { ctx.fillStyle = 'black'; ctx.font = '20px Arial'; ctx.fillText(`Score: ${Math.floor(frame / 60)}`, 10, 20); } function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); bird.update(); drawPipes(); updatePipes(); bird.draw(); drawScore(); if (checkCollision()) { alert('Game Over!'); document.location.reload(); } frame++; requestAnimationFrame(gameLoop); } document.addEventListener('keydown', (e) => { if (e.code === 'Space') { bird.flap(); } }); gameLoop(); </script> </body> </html>
Leave a Comment