Check out this Pen I made!
<!DOCTYPE html>
Flirty Bird
---
### **CSS (style.css)**
css
- { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: Arial, sans-serif;
background-color: #70c5ce;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
game {
position: relative;
width: 400px;
height: 600px;
background-color: #70c5ce;
border: 2px solid #000;
overflow: hidden;
}
bird {
position: absolute;
top: 50%;
left: 50px;
width: 40px;
height: 40px;
background-color: #ffcc00;
border-radius: 50%;
}
.obstacle {
position: absolute;
width: 60px;
background-color: green;
}
obstacle {
top: 0;
right: -60px;
height: 200px;
animation: moveObstacle 3s linear infinite;
}
@keyframes moveObstacle {
from {
right: -60px;
}
to {
right: 400px;
}
}
---
### **JavaScript (script.js)**
javascript
const bird = document.getElementById("bird");
const game = document.getElementById("game");
const obstacle = document.getElementById("obstacle");
let birdBottom = 50;
let gravity = 2;
let isGameOver = false;
// Make the bird fall
function applyGravity() {
if (birdBottom > 0) {
birdBottom -= gravity;
bird.style.bottom = birdBottom + "px";
} else {
gameOver();
}
}
// Make the bird jump
function jump() {
if (birdBottom < 500) {
birdBottom += 50;
bird.style.bottom = birdBottom + "px";
}
}
// Control the bird with spacebar
document.addEventListener("keyup", function (event) {
if (event.code === "Space") {
jump();
}
});
// Check for collisions
function checkCollision() {
const obstacleLeft = parseInt(
window.getComputedStyle(obstacle).getPropertyValue("left")
);
const obstacleBottom = parseInt(
window.getComputedStyle(obstacle).getPropertyValue("height")
);
if (
obstacleLeft < 90 &&
obstacleLeft > 50 &&
(birdBottom < obstacleBottom || birdBottom > obstacleBottom + 150)
) {
gameOver();
}
}
// Game over function
function gameOver() {
isGameOver = true;
console.log("Game Over!");
obstacle.style.animation = "none";
alert("Game Over! Refresh to play again.");
}
// Game loop
function gameLoop() {
if (!isGameOver) {
applyGravity();
checkCollision();
requestAnimationFrame(gameLoop);
}
}
gameLoop();
Top comments (0)