Skip to main content

Creating a Flappy Bird Game With HTML, CSS , Javascript

In this post, we will create a simple Flappy Bird game using HTML, CSS, and JavaScript. The game features a bird that moves up when the spacebar is pressed and obstacles of varying heights that appear from the right side of the screen. The objective is to navigate the bird through the gaps in the obstacles without colliding with them.

HTML Structure

        <div id="gameContainer">
    <div id="bird"></div>
    <div id="obstacle"></div>
    <div id="obstacleTop"></div>
    <div id="score">Score: 0</div>
    <div id="gameOver">Game Over!</div>
</div>
    

CSS Styling

        #gameContainer {
    position: relative;
    width: 400px;
    height: 600px;
    background: url('background.png') no-repeat center center;
    background-size: cover;
    overflow: hidden;
}
#bird {
    position: absolute;
    width: 40px;
    height: 40px;
    background: url('bird.png') no-repeat center center;
    background-size: cover;
    top: 200px;
    left: 50px;
}
#obstacle, #obstacleTop {
    position: absolute;
    width: 50px;
    background-color: green;
    animation: moveObstacle 4s linear infinite;
}
#obstacleTop {
    background-color: darkgreen;
}
#score, #gameOver {
    position: absolute;
    top: 10px;
    left: 10px;
    color: white;
    font-size: 24px;
    font-family: Arial, sans-serif;
}
#gameOver {
    display: none;
    font-size: 32px;
}
    

JavaScript Logic

        const bird = document.getElementById('bird');
const gameContainer = document.getElementById('gameContainer');
const obstacle = document.getElementById('obstacle');
const obstacleTop = document.getElementById('obstacleTop');
const scoreDisplay = document.getElementById('score');
const gameOverDisplay = document.getElementById('gameOver');

let birdY = 200;
let birdGravity = 2;
let birdLift = -30;
let isGameOver = false;
let score = 0;
let obstaclePassed = false;
let lastObstacleHeight = 0;

function gameLoop() {
    if (isGameOver) return;

    birdY += birdGravity;
    bird.style.top = birdY + 'px';

    const obstacleRect = obstacle.getBoundingClientRect();
    const birdRect = bird.getBoundingClientRect();

    if (obstacleRect.right < 0) {
        resetObstacles();
        obstaclePassed = true;
    }

    if (obstacleRect.right < birdRect.left && !obstaclePassed) {
        obstaclePassed = true;
        incrementScore();
    }

    if (checkCollision()) {
        gameOver();
    }

    requestAnimationFrame(gameLoop);
}

function jump() {
    birdY += birdLift;
}

function checkCollision() {
    const birdRect = bird.getBoundingClientRect();
    const obstacleRect = obstacle.getBoundingClientRect();
    const obstacleTopRect = obstacleTop.getBoundingClientRect();

    return (
        birdRect.top <= 0 ||
        birdRect.bottom >= gameContainer.clientHeight ||
        (birdRect.right >= obstacleRect.left &&
        birdRect.left <= obstacleRect.right &&
        birdRect.bottom >= obstacleRect.top) ||
        (birdRect.right >= obstacleTopRect.left &&
        birdRect.left <= obstacleTopRect.right &&
        birdRect.top <= obstacleTopRect.bottom)
    );
}

function resetObstacles() {
    let obstacleHeight;
    do {
        obstacleHeight = Math.floor(Math.random() * 150) + 100;
    } while (Math.abs(obstacleHeight - lastObstacleHeight) < 50);

    lastObstacleHeight = obstacleHeight;
    let gapHeight = 150;

    obstacle.style.height = obstacleHeight + 'px';
    obstacle.style.bottom = '0';
    obstacle.style.right = '-50px';

    obstacleTop.style.height = (600 - obstacleHeight - gapHeight) + 'px';
    obstacleTop.style.top = '0';
    obstacleTop.style.right = '-50px';

    obstacle.style.animation = 'moveObstacle 4s linear infinite';
    obstacleTop.style.animation = 'moveObstacle 4s linear infinite';
}

function gameOver() {
    isGameOver = true;
    gameOverDisplay.style.display = 'block';
    obstacle.style.animation = '';
    obstacleTop.style.animation = '';
}

function resetGame() {
    birdY = 200;
    score = 0;
    scoreDisplay.textContent = 'Score: ' + score;
    gameOverDisplay.style.display = 'none';
    isGameOver = false;
    obstaclePassed = false;
    resetObstacles();
    gameLoop();
}

document.addEventListener('keydown', event => {
    if (event.code === 'Space') {
        if (isGameOver) {
            resetGame();
        } else {
            jump();
        }
    }
});

function incrementScore() {
    if (!isGameOver) {
        score++;
        scoreDisplay.textContent = 'Score: ' + score;
    }
}

resetObstacles();
gameLoop();
    

This code sets up the HTML structure, CSS styling, and JavaScript logic to create a simple Flappy Bird game. The obstacles are randomly generated with different heights each time the bird passes through them, and the score increments accordingly. You can customize the game further by adjusting the styles and adding new features.

Comments

Popular posts from this blog

Creating a Simple Car Racing Game with HTML, CSS, Javascript

In this post, we will create a simple car racing game using HTML, CSS, and JavaScript. This game will feature a player car, an opponent car, and a score counter. The player can move their car left and right to avoid collisions with the opponent car. Let's dive into the code! HTML Structure The HTML structure consists of a game area that contains the road, player car, opponent car, and score display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Car Racing Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="gameArea"> <div class="road"></div> <div class="playerCar"></div> <div class="opponentCar"></div...

Pac-Man Game in HTML, CSS, and JavaScript

In this tutorial, we will create a classic Pac-Man game using HTML, CSS, and JavaScript. Follow the steps to build the game board, Pac-Man, and implement the game logic. HTML Structure First, we need to set up the HTML structure for our Pac-Man game. This includes the game board and score display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pac-Man Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Pac-Man Game</h1> <div id="game-board"></div> <div id="score-display">Score: 0</div> <script src="script.js"></script> </body> </html> CSS Styling Next, we add some CSS to style the game board, walls, dot...

How To Create 3D Car Racing Game in React.js

In this tutorial, we'll create a simple car racing game using React.js. The player can move the car left and right using the keyboard arrow keys. The opponent cars will move from the top to the bottom, and the game will end with a "Game Over" alert when the player's car collides with an opponent car. The speed of the opponent cars will gradually increase, making the game more challenging. Step 1: Set Up the Project First, make sure you have create-react-app installed. If not, install it using the following command: npx create-react-app car-racing-game Navigate to your project directory: cd car-racing-game Step 2: Install Styled-Components We will use styled-components for styling our components. Install it using the following command: npm install styled-components Step 3: Create the Game Components Create a new file src/App.js and replace its content with the following code: ...