Flappy Bird Game In Python

Introduction
Flappy Bird is a simple yet captivating game that has charmed millions with its straightforward mechanics and addictive gameplay. In this game, players control a small bird navigating through a series of vertical pipes by tapping the screen to make the bird flap its wings and soar. The objective is to avoid collisions with the pipes and stay in the air for as long as possible. The charm of Flappy Bird lies in its minimalist design and the challenge it presents; despite its easy-to-understand controls, mastering the game requires precise timing and skillful maneuvering. Creating a Flappy Bird-style game involves implementing core gameplay mechanics, handling physics for realistic flapping motion, and designing obstacles that provide a balanced challenge for players.
Coding a Paint Program in Python
Coding a Flappy Bird game in Python offers an engaging introduction to game development, allowing you to create a simple yet addictive game with fundamental mechanics. At its core, a Flappy Bird game involves controlling a bird that constantly falls due to gravity and must be kept airborne by tapping to make it flap. The game’s objective is to navigate through a series of obstacles, represented by pipes, without colliding with them.
To build this game in Python, you’ll typically use a library like Pygame, which provides tools for handling graphics, user input, and game logic. The process begins by setting up the game window and initializing the necessary game elements, such as the bird, pipes, and background.


What You Need To Know
To code a Flappy Bird game in Python, you’ll need to grasp several core programming concepts and tools. First, a solid understanding of variables, data types, and control structures is essential for managing game state and logic.
The Pygame library is crucial for rendering graphics, handling user inputs, and managing the game loop. You’ll also need to implement game mechanics such as gravity and collision detection to simulate the bird’s movement and interactions with obstacles. Additionally, designing elements like obstacle generation and scorekeeping will enhance the gameplay experience. Mastering these components will enable you to create an engaging and dynamic Flappy Bird game.


