Build a Flappy Bird Clone with Python and Pygame – Full Source Code
This article walks you through creating a Flappy Bird‑style game using Python 3 and the pygame library, covering installation of pygame, showcasing gameplay screenshots, and providing the complete source code with explanations and future refactoring plans.
Introduction
I previously played Flappy Bird on my phone and decided to recreate it using Python 3 and the pygame module. The resulting game runs smoothly and will surprise you.
1. Demo
After downloading the game, install the pygame module in your Python environment (if it is not already installed) with pip install pygame. The first screen you see after running the .py file looks like this:
Clicking the “Play” button in the above image produces the following effect:
The game includes background music; be sure to download the accompanying assets together with the code so the music plays during gameplay.
2. Full Code
The code uses several assets (background images, music, etc.). You can download them from this link . Below is the complete source code (kept unchanged for clarity):
import math
import os
import time
from random import randint, uniform
import pygame
from pygame.locals import *
from collections import deque
FPS = 60
BK_WIDTH = 900 # background width
BK_HEIGHT = 650 # background height
PIPE_WIDTH = 80
PIPE_HEIGHT = 10
PIPE_HEAD_HEIGHT = 32
BK_MOVE_SPEED = 0.22
ADD_TIME = 2500
TOTAL_PIPE_BODY = int(3/5 * BK_HEIGHT)
PIPE_RATE = 0.96
a_i = "bird-wingup"
b_i = "bird-wingmid"
c_i = "bird-wingdown"
INITAL_SPEED = -0.37
BIRD_WIDTH = 50
BIRD_HEIGHT = 40
BIRD_INIT_SCORE = 7
STONE_ADD_TIME = 1000
STONE_WIDTH = 40
STONE_HEIGHT = 30
STONE_LEVEL = 4
BUTTON_WIDTH = 140
BUTT0N_HEIGHT = 60
BULLET_SPEED = 0.32
BULLET_WIETH = 50
BULLET_HEIGHT = 30
pygame.init()
screen = pygame.display.set_mode((BK_WIDTH, BK_HEIGHT))
pygame.mixer.init()
music_lose = pygame.mixer.Sound("lose.wav")
music1 = pygame.mixer.Sound("touch.wav")
pygame.mixer.music.load("bkm.mp3")
font = pygame.font.SysFont('comicsansms', 25, bold=True)
def little_bird(list):
global a_i, b_i, c_i
a_i, b_i, c_i = list[0], list[1], list[2]
def seteasy(list):
global BK_MOVE_SPEED, ADD_TIME, TOTAL_PIPE_BODY, PIPE_RATE, STONE_LEVEL, BIRD_INIT_SCORE
BK_MOVE_SPEED, ADD_TIME, TOTAL_PIPE_BODY, PIPE_RATE, STONE_LEVEL, BIRD_INIT_SCORE = list
class Bullet(pygame.sprite.Sprite):
speed = BULLET_SPEED
width = BULLET_WIETH
height = BULLET_HEIGHT
def __init__(self, bird, images):
super(Bullet, self).__init__()
self.x, self.y = bird.x, bird.y
self.bullet = images
self.mask_bullet = pygame.mask.from_surface(self.bullet)
def update(self):
self.x += self.speed * frames_to_msec(1)
@property
def image(self):
return self.bullet
@property
def mask(self):
return self.mask_bullet
@property
def rect(self):
return Rect(self.x, self.y, Bullet.width, Bullet.height)
def visible(self):
return 0 < self.x < BK_WIDTH + Bullet.width
class Bird(pygame.sprite.Sprite):
width = BIRD_WIDTH
height = BIRD_HEIGHT
sink_gravity = 0.001
def __init__(self, x, y, level, images):
super(Bird, self).__init__()
self.x, self.y = x, y
self.wing_up, self.wing_mid, self.wing_down = images
self.mask_wing_up = pygame.mask.from_surface(self.wing_up)
self.mask_wing_mid = pygame.mask.from_surface(self.wing_mid)
self.mask_wing_down = pygame.mask.from_surface(self.wing_down)
self.inital_speed = 0
self.level = level
self.score = 0
def update(self, t):
y_ = self.inital_speed * t + 0.5 * self.sink_gravity * t * t
if self.inital_speed <= 0.3:
self.inital_speed += self.sink_gravity * t
self.y += y_
@property
def image(self):
if pygame.time.get_ticks() % 400 >= 120:
return self.wing_up
elif pygame.time.get_ticks() % 400 >= 280:
return self.wing_mid
else:
return self.wing_down
@property
def mask(self):
if pygame.time.get_ticks() % 400 >= 120:
return self.mask_wing_up
elif pygame.time.get_ticks() % 400 >= 280:
return self.mask_wing_mid
else:
return self.mask_wing_down
@property
def rect(self):
return Rect(self.x, self.y, Bird.width, Bird.height)
class Pipe(pygame.sprite.Sprite):
width = PIPE_WIDTH
pipe_head_height = PIPE_HEAD_HEIGHT
add_time = ADD_TIME
def __init__(self, pipe_head_image, pipe_body_image):
super(Pipe, self).__init__()
self.x = float(BK_WIDTH - 1)
self.score_count = False
self.image = pygame.Surface((Pipe.width, BK_HEIGHT), SRCALPHA)
self.image.convert()
self.image.fill((0, 0, 0, 0))
total_pipe_length = TOTAL_PIPE_BODY
self.bottom_length = randint(int(0.1 * total_pipe_length), int(0.8 * total_pipe_length))
self.top_length = total_pipe_length - self.bottom_length
for i in range(1, self.bottom_length + 1):
self.image.blit(pipe_body_image, (0, BK_HEIGHT - i))
bottom_head_y = BK_HEIGHT - self.bottom_length - self.pipe_head_height
self.image.blit(pipe_head_image, (0, bottom_head_y))
for i in range(-PIPE_HEIGHT, self.top_length - PIPE_HEIGHT):
self.image.blit(pipe_body_image, (0, i))
self.image.blit(pipe_head_image, (0, self.top_length))
self.mask = pygame.mask.from_surface(self.image)
@property
def rect(self):
return Rect(self.x, 0, Pipe.width, PIPE_HEIGHT)
@property
def visible(self):
return -Pipe.width < self.x < BK_WIDTH
def update(self, delta_frames=1):
self.x -= BK_MOVE_SPEED * frames_to_msec(delta_frames)
def collides(self, bird):
return pygame.sprite.collide_mask(self, bird)
def change_add_time():
Pipe.add_time = int((Pipe.add_time * PIPE_RATE) / 100) * 100
class Stone(pygame.sprite.Sprite):
add_time = STONE_ADD_TIME
width = STONE_WIDTH
height = STONE_HEIGHT
def __init__(self, image):
super(Stone, self).__init__()
self.x = BK_WIDTH - 5
self.y = randint(1, int(0.95 * BK_HEIGHT))
self.speed = uniform(0.1, 0.5)
self.stone_image = image
self.mask_image = pygame.mask.from_surface(self.image)
@property
def rect(self):
return Rect(self.x, self.y, Stone.width, Stone.height)
@property
def image(self):
return self.stone_image
@property
def mask(self):
return self.mask_image
def update(self, frame=1):
self.x -= int(self.speed * frames_to_msec(frame))
def collides(self, b):
return pygame.sprite.collide_mask(self, b)
def visible(self):
return -self.width < self.x < BK_WIDTH
def level_goal(bird):
return bird.level * BIRD_INIT_SCORE
def load_image(img_file_name):
file_name = os.path.join(".", "images", img_file_name)
img = pygame.image.load(file_name)
img.convert()
return img
def search_bk(bird):
return "bk" + str(bird.level)
img_x = load_image('backgroundx.png')
def load_images():
return {
'bk1': load_image('background.png'),
'bk2': load_image('background2.png'),
'bk3': load_image('background3.png'),
'bk4': load_image('background4.png'),
'bk5': load_image('background5.png'),
'bk6': load_image('background6.png'),
'stone': load_image('stone.png'),
'bullet': load_image('bullet.png'),
'pipe-end': load_image('pipe_end.png'),
'pipe-body': load_image('pipe_body.png'),
'f_u': load_image('fenghuang_up.png'),
'f_m': load_image('fenghuang_mid.png'),
'f_w': load_image('fenghuang_down.png'),
'bird-wingup': load_image('bird_wing_up.png'),
'bird-wingmid': load_image('bird_wing_mid.png'),
'bird-wingdown': load_image('bird_wing_down.png')
}
def frames_to_msec(frames, fps=FPS):
return 1000.0 * frames / fps
def msec_to_frames(milliseconds, fps=FPS):
return fps * milliseconds / 1000.0
def game_loop():
pygame.mixer.music.play(-1)
pygame.display.set_caption("Flappy Bird")
clock = pygame.time.Clock()
images = load_images()
bird = Bird(20, BK_HEIGHT // 2, 1, (images[a_i], images[b_i], images[c_i]))
score_font = pygame.font.SysFont(None, 50, bold=True)
score_font2 = pygame.font.SysFont(None, 40, bold=True)
score_font3 = pygame.font.SysFont(None, 70, bold=True)
pipes = deque()
stones = pygame.sprite.Group()
bullets = pygame.sprite.Group()
pause = done = False
frames = 0
while not done:
clock.tick(FPS)
if not (pause or frames % msec_to_frames(Pipe.add_time)):
pp = Pipe(images['pipe-end'], images['pipe-body'])
pipes.append(pp)
if not (pause or frames % msec_to_frames(Stone.add_time) or bird.level < STONE_LEVEL):
ss = Stone(images['stone'])
stones.add(ss)
for e in pygame.event.get():
if e.type == QUIT:
done = True
break
elif e.type == KEYUP:
if e.key == K_p:
pause = not pause
elif e.key == K_d:
bb = Bullet(bird, images['bullet'])
bullets.add(bb)
elif e.key in (K_s, K_SPACE):
bird.inital_speed = INITAL_SPEED
elif e.type == MOUSEBUTTONUP:
bird.inital_speed = INITAL_SPEED
if pause:
continue
pygame.sprite.groupcollide(stones, bullets, True, True, pygame.sprite.collide_mask)
pipe_collision = any(p.collides(bird) for p in pipes)
stone_collision = any(s.collides(bird) for s in stones)
if pipe_collision or stone_collision or bird.y <= 0 or bird.y > BK_HEIGHT - Bird.height:
pygame.mixer.music.stop()
pygame.mixer.Sound.play(music_lose, -1)
time.sleep(3.5)
pygame.mixer.Sound.stop(music_lose)
time.sleep(0.1)
done = True
continue
screen.blit(images[search_bk(bird)], (0, 0))
while pipes and not pipes[0].visible:
pipes.popleft()
for s in list(stones):
if not s.visible():
stones.remove(s)
for b in list(bullets):
if not b.visible():
bullets.remove(b)
for p in pipes:
p.update()
screen.blit(p.image, p.rect)
for s in stones:
s.update()
screen.blit(s.image, s.rect)
for b in bullets:
b.update()
screen.blit(b.bullet, b.rect)
for p in pipes:
if bird.x > p.x + Pipe.width and not p.score_count:
bird.score += 1
p.score_count = True
sl = score_font.render("level:", True, (255, 255, 255))
sc = score_font.render("score:", True, (255, 255, 255))
sl2 = score_font2.render(str(bird.level), True, (255, 255, 255))
sc2 = score_font2.render(str(bird.score), True, (255, 255, 255))
screen.blit(sc, (BK_WIDTH - 170, 20))
screen.blit(sl, (BK_WIDTH - 320, 20))
screen.blit(sc2, (BK_WIDTH - 50, 27))
screen.blit(sl2, (BK_WIDTH - 210, 27))
bird.update(frames_to_msec(1))
screen.blit(bird.image, bird.rect)
pygame.display.flip()
if bird.score >= level_goal(bird):
change_add_time()
pipes.clear()
stones.empty()
bullets.empty()
bird.level += 1
if bird.level <= 6:
s3 = score_font3.render("Next Level", True, (255, 255, 255))
screen.blit(s3, (BK_WIDTH // 2 - 150, BK_HEIGHT // 2 - 50))
pygame.display.flip()
time.sleep(2)
else:
s3 = score_font3.render("You Win!", True, (255, 255, 255))
screen.blit(s3, (BK_WIDTH // 2 - 150, BK_HEIGHT // 2 - 50))
pygame.display.flip()
time.sleep(2)
exit()
frames += 1
pygame.mixer.music.stop()
Pipe.add_time = ADD_TIME
main()
def quit_but():
pygame.quit()
exit()
def buttons(x, y, w, h, color, color2, text, action, list=[]):
mouse_position = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse_position[0] > x and y + h > mouse_position[1] > y:
color = color2
if click[0] == 1 and action is not None:
pygame.mixer.Sound.play(music1, -1)
time.sleep(0.215)
pygame.mixer.Sound.stop(music1)
if list:
action(list)
else:
action()
pygame.draw.rect(screen, color, (x, y, w, h))
TextSurf = font.render(text, True, (0, 0, 0))
TextRect = TextSurf.get_rect()
TextRect.center = ((x + w / 2), (y + h / 2))
screen.blit(TextSurf, TextRect)
pygame.display.update()
def setting():
screen.blit(img_x, (0, 0))
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
buttons(100, 200, BUTTON_WIDTH, BUTT0N_HEIGHT, (255, 0, 0), (170, 0, 0), 'easy', seteasy, [0.19, 2500, int(5/11 * BK_HEIGHT), 0.97, 5, 6])
buttons(400, 200, BUTTON_WIDTH, BUTT0N_HEIGHT, (0, 255, 0), (0, 170, 0), 'normal', seteasy, [0.19, 2500, int(3/5 * BK_HEIGHT), 0.96, 7, 4])
buttons(700, 200, BUTTON_WIDTH, BUTT0N_HEIGHT, (0, 0, 255), (0, 0, 160), 'hard', seteasy, [0.21, 1300, int(9/14 * BK_HEIGHT), 0.96, 2, 1])
buttons(700, 550, BUTTON_WIDTH, BUTT0N_HEIGHT, (0, 0, 255), (0, 0, 160), 'back', main)
buttons(100, 400, BUTTON_WIDTH, BUTT0N_HEIGHT, (255, 0, 0), (170, 0, 0), 'huo lie niao', little_bird, ["f_u", "f_m", "f_w"])
buttons(400, 400, BUTTON_WIDTH, BUTT0N_HEIGHT, (0, 255, 0), (0, 170, 0), 'xiao niao', little_bird, ["bird-wingup", "bird-wingmid", "bird-wingdown"])
def main():
screen.blit(img_x, (0, 0))
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
buttons((BK_WIDTH - BUTTON_WIDTH)//2, (BK_HEIGHT - BUTT0N_HEIGHT - 100)//2, BUTTON_WIDTH, BUTT0N_HEIGHT, (0, 255, 0), (0, 170, 0), 'Play!', game_loop)
buttons((BK_WIDTH - BUTTON_WIDTH)//2, (BK_HEIGHT - BUTT0N_HEIGHT + 100)//2, BUTTON_WIDTH, BUTT0N_HEIGHT, (0, 0, 255), (0, 0, 160), 'setting', setting)
buttons((BK_WIDTH - BUTTON_WIDTH)//2, (BK_HEIGHT - BUTT0N_HEIGHT + 300)//2, BUTTON_WIDTH, BUTT0N_HEIGHT, (255, 0, 0), (170, 0, 0), 'Quit', quit_but)
if __name__ == "__main__":
main()Conclusion
This is version 1 of the project; it is written in a procedural style for simplicity. Future work will refactor the code into classes and split it across multiple modules for better organization.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
