Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Flappy Bird Game using PyGame in Python



In the Flappy Bird game, players control a bird by tapping the screen to make it fly between pipes without hitting them. Here, we will design a flappy bird game using pygame library.

Steps to Design Flappy Bird Game using pygame

1. Install pygame Library

To install pygame library, use the PIP command. Here is the command to instant it −

pip install pygame

2. Import Libraries

You need to import pygame and random libraries using the import statement. The below are the code statements to import these libraries −

import pygame
import random

3. Initialize Pygame

To initialize the pygame, simply call the pygame.init() method after importing the libraries.

pygame.init()

4. Set Up Screen

Describe screen resolution and establish a window to a game through pygame.display.set_mode() method.

5. Define Colors and Properties

You have to set colors and define properties for the bird and pipes.

6. Create Drawing Functions

Create functions that will be layouts for the bird and the pipes on the screen.

7. Implement Collision Detection

Now, incorporate a function to determine whether the bird collides with the pipes or the borders of the screen.

8. Manage Pipes

Develop a function that will allow for the changes and add new pipes that may be required.

9. Run Game Loop

Receive inputs from the user, manage game status, identify coincidences, and redraw interface.

10. End Game

Quit the game window when a collision is detected with the aid of `pygame. quit()`.

Python Code for Flappy Bird Game using PyGame

import pygame
import random

# Initialize Pygame
pygame.init()

# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Bird")

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)

# Bird properties
BIRD_WIDTH = 40
BIRD_HEIGHT = 30
bird_x = 50
bird_y = SCREEN_HEIGHT // 2
bird_velocity = 0
gravity = 0.5  # Gravity
flap_strength = -7  # Moderate flap strength

# Pipe properties
PIPE_WIDTH = 70
PIPE_HEIGHT = 500
PIPE_GAP = 200  # Pipe gap
pipe_velocity = -2  # Pipe velocity
pipes = []

# Game variables
score = 0
clock = pygame.time.Clock()
flap_cooldown = 0  # Time before the bird can flap again

def draw_bird():
   pygame.draw.rect(screen, BLACK, (bird_x, bird_y, BIRD_WIDTH, BIRD_HEIGHT))

def draw_pipes():
   for pipe in pipes:
      pygame.draw.rect(screen, GREEN, pipe['top'])
      pygame.draw.rect(screen, GREEN, pipe['bottom'])

def check_collision():
   global score
   bird_rect = pygame.Rect(bird_x, bird_y, BIRD_WIDTH, BIRD_HEIGHT)
   for pipe in pipes:
      if bird_rect.colliderect(pipe['top']) or bird_rect.colliderect(pipe['bottom']):
         return True
   if bird_y > SCREEN_HEIGHT or bird_y < 0:
      return True
   return False

def update_pipes():
   global score
   for pipe in pipes:
      pipe['top'].x += pipe_velocity
      pipe['bottom'].x += pipe_velocity
      if pipe['top'].x + PIPE_WIDTH < 0:
         pipes.remove(pipe)
         score += 1
   if len(pipes) == 0 or pipes[-1]['top'].x < SCREEN_WIDTH - 300:
      pipe_height = random.randint(100, SCREEN_HEIGHT - PIPE_GAP - 100)
      pipes.append({
         'top': pygame.Rect(SCREEN_WIDTH, 0, PIPE_WIDTH, pipe_height),
         'bottom': pygame.Rect(SCREEN_WIDTH, pipe_height + PIPE_GAP, PIPE_WIDTH, SCREEN_HEIGHT - pipe_height - PIPE_GAP)
      })

# Game loop
running = True
while running:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         running = False
      if event.type == pygame.KEYDOWN:
         if event.key == pygame.K_SPACE and flap_cooldown <= 0:
            bird_velocity = flap_strength
            flap_cooldown = 10  # Set cooldown to prevent rapid flapping
      if event.type == pygame.MOUSEBUTTONDOWN and flap_cooldown <= 0:
         bird_velocity = flap_strength
         flap_cooldown = 10  # Set cooldown to prevent rapid flapping
    
   # Update bird position
   bird_velocity += gravity
   bird_y += bird_velocity

   # Update pipes
   update_pipes()

   # Check for collision
   if check_collision():
      running = False

   # Manage flap cooldown
   if flap_cooldown > 0:
      flap_cooldown -= 1

   # Draw everything
   screen.fill(WHITE)
   draw_bird()
   draw_pipes()

   # Display the score
   font = pygame.font.SysFont(None, 36)
   score_text = font.render(f'Score: {score}', True, BLACK)
   screen.blit(score_text, (10, 10))

   pygame.display.flip()
   clock.tick(30)

pygame.quit()

Output

Flappy Bird Flappy Bird

Click the Right click mouse button, you will score and played the game properly.

Flappy Bird Game Summary

When the game is run, a window opens with the title bar "Flappy Bird" and the bird, as well as the pipes are displayed. The bird becomes subjected to gravitational force and in order to make the bird flap, the player has to use the space bar key or the mouse. Tubes appear from the right side of the screen and shift to the left and the bird has to be controlled to avoid coming into contact with the tubes. The score is positioned on the top left of the pixel game and increase with the movement of the bird through pipes.

Conclusion

This Flappy Bird implementation in pygame is a simple yet very serviceable example of some of the concepts involved with game development. If the given code is analyzed and implemented into a game then the skills which developers can learn include sprite movement, collision detection and game state management. Possibilities of addition of such features as sound effects, different levels of complexities and improved graphics can also be incorporated to make the game more interesting.

python_projects_from_basic_to_advanced.htm
Advertisements