Flappy Bird Using HTML, CSS and JS With Source Code - CodeWithCurious (2024)

Flappy Bird Using HTML, CSS and JS With Source Code

Flappy Bird Using HTML, CSS and JS With Source Code - CodeWithCurious (1)

Introduction :

In this project, we delve into the fascinating world of game development by creating a classic arcade-style game known as Flappy Bird. Inspired by the immensely popular mobile game, our project aims to provide an engaging and interactive experience for players of all ages. Using HTML, CSS, and JavaScript, we embark on a journey to build the foundation of Flappy Bird, incorporating essential game mechanics such as player control, obstacle avoidance, and scoring systems. Let’s dive into the intricacies of game development and witness the magic unfold as we bring Flappy Bird to life on the web platform.

Steps to create Flappy Bird

  1. Set Up HTML Structure:

    • Create an HTML file (e.g., index.html).
    • Inside the HTML file, set up the basic structure including <html>, <head>, <title>, and <body> tags.
  2. Create Canvas Element:

    • Within the <body> tag, add a <canvas> element to serve as the game board.
    • Give the canvas an id attribute (e.g., “gameCanvas”).
  3. Style with CSS:

    • Create a separate CSS file (e.g., styles.css).
    • Add styles to the canvas element to define its dimensions and appearance.
    • Customize styles for the bird, pipes, background, and any other game elements.
  4. Draw Game Elements with JavaScript:

    • Create a JavaScript file (e.g., game.js).
    • Select the canvas element using JavaScript.
    • Use the canvas API (getContext) to get the drawing context.
    • Write functions to draw the bird, pipes, background, and any other game elements on the canvas.
  5. Implement Game Logic:

    • Define variables to store the bird’s position, velocity, and gravity.
    • Implement functions to handle user input (e.g., spacebar for bird flap).
    • Write logic to move the bird up and down based on user input and gravity.
    • Generate pipes at regular intervals and move them horizontally across the screen.
    • Detect collisions between the bird and pipes to determine when the game ends.
  6. Add Scoring System:

    • Create a variable to keep track of the player’s score.
    • Increase the score each time the bird successfully passes through a set of pipes.
  7. Handle Game Over:

    • Implement logic to detect when the bird collides with a pipe or goes out of bounds.
    • Display a “Game Over” message on the canvas.
    • Allow the player to restart the game.
  8. Test and Debug:

    • Test the game thoroughly to ensure all features work as expected.
    • Debug any issues with game mechanics, collision detection, or user input.

Explanation

HTML

index.html

  • Document Declaration:The HTML code begins with the declaration <!DOCTYPE html>, signifying that the document adheres to the HTML5 standard. Additionally, it specifies the language as English, ensuring proper interpretation by web browsers.
  • Head Section: Within the <head> section, essential meta-information and external resource links are housed. This includes metadata tags for character encoding and viewport configuration, crucial for rendering the content correctly across various devices and screen sizes.
  • Canvas Element: A <canvas> element with the id “gameCanvas” is introduced within the <body> section. This serves as the game board where Flappy Bird and game elements will be drawn dynamically using JavaScript.
  • Game Container: A <div> element with the id “game-container” encloses the game canvas and provides a container for organizing and styling game-related content.
  • Game Title: An <h1> heading displaying the title “Flappy Bird” serves as the prominent identifier for the game, providing users with a clear indication of the game’s identity and purpose.
  • JavaScript Integration: A <script> tag is included at the end of the <body> section, linking an external JavaScript file named “game.js”. This file contains the game logic and functionality responsible for controlling the behavior of Flappy Bird, including player input, obstacle generation, and scoring.
  • External Stylesheet: The HTML document links an external CSS file named “styles.css” using the <link> tag within the <head> section. This stylesheet is responsible for styling various game elements, ensuring consistency in appearance and enhancing the visual aesthetics of the game interface.

In summary, the HTML code establishes the foundational structure and layout for the Flappy Bird game, incorporating essential elements such as the canvas element for rendering graphics, JavaScript integration for game logic, and external styling for visual enhancement.

