const bird = document.getElementById(‘bird’);
const game = document.getElementById(‘game’);
const scoreDisplay = document.getElementById(‘score’);
let birdY = 250;
let gravity = 2;
let isGameOver = false;
let score = 0;
document.addEventListener(‘keydown’, jump);
function jump() {
if (isGameOver) return;
birdY -= 50;
bird.style.bottom = birdY + ‘px’;
}
function createPillar() {
const pillar = document.createElement(‘div’);
const randomHeight = Math.random() * (window.innerHeight - 200) + 50;
pillar.style.height = randomHeight + ‘px’;
pillar.classList.add(‘pillar’);
pillar.style.left = ‘100vw’;
game.appendChild(pillar);
movePillar(pillar, randomHeight);
}
function movePillar(pillar, height) {
let pillarX = 1000;
const interval = setInterval(() => {
if (isGameOver) {
clearInterval(interval);
return;
}
pillarX -= 5;
pillar.style.left = pillarX + ‘px’;
// Check for collision
if (pillarX < 80 && pillarX > 50) {
if (birdY < height || birdY > height + 100) {
endGame();
}
}
// Increase score
if (pillarX < 50) {
score++;
scoreDisplay.innerText = 'Score: ' + score;
clearInterval(interval);
pillar.remove();
}
if (pillarX < -50) {
clearInterval(interval);
pillar.remove();
}
}, 20);
}
function endGame() {
isGameOver = true;
alert('Game Over! Your score: ’ + score);
document.location.reload();
}
setInterval(() => {
if (!isGameOver) {
birdY += gravity;
bird.style.bottom = birdY + ‘px’;
}
}, 20);
setInterval(createPillar, 2000);