Untitled
unknown
plain_text
10 months ago
2.8 kB
17
Indexable
<!DOCTYPE html>
<html>
<head>
<title>Simple Flappy Bird</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #70c5ce;
}
canvas {
display: block;
background: #70c5ce;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Game variables
let birdY = 300;
let birdVelocity = 0;
const gravity = 0.5;
const jump = -10;
let pipes = [];
const pipeWidth = 50;
const pipeGap = 150;
let frame = 0;
let score = 0;
let gameOver = false;
// Handle space key
document.addEventListener('keydown', () => {
birdVelocity = jump;
});
function drawBird() {
ctx.fillStyle = 'yellow';
ctx.fillRect(50, birdY, 30, 30);
}
function drawPipes() {
ctx.fillStyle = 'green';
for (let i = 0; i < pipes.length; i++) {
let p = pipes[i];
ctx.fillRect(p.x, 0, pipeWidth, p.top);
ctx.fillRect(p.x, canvas.height - p.bottom, pipeWidth, p.bottom);
}
}
function updatePipes() {
if (frame % 90 === 0) {
let topHeight = Math.random() * (canvas.height - pipeGap - 100) + 50;
let bottomHeight = canvas.height - topHeight - pipeGap;
pipes.push({x: canvas.width, top: topHeight, bottom: bottomHeight});
}
for (let i = 0; i < pipes.length; i++) {
pipes[i].x -= 2;
// Collision detection
if (50 + 30 > pipes[i].x && 50 < pipes[i].x + pipeWidth &&
(birdY < pipes[i].top || birdY + 30 > canvas.height - pipes[i].bottom)) {
gameOver = true;
}
// Increase score
if (pipes[i].x + pipeWidth === 50) {
score++;
}
}
// Remove off-screen pipes
pipes = pipes.filter(p => p.x + pipeWidth > 0);
}
function updateBird() {
birdVelocity += gravity;
birdY += birdVelocity;
if (birdY + 30 > canvas.height || birdY < 0) {
gameOver = true;
}
}
function drawScore() {
ctx.fillStyle = 'white';
ctx.font = '24px Arial';
ctx.fillText('Score: ' + score, 10, 30);
}
function gameLoop() {
if (gameOver) {
ctx.fillStyle = 'red';
ctx.font = '48px Arial';
ctx.fillText('Game Over', 80, 300);
return;
}
frame++;
ctx.clearRect(0, 0, canvas.width, canvas.height);
updateBird();
updatePipes();
drawBird();
drawPipes();
drawScore();
requestAnimationFrame(gameLoop);
}
gameLoop();
</script>
</body>
</html>
Editor is loading...
Leave a Comment