CSS Styling

  1. Body Styling:

    • The body selector applies styling to the entire webpage.
    • margin: 0; and padding: 0; remove any default margins and padding, ensuring consistent spacing.
    • font-family: Arial, sans-serif; specifies the font family for text content, prioritizing Arial and falling back to a generic sans-serif font if Arial is not available.
    • background-color: #f1f1f1; sets the background color of the webpage to a light gray (#f1f1f1), providing a neutral backdrop for content.
  2. Game Container Styling:

    • The #game-container selector targets a specific container element with the id “game-container”.
    • position: relative; specifies that the container’s position is relative to its normal position, allowing absolute positioning of child elements.
    • width: fit-content; sets the width of the container to fit its content, ensuring that it expands or contracts based on the content inside.
    • margin: 50px auto; centers the container horizontally on the page with a top and bottom margin of 50 pixels, auto-calculating the left and right margins.
    • background-color: #fff; sets the background color of the container to white (#fff), creating a clean and minimalistic appearance.
    • border-radius: 10px; adds rounded corners to the container with a border radius of 10 pixels, adding a subtle visual effect.
    • box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); applies a shadow effect to the container, providing depth and dimensionality to the layout.
    • padding: 20px; adds internal spacing of 20 pixels to the container, ensuring adequate space between the content and container edges.
  3. Canvas Styling:

    • The canvas selector targets the canvas element within the game container.
    • display: block; sets the display property to block, making the canvas a block-level element that fills its container’s width.
    • margin: 0 auto; centers the canvas horizontally within its container by setting left and right margins to auto.
    • background-image: url('bg.jpg'); specifies a background image for the canvas, using the file “bg.jpg”.
    • background-size: cover; ensures that the background image covers the entire canvas, maintaining aspect ratio and filling any empty space.
  4. Additional Styling:

    • The #instructions selector targets an element with the id “instructions” to provide styling for game instructions.
    • The h1 selector styles heading elements to have centered text alignment.

game.js

  1. Canvas Initialization:

    • The canvas variable holds the reference to the HTML canvas element with the id “gameCanvas”.
    • The ctx variable stores the 2D rendering context of the canvas, enabling drawing operations.
  2. Bird Object Definition:

    • The bird object encapsulates properties such as position (x and y), size (radius), gravity, velocity, and lift.
    • These properties control the behavior of the bird within the game environment, including its movement and response to user input.
  3. Pipes and Scoring:

    • The pipes array stores information about the pipes in the game, including their position and whether the bird has passed them.
    • The pipeGap variable defines the vertical gap between upper and lower pipes.
    • The pipeWidth variable specifies the width of the pipes.
    • The score variable keeps track of the player’s score as they successfully navigate through pipes.
  4. Game State Management:

    • The isGameOver flag indicates whether the game is over.
    • The attempts variable counts the number of attempts the player has made, limiting the number of retries.
    • The maxAttempts constant determines the maximum number of attempts allowed.
  5. Image Loading:

    • The birdImg and pipeImg variables load image files for the bird and pipes, respectively, using the Image constructor.
    • These images are later drawn on the canvas to represent game elements.
  6. Drawing Functions:

    • drawBird() and drawPipes() functions render the bird and pipes on the canvas using the drawImage() method of the canvas context (ctx).
    • These functions are responsible for visually representing game elements to the player.
  7. Game Logic:

    • updateBird() and updatePipes() functions handle the game’s core mechanics, including bird movement, pipe generation, collision detection, and scoring.
    • These functions update the game state based on user input and game rules, ensuring proper gameplay mechanics.
  8. Game Over Handling:

    • The gameOver() function is triggered when the game ends due to collision or reaching the maximum number of attempts.
    • It displays appropriate messages on the canvas, indicating whether the player can restart the game or if it’s over.
  9. Restart Functionality:

    • The restartListener() function listens for the spacebar key press to restart the game after it has ended.
    • It resets game variables and starts the game loop again upon player input.
  10. Game Loop and Event Listeners:

    • The gameLoop() function runs continuously to update the game state and render the game elements on the canvas.
    • Event listeners are added to handle user input (e.g., spacebar for bird flap) and restart the game after game over.
  11. Initialization and Start:

    • The gameLoop() function is initially called to start the game loop and render the game on the canvas.

This JavaScript code orchestrates the Flappy Bird game, managing game state, user input, rendering, and game mechanics to provide an immersive gaming experience for players.

Source Code :

HTML (index.html)

 <title>Flappy Bird</title> 

CSS (styles.css)

body { margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f1f1f1;}#game-container { position: relative; width: fit-content; margin: 50px auto; background-color: #fff; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); padding: 20px;}canvas { display: block; margin: 0 auto; background-image: url('bg.jpg'); /* Set your background image here */ background-size: cover;}#instructions { text-align: center; margin-top: 20px;}h1 { text-align: center;}

JS (game.js)

