FLAPPY BIRD GAME USING PYTHON AND IT'S MODULE:
![]() |
Flappy Bird Game In Python |
DOWNLOAD SOURCE CODE WITH MEDIA IMAGE AND SONG
CODE DESCRIPTION:
Importing Libraries:
- The code starts by importing the necessary Python libraries:
- random: Used for generating random numbers.
- sys: Used to exit the program.
- pygame: A popular library for game development in Python.
- pygame.locals: Contains constants and data types used in Pygame.
Global Variables:
- Several global variables are defined, including constants for screen dimensions, file paths for game assets (images and sounds), and various game parameters like velocities and pipe positions.
welcomeScreen Function:
- This function displays a welcome screen with the game's title and instructions.
- It waits for the player to press the spacebar or up arrow key to start the game.
- The game will exit if the player closes the window or presses the Escape key.
mainGame Function:
- This is the main game loop where the actual gameplay occurs.
- It includes the game's core logic, such as controlling the bird's movement, detecting collisions, updating the score, and managing pipes.
- The loop continues until the player loses the game or exits manually.
- It also checks for user input to make the bird flap when the spacebar or up arrow key is pressed.
isCollide Function:
- This function checks for collisions between the bird and the ground or pipes.
- It returns True if a collision is detected, indicating that the game should end.
getRandomPipe Function:
- This function generates random positions for two pipes (one upper and one lower) to appear on the screen.
- The pipes are created with different heights and positions to create the appearance of a gap for the bird to pass through.
Initialization:
- The code initializes the Pygame library, sets up the game window, and loads various game assets (images and sounds).
- It also defines a clock object to control the frame rate.
Game Assets:
- Game sprites, including numbers, the background, the player (bird), the base, and pipes, are loaded into memory.
- The game sounds for events like hitting a pipe, scoring a point, and flapping the bird's wings are also loaded.
Game Loop:
- The program enters a loop where it first displays the welcome screen.
- After the player starts the game, it enters the main game loop (mainGame function).
- The loop continues until the player loses or manually exits the game.
Score Display:
- The player's score is displayed on the screen during gameplay.
Event Handling:
- The code continuously checks for events, including user input and collisions, to update the game state.
Game Over:
- When a collision is detected or the player quits the game, the game loop exits.
SOURCE CODE:
import random # For generating random numbers
import sys # We will use sys.exit to exit the program
import pygame
from pygame.locals import * # Basic pygame imports
# Global Variables for the game
FPS = 32
SCREENWIDTH = 289
SCREENHEIGHT = 511
SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
GROUNDY = SCREENHEIGHT * 0.8
GAME_SPRITES = {}
GAME_SOUNDS = {}
PLAYER = r'C:\Users\madde\Desktop\game\BIRDGAME\IMAGE\bird.png'
BACKGROUND = r'C:\Users\madde\Desktop\game\BIRDGAME\IMAGE\background.png'
PIPE = r'C:\Users\madde\Desktop\game\BIRDGAME\IMAGE\pipe.png'
def welcomeScreen():
"""
Shows welcome images on the screen
"""
playerx = int(SCREENWIDTH / 5)
playery = int((SCREENHEIGHT - GAME_SPRITES['player'].get_height()) / 2)
messagex = int((SCREENWIDTH - GAME_SPRITES['message'].get_width()) / 2)
messagey = int(SCREENHEIGHT * 0.13)
basex = 0
while True:
for event in pygame.event.get():
# if user clicks on cross button, close the game
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
# If the user presses space or up key, start the game for them
elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
return
else:
SCREEN.blit(GAME_SPRITES['background'], (0, 0))
SCREEN.blit(GAME_SPRITES['player'], (playerx, playery))
SCREEN.blit(GAME_SPRITES['message'], (messagex, messagey))
SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY))
pygame.display.update()
FPSCLOCK.tick(FPS)
def mainGame():
score = 0
playerx = int(SCREENWIDTH / 5)
playery = int(SCREENWIDTH / 2)
basex = 0
# Create 2 pipes for blitting on the screen
newPipe1 = getRandomPipe()
newPipe2 = getRandomPipe()
# my List of upper pipes
upperPipes = [
{'x': SCREENWIDTH + 200, 'y': newPipe1[0]['y']},
{'x': SCREENWIDTH + 200 + (SCREENWIDTH / 2), 'y': newPipe2[0]['y']},
]
# my List of lower pipes
lowerPipes = [
{'x': SCREENWIDTH + 200, 'y': newPipe1[1]['y']},
{'x': SCREENWIDTH + 200 + (SCREENWIDTH / 2), 'y': newPipe2[1]['y']},
]
pipeVelX = -4
playerVelY = -9
playerMaxVelY = 10
playerMinVelY = -8
playerAccY = 1
playerFlapAccv = -8 # velocity while flapping
playerFlapped = False # It is true only when the bird is flapping
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
if playery > 0:
playerVelY = playerFlapAccv
playerFlapped = True
GAME_SOUNDS['wing'].play()
crashTest = isCollide(playerx, playery, upperPipes,
lowerPipes) # This function will return true if
import sys # We will use sys.exit to exit the program
import pygame
from pygame.locals import * # Basic pygame imports
# Global Variables for the game
FPS = 32
SCREENWIDTH = 289
SCREENHEIGHT = 511
SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
GROUNDY = SCREENHEIGHT * 0.8
GAME_SPRITES = {}
GAME_SOUNDS = {}
PLAYER = r'C:\Users\madde\Desktop\game\BIRDGAME\IMAGE\bird.png'
BACKGROUND = r'C:\Users\madde\Desktop\game\BIRDGAME\IMAGE\background.png'
PIPE = r'C:\Users\madde\Desktop\game\BIRDGAME\IMAGE\pipe.png'
def welcomeScreen():
"""
Shows welcome images on the screen
"""
playerx = int(SCREENWIDTH / 5)
playery = int((SCREENHEIGHT - GAME_SPRITES['player'].get_height()) / 2)
messagex = int((SCREENWIDTH - GAME_SPRITES['message'].get_width()) / 2)
messagey = int(SCREENHEIGHT * 0.13)
basex = 0
while True:
for event in pygame.event.get():
# if user clicks on cross button, close the game
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
# If the user presses space or up key, start the game for them
elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
return
else:
SCREEN.blit(GAME_SPRITES['background'], (0, 0))
SCREEN.blit(GAME_SPRITES['player'], (playerx, playery))
SCREEN.blit(GAME_SPRITES['message'], (messagex, messagey))
SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY))
pygame.display.update()
FPSCLOCK.tick(FPS)
def mainGame():
score = 0
playerx = int(SCREENWIDTH / 5)
playery = int(SCREENWIDTH / 2)
basex = 0
# Create 2 pipes for blitting on the screen
newPipe1 = getRandomPipe()
newPipe2 = getRandomPipe()
# my List of upper pipes
upperPipes = [
{'x': SCREENWIDTH + 200, 'y': newPipe1[0]['y']},
{'x': SCREENWIDTH + 200 + (SCREENWIDTH / 2), 'y': newPipe2[0]['y']},
]
# my List of lower pipes
lowerPipes = [
{'x': SCREENWIDTH + 200, 'y': newPipe1[1]['y']},
{'x': SCREENWIDTH + 200 + (SCREENWIDTH / 2), 'y': newPipe2[1]['y']},
]
pipeVelX = -4
playerVelY = -9
playerMaxVelY = 10
playerMinVelY = -8
playerAccY = 1
playerFlapAccv = -8 # velocity while flapping
playerFlapped = False # It is true only when the bird is flapping
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
if playery > 0:
playerVelY = playerFlapAccv
playerFlapped = True
GAME_SOUNDS['wing'].play()
crashTest = isCollide(playerx, playery, upperPipes,
lowerPipes) # This function will return true if
the player is crashed
if crashTest:
return
# check for score
playerMidPos = playerx + GAME_SPRITES['player'].get_width() / 2
for pipe in upperPipes:
pipeMidPos = pipe['x'] + GAME_SPRITES['pipe'][0].get_width() / 2
if pipeMidPos <= playerMidPos < pipeMidPos + 4:
score += 1
print(f"Your score is {score}")
GAME_SOUNDS['point'].play()
if playerVelY < playerMaxVelY and not playerFlapped:
playerVelY += playerAccY
if playerFlapped:
playerFlapped = False
playerHeight = GAME_SPRITES['player'].get_height()
playery = playery + min(playerVelY, GROUNDY - playery - playerHeight)
# move pipes to the left
for upperPipe, lowerPipe in zip(upperPipes, lowerPipes):
upperPipe['x'] += pipeVelX
lowerPipe['x'] += pipeVelX
# Add a new pipe when the first is about to cross the leftmost part of the screen
if 0 < upperPipes[0]['x'] < 5:
newpipe = getRandomPipe()
upperPipes.append(newpipe[0])
lowerPipes.append(newpipe[1])
# if the pipe is out of the screen, remove it
if upperPipes[0]['x'] < -GAME_SPRITES['pipe'][0].get_width():
upperPipes.pop(0)
lowerPipes.pop(0)
# Lets blit our sprites now
SCREEN.blit(GAME_SPRITES['background'], (0, 0))
for upperPipe, lowerPipe in zip(upperPipes, lowerPipes):
SCREEN.blit(GAME_SPRITES['pipe'][0], (upperPipe['x'], upperPipe['y']))
SCREEN.blit(GAME_SPRITES['pipe'][1], (lowerPipe['x'], lowerPipe['y']))
SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY))
SCREEN.blit(GAME_SPRITES['player'], (playerx, playery))
myDigits = [int(x) for x in list(str(score))]
width = 0
for digit in myDigits:
width += GAME_SPRITES['numbers'][digit].get_width()
Xoffset = (SCREENWIDTH - width) / 2
for digit in myDigits:
SCREEN.blit(GAME_SPRITES['numbers'][digit], (Xoffset, SCREENHEIGHT * 0.12))
Xoffset += GAME_SPRITES['numbers'][digit].get_width()
pygame.display.update()
FPSCLOCK.tick(FPS)
def isCollide(playerx, playery, upperPipes, lowerPipes):
if playery > GROUNDY - 25 or playery < 0:
GAME_SOUNDS['hit'].play()
return True
for pipe in upperPipes:
pipeHeight = GAME_SPRITES['pipe'][0].get_height()
if (playery < pipeHeight + pipe['y'] and abs(playerx - pipe['x']) <
if crashTest:
return
# check for score
playerMidPos = playerx + GAME_SPRITES['player'].get_width() / 2
for pipe in upperPipes:
pipeMidPos = pipe['x'] + GAME_SPRITES['pipe'][0].get_width() / 2
if pipeMidPos <= playerMidPos < pipeMidPos + 4:
score += 1
print(f"Your score is {score}")
GAME_SOUNDS['point'].play()
if playerVelY < playerMaxVelY and not playerFlapped:
playerVelY += playerAccY
if playerFlapped:
playerFlapped = False
playerHeight = GAME_SPRITES['player'].get_height()
playery = playery + min(playerVelY, GROUNDY - playery - playerHeight)
# move pipes to the left
for upperPipe, lowerPipe in zip(upperPipes, lowerPipes):
upperPipe['x'] += pipeVelX
lowerPipe['x'] += pipeVelX
# Add a new pipe when the first is about to cross the leftmost part of the screen
if 0 < upperPipes[0]['x'] < 5:
newpipe = getRandomPipe()
upperPipes.append(newpipe[0])
lowerPipes.append(newpipe[1])
# if the pipe is out of the screen, remove it
if upperPipes[0]['x'] < -GAME_SPRITES['pipe'][0].get_width():
upperPipes.pop(0)
lowerPipes.pop(0)
# Lets blit our sprites now
SCREEN.blit(GAME_SPRITES['background'], (0, 0))
for upperPipe, lowerPipe in zip(upperPipes, lowerPipes):
SCREEN.blit(GAME_SPRITES['pipe'][0], (upperPipe['x'], upperPipe['y']))
SCREEN.blit(GAME_SPRITES['pipe'][1], (lowerPipe['x'], lowerPipe['y']))
SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY))
SCREEN.blit(GAME_SPRITES['player'], (playerx, playery))
myDigits = [int(x) for x in list(str(score))]
width = 0
for digit in myDigits:
width += GAME_SPRITES['numbers'][digit].get_width()
Xoffset = (SCREENWIDTH - width) / 2
for digit in myDigits:
SCREEN.blit(GAME_SPRITES['numbers'][digit], (Xoffset, SCREENHEIGHT * 0.12))
Xoffset += GAME_SPRITES['numbers'][digit].get_width()
pygame.display.update()
FPSCLOCK.tick(FPS)
def isCollide(playerx, playery, upperPipes, lowerPipes):
if playery > GROUNDY - 25 or playery < 0:
GAME_SOUNDS['hit'].play()
return True
for pipe in upperPipes:
pipeHeight = GAME_SPRITES['pipe'][0].get_height()
if (playery < pipeHeight + pipe['y'] and abs(playerx - pipe['x']) <
GAME_SPRITES['pipe'][0].get_width()):
GAME_SOUNDS['hit'].play()
return True
for pipe in lowerPipes:
if (playery + GAME_SPRITES['player'].get_height() > pipe['y']) and
GAME_SOUNDS['hit'].play()
return True
for pipe in lowerPipes:
if (playery + GAME_SPRITES['player'].get_height() > pipe['y']) and
abs(playerx - pipe['x']) < \
GAME_SPRITES['pipe'][0].get_width():
GAME_SOUNDS['hit'].play()
return True
return False
def getRandomPipe():
"""
Generate positions of two pipes(one bottom straight and one top rotated )
GAME_SPRITES['pipe'][0].get_width():
GAME_SOUNDS['hit'].play()
return True
return False
def getRandomPipe():
"""
Generate positions of two pipes(one bottom straight and one top rotated )
for blitting on the screen
"""
pipeHeight = GAME_SPRITES['pipe'][0].get_height()
offset = SCREENHEIGHT / 3
y2 = offset + random.randrange(0, int(SCREENHEIGHT -
"""
pipeHeight = GAME_SPRITES['pipe'][0].get_height()
offset = SCREENHEIGHT / 3
y2 = offset + random.randrange(0, int(SCREENHEIGHT -
GAME_SPRITES['base'].get_height() - 1.2 * offset))
pipeX = SCREENWIDTH + 10
y1 = pipeHeight - y2 + offset
pipe = [
{'x': pipeX, 'y': -y1}, # upper Pipe
{'x': pipeX, 'y': y2} # lower Pipe
]
return pipe
if __name__ == "__main__":
# This will be the main point from where our game will start
pygame.init() # Initialize all pygame's modules
FPSCLOCK = pygame.time.Clock()
pygame.display.set_caption('Flappy Bird by codewithgaurav')
GAME_SPRITES['numbers'] = (
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\0.png').
pipeX = SCREENWIDTH + 10
y1 = pipeHeight - y2 + offset
pipe = [
{'x': pipeX, 'y': -y1}, # upper Pipe
{'x': pipeX, 'y': y2} # lower Pipe
]
return pipe
if __name__ == "__main__":
# This will be the main point from where our game will start
pygame.init() # Initialize all pygame's modules
FPSCLOCK = pygame.time.Clock()
pygame.display.set_caption('Flappy Bird by codewithgaurav')
GAME_SPRITES['numbers'] = (
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\0.png').
convert_alpha(),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\1.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\1.png').
convert_alpha(),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\2.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\2.png').
convert_alpha(),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\3.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\3.png').
convert_alpha(),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\4.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\4.png').
convert_alpha(),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\5.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\5.png').
convert_alpha(),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\6.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\6.png').
convert_alpha(),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\7.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\7.png').
convert_alpha(),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\8.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\8.png').
convert_alpha(),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\9.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\9.png').
convert_alpha(),
)
GAME_SPRITES['message'] = pygame.image.load
)
GAME_SPRITES['message'] = pygame.image.load
(r'C:\Users\madde\Desktop\game\BIRDGAME\IMAGE\FRONT.png').convert_alpha()
GAME_SPRITES['base'] = pygame.image.load
GAME_SPRITES['base'] = pygame.image.load
(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\base.png').convert_alpha()
GAME_SPRITES['pipe'] = (pygame.transform.rotate(pygame.image.load
GAME_SPRITES['pipe'] = (pygame.transform.rotate(pygame.image.load
(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\pipe.png').convert_alpha(), 180),
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\pipe.png').
pygame.image.load(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\pipe.png').
convert_alpha())
# Game sounds
GAME_SOUNDS['die'] = pygame.mixer.Sound
# Game sounds
GAME_SOUNDS['die'] = pygame.mixer.Sound
(r'C:\Users\madde\PycharmProjects\BIRDGAME\SOUND\die.wav')
GAME_SOUNDS['hit'] = pygame.mixer.Sound
GAME_SOUNDS['hit'] = pygame.mixer.Sound
(r'C:\Users\madde\PycharmProjects\BIRDGAME\SOUND\hit.wav')
GAME_SOUNDS['point'] = pygame.mixer.Sound
GAME_SOUNDS['point'] = pygame.mixer.Sound
(r'C:\Users\madde\PycharmProjects\BIRDGAME\SOUND\point.wav')
GAME_SOUNDS['swoosh'] = pygame.mixer.Sound
GAME_SOUNDS['swoosh'] = pygame.mixer.Sound
(r'C:\Users\madde\PycharmProjects\BIRDGAME\SOUND\swoosh.wav')
GAME_SOUNDS['wing'] = pygame.mixer.Sound
GAME_SOUNDS['wing'] = pygame.mixer.Sound
(r'C:\Users\madde\PycharmProjects\BIRDGAME\SOUND\wing.wav')
GAME_SPRITES['background'] = pygame.image.load
GAME_SPRITES['background'] = pygame.image.load
(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\background.png').convert()
GAME_SPRITES['player'] = pygame.image.load
GAME_SPRITES['player'] = pygame.image.load
(r'C:\Users\madde\PycharmProjects\BIRDGAME\IMAGE\bird.png').convert_alpha()
while True:
welcomeScreen() # Shows welcome screen to the user until he presses a button
mainGame() # This is the main game function
while True:
welcomeScreen() # Shows welcome screen to the user until he presses a button
mainGame() # This is the main game function
DOWNLOAD SOURCE CODE WITH MEDIA IMAGE AND SONG
OUTPUT:
![]() |
output of flappy bird game in python |
2 Comments
sir can you provide the codes in files ?? with all the images and its relative path ?
ReplyDeletethe code will now provided
Delete