Flappy Bird With Python (Full Code)
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Set up the screen
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Load images
bird_img = pygame.image.load("bird.png").convert_alpha()
background_img = pygame.image.load("background.png").convert()
# Background attributes
background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH, SCREEN_HEIGHT))
# Bird attributes
bird_rect = bird_img.get_rect(topleft=(SCREEN_WIDTH // 4, SCREEN_HEIGHT // 2))
bird_speed = 0
gravity = 0.25
jump_strength = -5
# Pipe attributes
pipe_width = 80
pipe_gap = 150
pipe_distance = 300 # Increased horizontal distance between pipes
pipe_speed = 3
pipes = []
# Score
score = 0
font = pygame.font.Font(None, 36)
# Game over flag
game_over = False
# Function to draw the pipes
def draw_pipes():
for pipe in pipes:
pygame.draw.rect(screen, (210, 221, 233), pipe[0]) # Draw upper pipe
pygame.draw.rect(screen, (210, 221, 233), pipe[1]) # Draw lower pipe
# Function to generate pipes
def generate_pipe():
pipe_x = SCREEN_WIDTH
pipe_height = random.randint(50, SCREEN_HEIGHT - pipe_gap - 50)
upper_pipe_rect = pygame.Rect(pipe_x, 0, pipe_width, pipe_height)
lower_pipe_rect = pygame.Rect(pipe_x, pipe_height + pipe_gap, pipe_width, SCREEN_HEIGHT - pipe_height - pipe_gap)
return (upper_pipe_rect, lower_pipe_rect)
# Main game loop
clock = pygame.time.Clock()
while True:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and not game_over:
if event.key == pygame.K_SPACE:
bird_speed = jump_strength
# Update bird position
bird_speed += gravity
bird_rect.y += bird_speed
# Generate pipes
if len(pipes) == 0 or pipes[-1][0].x < SCREEN_WIDTH - pipe_distance:
pipes.append(generate_pipe())
# Move pipes
for pipe in pipes:
pipe[0].x -= pipe_speed
pipe[1].x -= pipe_speed
# Check for collision with bird
if bird_rect.colliderect(pipe[0]) or bird_rect.colliderect(pipe[1]) or bird_rect.top <= 0 or bird_rect.bottom >= SCREEN_HEIGHT:
game_over = True
# Check if bird passed the pipe
if pipe[0].x + pipe_width < bird_rect.x and not pipe[0].x < 0:
score += 1
# Remove off-screen pipes
pipes = [pipe for pipe in pipes if pipe[0].x > -pipe_width]
# Draw everything
screen.blit(background_img, (0, 0)) # Draw background image
screen.blit(bird_img, bird_rect)
draw_pipes()
# Display score
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
# Check for game over
if game_over:
game_over_text = font.render("Game Over! Press R to restart", True, (0, 0, 0))
screen.blit(game_over_text, (SCREEN_WIDTH // 2 - game_over_text.get_width() // 2, SCREEN_HEIGHT // 2 - game_over_text.get_height() // 2))
pygame.display.flip()
clock.tick(60)
# Restart game if game over and R key is pressed
keys = pygame.key.get_pressed()
if game_over and keys[pygame.K_r]:
bird_rect.y = SCREEN_HEIGHT // 2 - bird_rect.height // 2
bird_speed = 0
pipes = []
score = 0
game_over = False
Now you can copy paste the following code on Pycharm and run it. The game will be launched and you can begin to play but the goal is not to play the game, it is to create it! So i recommand you to try to fully understand how it works by continuing to read this page and then try to add more implementations from your own perspective. Like you can see on the above code, i commented every line of the code so you can have a fully understanding of how things are going on. Later on, i extracted each part of the code and explain the main goals of each function.

Gravity Handling
Gravity handling in a game like Flappy Bird is crucial for creating the character’s natural falling motion and challenging gameplay. In the game, gravity is simulated by continuously applying a downward force to the bird, which affects its vertical velocity.
This force is usually represented as a constant value that increments the bird’s downward speed over time, making it fall faster as the game progresses. By adjusting the gravity and the bird’s upward thrust, players experience a realistic and engaging flight mechanic. Properly managing gravity ensures that the bird’s movement feels fluid and responsive, while also balancing the difficulty to maintain an enjoyable gameplay experience.

Main Algorithms To Understand
Initialize Variable:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
# Initialize variables
bird_speed = 0 # Initial vertical speed of the bird
gravity = 0.25 # Strength of gravity
# Update bird's position in the game loop
bird_speed += gravity # Apply gravity to the bird's speed
bird_y += bird_speed # Update bird's vertical position
The bird’s vertical movement is governed by two key variables: bird_speed
and gravity
. Initially, bird_speed
is set to 0, meaning the bird starts with no vertical motion. Gravity, defined by gravity = 0.25
, continuously pulls the bird downward.
In each game loop iteration, gravity is added to bird_speed
, causing the bird to accelerate downward over time. Consequently, the bird’s vertical position, bird_y
, is updated based on this speed, creating a realistic simulation of falling and jumping. This dynamic adjustment ensures the bird’s movement is both responsive and natural.

Placing The Pipes:
The generate_pipe
function creates a pair of pipes for the Flappy Bird game.
# Function to generate a pair of pipes
def generate_pipe():
pipe_x = SCREEN_WIDTH # Start position of the pipe from the right side of the screen
pipe_height = random.randint(50, SCREEN_HEIGHT - pipe_gap - 50) # Randomize the height of the gap between pipes
upper_pipe_rect = pygame.Rect(pipe_x, 0, pipe_width, pipe_height) # Create upper pipe
lower_pipe_rect = pygame.Rect(pipe_x, pipe_height + pipe_gap, pipe_width, SCREEN_HEIGHT - pipe_height - pipe_gap) # Create lower pipe
return (upper_pipe_rect, lower_pipe_rect)
It starts by positioning the pipes off-screen to the right, ensuring they enter the view from the edge. The height of the gap between the pipes is randomized within a defined range, ensuring variability in the game’s difficulty. Two pygame.Rect
objects represent the pipes: the upper_pipe_rect
and lower_pipe_rect
. The upper pipe is positioned at the top of the screen and extends to the random height, while the lower pipe is positioned below the gap, extending from the gap’s bottom to the bottom of the screen. This function returns both pipe rectangles, which can be used to draw and update the pipes during gameplay.

Initializing The Game:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Set up the screen
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Bird")
This code snippet sets up the foundational elements for a Flappy Bird game using Pygame. It begins by initializing the Pygame library, which is essential for game development with Pygame.
The SCREEN_WIDTH
and SCREEN_HEIGHT
constants define the dimensions of the game window, which is set to 800 by 600 pixels. The pygame.display.set_mode()
function creates the game window with these dimensions, while pygame.display.set_caption()
sets the title of the window to “Flappy Bird.” This setup establishes the environment where the game will be played and visualized.

Load Images and Background:
# Load images
bird_img = pygame.image.load("bird.png").convert_alpha()
background_img = pygame.image.load("background.png").convert()
bird_img = pygame.image.load("bird.png").convert_alpha()
bird_img = pygame.image.load("path/to/bird.png").convert_alpha()
bird_img = pygame.transform.scale(bird_img, (bird_width, bird_height))
screen.blit(bird_img, (bird_x, bird_y))
images are loaded into the game using Pygame’s pygame.image.load()
function. The bird_img
variable is assigned the image for the bird, which is loaded with the convert_alpha()
method to handle transparency correctly.
The convert_alpha()
method is used to optimize the image by converting it to a format that supports transparency, ensuring that any transparent parts of the image are handled correctly.
The pygame.transform.scale()
function takes the original image and scales it to the new width and height, allowing you to adjust the size of the bird sprite to fit your game’s requirements. This ensures that the bird image appears at the correct size on the screen, providing a consistent visual experience in the game.
The screen.blit()
function takes two arguments: the image to be drawn (bird_img
) and a tuple representing the position on the screen where the image will be placed ((bird_x, bird_y)
).

Bird and Pipe Attributes:
The attributes for the bird and the pipes are established.
# Bird attributes
bird_rect = bird_img.get_rect(topleft=(SCREEN_WIDTH // 4, SCREEN_HEIGHT // 2))
bird_speed = 0
gravity = 0.25
jump_strength = -5
# Pipe attributes
pipe_width = 80
pipe_gap = 150
pipe_distance = 300 # Increased horizontal distance between pipes
pipe_speed = 3
pipes = []
The bird_rect
sets the bird’s initial position on the screen and is used for rendering and collision detection.
The bird_speed
and gravity
control the bird’s vertical movement, while jump_strength
determines how high the bird will jump when prompted. For the pipes, pipe_width
and pipe_gap
define their dimensions, with pipe_distance
controlling the space between consecutive pipes.
The pipe_speed
dictates how quickly the pipes move across the screen, and pipes
is an empty list that will later hold the active pipes. These settings lay the groundwork for the bird’s movement and the generation and scrolling of pipes in the game.

Generating and Drawing The Pipes:
The draw_pipes
function is responsible for rendering the pipes on the screen.
# Function to draw the pipes
def draw_pipes():
for pipe in pipes:
pygame.draw.rect(screen, (210, 221, 233), pipe[0]) # Draw upper pipe
pygame.draw.rect(screen, (210, 221, 233), pipe[1]) # Draw lower pipe
# Function to generate pipes
def generate_pipe():
pipe_x = SCREEN_WIDTH
pipe_height = random.randint(50, SCREEN_HEIGHT - pipe_gap - 50)
upper_pipe_rect = pygame.Rect(pipe_x, 0, pipe_width, pipe_height)
lower_pipe_rect = pygame.Rect(pipe_x, pipe_height + pipe_gap, pipe_width, SCREEN_HEIGHT - pipe_height - pipe_gap)
return (upper_pipe_rect, lower_pipe_rect)
The generate_pipe
function creates a new pair of pipes. It sets the initial x-position of the pipes to the right edge of the screen and randomly determines the height of the gap between the pipes.
The upper_pipe_rect
and lower_pipe_rect
are then defined as pygame.Rect
objects, representing the positions and sizes of the upper and lower pipes. These pipe rectangles are returned as a tuple.

Main Loop:
Manages the essential aspects of gameplay.
# Main game loop
clock = pygame.time.Clock()
while True:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and not game_over:
if event.key == pygame.K_SPACE:
bird_speed = jump_strength
# Update bird position
bird_speed += gravity
bird_rect.y += bird_speed
# Generate pipes
if len(pipes) == 0 or pipes[-1][0].x < SCREEN_WIDTH - pipe_distance:
pipes.append(generate_pipe())
# Move pipes
for pipe in pipes:
pipe[0].x -= pipe_speed
pipe[1].x -= pipe_speed
# Check for collision with bird
if bird_rect.colliderect(pipe[0]) or bird_rect.colliderect(pipe[1]) or bird_rect.top <= 0 or bird_rect.bottom >= SCREEN_HEIGHT:
game_over = True
# Check if bird passed the pipe
if pipe[0].x + pipe_width < bird_rect.x and not pipe[0].x < 0:
score += 1
# Remove off-screen pipes
pipes = [pipe for pipe in pipes if pipe[0].x > -pipe_width]
# Draw everything
screen.blit(background_img, (0, 0)) # Draw background image
screen.blit(bird_img, bird_rect)
draw_pipes()
# Display score
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
# Check for game over
if game_over:
game_over_text = font.render("Game Over! Press R to restart", True, (0, 0, 0))
screen.blit(game_over_text, (SCREEN_WIDTH // 2 - game_over_text.get_width() // 2, SCREEN_HEIGHT // 2 - game_over_text.get_height() // 2))
pygame.display.flip()
clock.tick(60)
# Restart game if game over and R key is pressed
keys = pygame.key.get_pressed()
if game_over and keys[pygame.K_r]:
bird_rect.y = SCREEN_HEIGHT // 2 - bird_rect.height // 2
bird_speed = 0
pipes = []
score = 0
game_over = False
The main game loop for the Flappy Bird implementation manages the essential aspects of gameplay, including event handling, bird movement, pipe generation and movement, and game-over conditions. It begins by processing user inputs, such as jumping when the space bar is pressed.
The loop continuously updates the bird’s position based on gravity and handles the generation and movement of pipes. Collisions between the bird and pipes, as well as the screen edges, are checked to determine if the game should end. The game state, including the score and game-over messages, is rendered and displayed to the player. If the game ends, the player can restart by pressing ‘R’, which resets the game variables and clears the pipes. This loop ensures that the game runs smoothly, providing a dynamic and engaging experience for players.


Summary
In conclusion, we’ve successfully completed coding the Flappy Bird game using Python and Pygame. Throughout the development process, we implemented essential game mechanics including gravity, jumping, and pipe generation. We also integrated collision detection and scoring systems to enhance the gameplay experience.
The game features a simple yet engaging interface where players control a bird to navigate through obstacles, aiming to achieve the highest score possible. With the game over screen and restart functionality, players can enjoy replaying and improving their performance.
By understanding and implementing these core components, we’ve created a functional and enjoyable version of the Flappy Bird game. This project not only demonstrates key programming concepts but also provides a foundation for further enhancements and customizations.
Post Comment