const canvas = document.getElementById('gameCanvas');const ctx = canvas.getContext('2d');const bird = { x: 50, y: canvas.height / 2, radius: 15, gravity: 0.6, velocity: 0, lift: -12};const pipes = [];const pipeGap = 250;const pipeWidth = 100;let score = 0;let isGameOver = false;let attempts = 0;const maxAttempts = 3;// Load the bird imageconst birdImg = new Image();birdImg.src = 'bird.png'; // Set your bird image file path herefunction drawBird() { ctx.drawImage(birdImg, bird.x - bird.radius, bird.y - bird.radius, bird.radius * 2, bird.radius * 2);}// Load the pipe imageconst pipeImg = new Image();pipeImg.src = 'pipe.png'; // Set your pipe image file path herefunction drawPipes() { for (let i = 0; i = canvas.height || bird.y &lt;= 0) { gameOver(); }}function updatePipes() { if (pipes.length === 0 || pipes[pipes.length - 1].x &lt; canvas.width - 200) { pipes.push({ x: canvas.width, topHeight: Math.random() * (canvas.height - pipeGap - 300) + 150 }); } for (let i = 0; i &lt; pipes.length; i++) { pipes[i].x -= 2; if (pipes[i].x + pipeWidth pipes[i].x &amp;&amp; bird.x - bird.radius &lt; pipes[i].x + pipeWidth &amp;&amp; (bird.y - bird.radius pipes[i].topHeight + pipeGap)) { gameOver(); } if (pipes[i].x + pipeWidth = maxAttempts) { ctx.font = '50px Arial'; ctx.fillStyle = '#000'; ctx.fillText('Game Over', canvas.width / 2 - 150, canvas.height / 2); } else { ctx.font = '30px Arial'; ctx.fillStyle = '#000'; ctx.fillText('Start Again', canvas.width / 2 - 150, canvas.height / 2); } // Add event listener for restart document.addEventListener('keydown', restartListener);}function restartListener(e) { if (e.key === ' ' &amp;&amp; attempts = maxAttempts) return; if (!isGameOver) { ctx.clearRect(0, 0, canvas.width, canvas.height); drawBird(); drawPipes(); updateBird(); updatePipes(); drawScore(); requestAnimationFrame(gameLoop); } else { drawInstructions(); }}document.addEventListener('keydown', function (e) { if (e.key === ' ' &amp;&amp; attempts &lt; maxAttempts) { if (isGameOver) { restartGame(); } else { bird.velocity = bird.lift; } }});function restartGame() { pipes.length = 0; bird.y = canvas.height / 2; score = 0; isGameOver = false; gameLoop();}gameLoop();

Output :

Find More Projects

Number Guessing Game Using HTML CSS And JavaScript

Number Guessing Game Using HTML CSS And JavaScript

Goutam Prajapat

October 17, 2024

projects, Web Development Projects

Build a Quiz Game Using HTML CSS and JavaScript Introduction Hello coders, you might have played various games, but were you aware …

Emoji Catcher Game Using HTML CSS and JavaScript

Emoji Catcher Game Using HTML CSS and JavaScript

Goutam Prajapat

October 17, 2024

projects, Web Development Projects

Emoji Catcher Game Using HTML CSS and JavaScript Introduction Hello Coders, Welcome to another new blog. In this article we’ve made a …

Typing Challenge Using HTML CSS and JavaScript with complete source code

Typing Challenge Using HTML CSS and JavaScript with complete source code

Goutam Prajapat

October 17, 2024

projects, Web Development Projects

Typing Challenge Using HTML CSS and JavaScript Introduction Hello friends, all you developer friends are welcome to our new project. If you …

Breakout Game Using HTML CSS and JavaScript With Source Code

Breakout Game Using HTML CSS and JavaScript With Source Code

Goutam Prajapat

October 17, 2024

projects, Web Development Projects

Breakout Game Using HTML CSS and JavaScript With Source Code Introduction Hello friends, welcome to today’s new blog post. All of you …

Digital and Analog Clock using HTML CSS and JavaScript

Digital and Analog Clock using HTML CSS and JavaScript

Nikhil Kamble

October 17, 2024

projects, Web Development Projects

Digital and Analog Clock using HTML CSS and JavaScript Introduction : This project is a digital clock and stopwatch system, which allows …

Coffee Shop Website using HTML CSS and JavaScript

Coffee Shop Website using HTML CSS and JavaScript

Nikhil Kamble

October 17, 2024

projects, Web Development Projects

Coffee Shop Website using HTML, CSS & JavaScript Introduction : This project is a website for coffee house business. It uses HTML …

More HTML CSS JS Projects

