Subscribe Us

How To Create a Flappy Bird Game Using Python ? Easy Step by Step 👍



FLAPPY  BIRD  GAME :




 bash

pip install pygame

Step 1: Import Libraries

Start by importing the necessary libraries:

python
import pygame import random import sys from pygame.locals import *

Step 2: Initialize Game Variables

Set up the screen, clock, and colors:

python
# Initialize pygame pygame.init() # Set up the screen SCREEN_WIDTH = 400 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) clock = pygame.time.Clock() # Set up colors WHITE = (255, 255, 255) BLACK = (0, 0, 0)

Step 3: Load Game Assets

Load images and set up the game’s assets like bird, background, and pipes:

python
# Load images bird_image = pygame.image.load('bird.png') background_image = pygame.image.load('background.png') pipe_image = pygame.image.load('pipe.png') # Scale images bird = pygame.transform.scale(bird_image, (34, 24)) background = pygame.transform.scale(background_image, (SCREEN_WIDTH, SCREEN_HEIGHT)) pipe = pygame.transform.scale(pipe_image, (52, 320))

Step 4: Create Game Functions

Create functions to handle game logic:

  1. Drawing the game elements:
python
def draw_objects(bird_y, pipe_x, pipe_y): screen.blit(background, (0, 0)) screen.blit(bird, (50, bird_y)) screen.blit(pipe, (pipe_x, pipe_y)) screen.blit(pipe, (pipe_x, pipe_y + 420))
  1. Collision detection:
python
def check_collision(bird_y, pipe_x, pipe_y): if bird_y > SCREEN_HEIGHT - 40 or bird_y < 0: return True if pipe_x < 84 and (bird_y < pipe_y + 320 or bird_y > pipe_y + 420): return True return False
  1. Main game loop:
python
def main_game(): bird_y = SCREEN_HEIGHT // 2 bird_movement = 0 gravity = 0.25 pipe_x = SCREEN_WIDTH pipe_y = random.randint(-100, 100) pipe_velocity = -4 score = 0 while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_SPACE: bird_movement = -6 bird_movement += gravity bird_y += bird_movement pipe_x += pipe_velocity if pipe_x < -50: pipe_x = SCREEN_WIDTH pipe_y = random.randint(-100, 100) score += 1 if check_collision(bird_y, pipe_x, pipe_y): main_game() draw_objects(bird_y, pipe_x, pipe_y) pygame.display.update() clock.tick(30)

Step 5: Run the Game

Finally, start the game loop:

python
if __name__ == "__main__": main_game()

Step 6: Add Bird and Pipe Images

Make sure you have the following image files in the same directory as your script:

  • bird.png
  • background.png
  • pipe.png

These images can be any suitable representation of the bird, background, and pipes.

Step 7: Run the Game

Run your Python script, and you should see the Flappy Bird game running!

Post a Comment

0 Comments