Number Guessing Game Using HTML CSS And JavaScript

Emoji Catcher Game Using HTML CSS and JavaScript

Typing Challenge Using HTML CSS and JavaScript with complete source code

Breakout Game Using HTML CSS and JavaScript With Source Code

Digital and Analog Clock using HTML CSS and JavaScript

Coffee Shop Website using HTML CSS and JavaScript

Architectural Website using HTML CSS and JavaScript

Interior Design Website using HTML CSS and JavaScript

Candy Crush Game Using HTML CSS JavaScript

Archery Game Using HTML CSS and JavaScript

Instagram Clone Using HTML CSS Js

Google Homepage Clone Using HTML and CSS With Source Code

YouTube Clone Using HTML, CSS and JavaScript With Source Code

Real Time Chat App Using HTML, CSS, JavaScript and ReactJs With Source Code

Admin Dashboard Using HTML, CSS, JavaScript and ReactJs With Source Code

Crypto Currency Tracker Using HTML, CSS, JavaScript and ReactJs With Source Code

Facebook Messenger Using HTML, CSS, JavaScript and ReactJs With Source Code

Exercise App using HTML, CSS, JavaScript and ReactJs With Source Code

Spotify Clone Using HTML, CSS, JavaScript and ReactJs With Source Code

Figma Clone Using HTML, CSS, JavaScript and ReactJs With Source Code

YouTube Clone Using HTML, CSS, JavaScript and ReactJs With Source Code

Chat Application Using HTML , CSS And Javascript With Source Code

Travel Planner Website Using HTML , CSS And JavaScript With Source Code

Rock Paper Scissor Game Using HTML , CSS And JavaScript With Source Code

Color Guessing Game using HTML , CSS And Javascript With Source Code

Fanta Landing Page Using HTML CSS And JS With Source Code

YouTube Thumbnail Downloader Using HTML , CSS And JavaScript With Source Code

Amazing Love Puzzle Using HTML , CSS And Javascript With Source Code

Word Counter Website Using HTML , CSS And JavaScript With Source Code

Student Registration Dashboard Using HTML CSS And JavaScript With Source Code

Snake Game Using HTML , CSS And Javascript With Source Code

Flappy Bird Using HTML, CSS and JS With Source Code

Facebook Clone Using HTML, CSS and JS With Source Code

Spotify Clone Using HTML CSS and JS With Source Code

Ticket Management System Using HTML CSS and JS With Source Code

Pong Game Using HTML CSS and JavaScript With Source Code

Facebook Login Using HTML CSS JS With Source Code

Maze Game using HTML CSS JavaScript With Source Code

Word Scramble Game Using HTML, CSS and JavaScript With Source Code

Create Simple Website Using HTML and CSS With Source Code

Holi Fluid Animation Using HTML CSS JavaScript With Source Code

Music Player using HTML, CSS, JavaScript and React With Source Code

Expense Tracker App using HTML, CSS, JavaScript and ReactJs Framework With Source Code

E-commerce App using HTML, CSS, JavaScript and React Framework With Source Code

Personal Portfolio using HTML, CSS and JavaScript With Source Code

Snake Game using HTML, CSS and JavaScript With Source Code

Tic Tac Toe Game using HTML, CSS and JavaScript With Source Code

Amazon Clone using HTML and CSS With Source Code

QR Code Generator using HTML, CSS and JavaScript With Source Code

Hangman Game using HTML, CSS and JavaScript With Source Code

AI Image Generator using HTML, CSS and JavaScript With Source Code

News App using HTML, CSS and JavaScript With Source Code

Speech to Text Converter using HTML, CSS and JavaScript With Source Code

Currency Converter using HTML, CSS and JavaScript With Source Code

Drum kit using HTML, CSS and JavaScript With Source Code

Notes app using HTML, CSS and JavaScript With Source Code

Music Player using HTML, CSS and JavaScript With Source Code

To-Do List using HTML, CSS and JS With Source Code

Dynamic Interactive Calculator Using HTML CSS JS With Source Code

Task Manager Using HTML , CSS , JavaScript With Source Code

Personal Portfolio Website Using HTML , CSS , JavaScript With Source Code

Get Huge Discounts

Get Discount on Top EdTech Compnies
  • 45% Discount on SkillShare
  • 10% Discount on KodeKoloud
  • 30% Discount on AlmaBetter
  • 10% Discount on Coding Ninjas
  • Upto 80% Discount on GeeksforGeeks
Flappy Bird Using HTML, CSS and JS With Source Code - CodeWithCurious (2024)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 5357

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.