Flappy Bird In Python Pygame with source code

Flappy Bird In Python Pygame

OPERATING EVENTS AND TAKING INPUTS FROM THE USER

Till now, we did so much we loaded all the sprites and sounds, we created welcomeScreen function in which we have given playerx, playery, messagex, messagey and basex.

But there is nothing yet when you’ll run the code you will see that our window appears for a second and then will disappear.

So now we’ll create a while infinite loop so that our screen can’t disappear within a second but with our choice and we have to blit the images and play intro music as well.

Before going further to code Flappy Bird In Python Pygame, let’s have a look at the code after then we will explain them.

while True:
        for event in pygame.event.get():
             #If user clicks on Cross or presses the Escape button Close the Game
            if event.type== QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()

What we are doing is we are commanding that don’t close the game until we want to close it, after then we accessed all the events which are going on via for event in pygame.event.get():

Events are anything that you do with your computer either pressing a keyboard’s key or moving the mouse cursor all are said to be events.

And from that Events, we checked whether users clicks on the Cross button or presses the Escape key. If yes then we will close the pygame window with the help of pygame.quit() and sys.exit().

Now, we will check for other Events, we want that if the user presses the Space bar or Up arrow key then we will start the game for them.

ACCESSING EVENTS

while True:
        for event in pygame.event.get():
             #If user clicks on Cross or presses the Escape button Close the Game
            if event.type== QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
    
             ## If user presses the Space bar or up arrow key start the game for them
            elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
                return

So we made an infinite loop and inside this, we first accessed all the events that are happening within the game.
Events are anything that you do with your computer either pressing a keyboard’s key or moving the mouse cursor all are said to be events.

And from that Events, we checked whether users clicks on the Cross button or presses the Escape key. If yes then we will close the pygame window with the help of pygame.quit() and sys.exit().

Now, we will check for other Events, we want that if the user presses the Space bar or Up arrow key then we will start the game for them.

while True:
        for event in pygame.event.get():
             #If user clicks on Cross or presses the Escape button Close the Game
            if event.type== QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
    
             ## If user presses the Space bar or up arrow key start the game for them
            elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
                return

Even though we have coded so much but our screen is still black there is no image, no sound, nothing because we haven’t displayed them yet.
So, let’s first blit our images after then we’ll check some mouse events for

while True:
        for event in pygame.event.get():
             #If user clicks on Cross or presses the Escape button Close the Game
            if event.type== QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()

            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)

Under else statement, we blitted our images and then updated them.
Screen.blit() is a funtction which takes two arguments first is image we want to blit and second is coordinates. for ex- SCREEN.blit(image, coordinates)

And then we typed ‘pygame.display.update()’ which is very important it updates the window and then we have ‘FPSClock’ which controls our FPS.

Now, we have displayed our images and we don’t have black or dark screen to see. We have our beautiful welcome screen. Let’s have a look.

welcome screen of Flappy Bird game
Welcome Screen

ACCESSING MOUSE EVENTS

Now, we are glad to see some visuals on our game window now we would operate some Mouse events. We want two things first is when we click on the play button our game should be Start and Second when we hover to the play button then the cursor arrow should be changed into a hand gesture.

First, we will change our mouse cursor when we hover on the play button.
But before that, we have to create a transparent rectangle which we will use as a play button because the icon is not any button it is within the image.

So, let’s look at the highlighted lines of code.

import random #for generating random numbers
import sys #To Exit the game
import pygame
from pygame.locals import * #Basic Pygame Imports

FPS = 32
SCREENWIDTH = 289
SCREENHEIGHT = 511
SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
GROUNDY = SCREENHEIGHT*0.8
GAME_SPRITES = {}
GAME_SOUNDS = {}
PLAYER = 'resources\SPRITES\\bird.png'
BACKGROUND = 'resources\SPRITES\\bg.jpeg'
PIPE = 'resources\SPRITES\pipe.png '

def welcomeScreen():

    #IT WIll Show Welcome Screen TO user to make the game more interactive and interesting
    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
    
    # Drawing Rectangle for playbutton
    playbutton = pygame.Rect(108,222,68,65)

    while True:
        for event in pygame.event.get():
             #If user clicks on Cross or presses the Escape button Close the Game
            if event.type== QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()

            elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
                return
            
            #This will make the cursor to arrow again if we move out our cursor from playbutton
            pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
            if pygame.mouse.get_pos()[0] > playbutton[0]  and pygame.mouse.get_pos()[0] < playbutton[0] + playbutton[2]:
                if pygame.mouse.get_pos()[1] > playbutton[1]  and pygame.mouse.get_pos()[1] < playbutton[1] + playbutton[3]:
                    pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)

            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)

 ### This is the point from Where Our Game is going to be Started ###
if __name__ == "__main__":

    pygame.init() #Initializing the Modules of Pygame 
    FPSCLOCK = pygame.time.Clock() #for controlling the FPS
    pygame.display.set_caption('Flappy Bird With Sameer') #Setting the Caption of The Game

    #### LOADING THE SPRITES ####

    GAME_SPRITES['numbers'] = (
        pygame.image.load('resources\SPRITES\\0.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\1.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\2.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\3.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\4.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\5.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\6.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\7.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\8.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\9.png').convert_alpha(),
    
    ) 
    
    
    GAME_SPRITES['background'] = pygame.image.load(BACKGROUND).convert_alpha()
    GAME_SPRITES['player'] = pygame.image.load(PLAYER).convert_alpha()
    GAME_SPRITES['message'] = pygame.image.load('resources\SPRITES\message.png').convert_alpha()
    GAME_SPRITES['base'] = pygame.image.load('resources\SPRITES\\base.png').convert_alpha()
    GAME_SPRITES['pipe'] = (
        
        
    pygame.transform.rotate(pygame.image.load(PIPE).convert_alpha(), 180), #### UPPER PIPES, WE JUST ROTATED THE PIPE BY 180deg
    pygame.image.load(PIPE).convert_alpha()   #### LOWER PIPES  
    )

    #Game Sounds
    GAME_SOUNDS['die'] = pygame.mixer.Sound('resources\AUDIO\die.wav')
    GAME_SOUNDS['hit'] = pygame.mixer.Sound('resources\AUDIO\hit.wav')
    GAME_SOUNDS['point'] = pygame.mixer.Sound('resources\AUDIO\point.wav')
    GAME_SOUNDS['swoosh'] = pygame.mixer.Sound('resources\AUDIO\swoosh.wav')
    GAME_SOUNDS['wing'] = pygame.mixer.Sound('resources\AUDIO\wing.wav')
    while True:
        welcomeScreen() #Shows a welcomescreen to the user until they starts the game
        # mainGame() #This is our main game funtion

First, we created a rectangle in a variable call playbutton.

    # Drawing Rectangle for playbutton
    playbutton = pygame.Rect(108,222,68,65)

pygame.Rect() takes 4 things as arguments x, y, length, breadth of the rectangle. Here x, y coordinates are (108,222) and the dimension of the rectangle are (68,65).

HOVER EFFECT

Now, we will write code that if we hover over the play button arrow will change into a hand gesture.

 #This will make the cursor to arrow again if we move out our cursor from playbutton
            pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
            if pygame.mouse.get_pos()[0] > playbutton[0]  and pygame.mouse.get_pos()[0] < playbutton[0] + playbutton[2]:
                if pygame.mouse.get_pos()[1] > playbutton[1]  and pygame.mouse.get_pos()[1] < playbutton[1] + playbutton[3]:
                    pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)

pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW) –> This will set our cursor to the arrow again when we move out our mouse cursor from the play button.

pygame.mouse.get_pos()

This will give the coordinates/position of our mouse cursor. It will return two values one will be our x-coordinate and the second will be our y-coordinate.

After then we checked if our mouse cursor’s x-coordinate is greater than our play button’s x-coordinate and smaller than the play button’s x-coordinate + width of the play button.

After then we checked our mouse cursor’s y-coordinate is greater than our play button’s x-coordinate and smaller than the play button’s y-coordinate + height of the play button.

If both conditions which are discussed above satisfies then change our mouse cursor’s arrow to hand gesture. See below.

Now, we will write code that will check if the user clicks on the play button then start the game for them. Let’s have a look at the code for that.

if playbutton.collidepoint(pygame.mouse.get_pos()): #checking if mouse is collided with the play button
            
                if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: #checking if mouse has been clicked
                    mainGame()

By this, we have successfully created our welcomeScreen() function but if you run this code we will get an error because we haven’t created our mainGame() function. Now our code will look something like this…

import random #for generating random numbers
import sys #To Exit the game
import pygame
from pygame.locals import * #Basic Pygame Imports

FPS = 32
SCREENWIDTH = 289
SCREENHEIGHT = 511
SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
GROUNDY = SCREENHEIGHT*0.8
GAME_SPRITES = {}
GAME_SOUNDS = {}
PLAYER = 'resources\SPRITES\\bird.png'
BACKGROUND = 'resources\SPRITES\\bg.jpeg'
PIPE = 'resources\SPRITES\pipe.png '

def welcomeScreen():

    #IT WIll Show Welcome Screen TO user to make the game more interactive and interesting
    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
    
    # Drawing Rectangle for playbutton
    playbutton = pygame.Rect(108,222,68,65)

    while True:
        for event in pygame.event.get():
             #If user clicks on Cross or presses the Escape button Close the Game
            if event.type== QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()

            elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
                return

            pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
            if pygame.mouse.get_pos()[0] > playbutton[0]  and pygame.mouse.get_pos()[0] < playbutton[0] + playbutton[2]:
                if pygame.mouse.get_pos()[1] > playbutton[1]  and pygame.mouse.get_pos()[1] < playbutton[1] + playbutton[3]:
                    pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)

            if playbutton.collidepoint(pygame.mouse.get_pos()): #checking if mouse is collided with the play button
            
                if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: #checking if mouse has been clicked
                    mainGame()

            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)

 ### This is the point from Where Our Game is going to be Started ###
if __name__ == "__main__":

    pygame.init() #Initializing the Modules of Pygame 
    FPSCLOCK = pygame.time.Clock() #for controlling the FPS
    pygame.display.set_caption('Flappy Bird With Sameer') #Setting the Caption of The Game

    #### LOADING THE SPRITES ####

    GAME_SPRITES['numbers'] = (
        pygame.image.load('resources\SPRITES\\0.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\1.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\2.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\3.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\4.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\5.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\6.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\7.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\8.png').convert_alpha(),
        pygame.image.load('resources\SPRITES\\9.png').convert_alpha(),
    
    ) 
    
    
    GAME_SPRITES['background'] = pygame.image.load(BACKGROUND).convert_alpha()
    GAME_SPRITES['player'] = pygame.image.load(PLAYER).convert_alpha()
    GAME_SPRITES['message'] = pygame.image.load('resources\SPRITES\message.png').convert_alpha()
    GAME_SPRITES['base'] = pygame.image.load('resources\SPRITES\\base.png').convert_alpha()
    GAME_SPRITES['pipe'] = (
        
        
    pygame.transform.rotate(pygame.image.load(PIPE).convert_alpha(), 180), #### UPPER PIPES, WE JUST ROTATED THE PIPE BY 180deg
    pygame.image.load(PIPE).convert_alpha()   #### LOWER PIPES  
    )

    #Game Sounds
    GAME_SOUNDS['die'] = pygame.mixer.Sound('resources\AUDIO\die.wav')
    GAME_SOUNDS['hit'] = pygame.mixer.Sound('resources\AUDIO\hit.wav')
    GAME_SOUNDS['point'] = pygame.mixer.Sound('resources\AUDIO\point.wav')
    GAME_SOUNDS['swoosh'] = pygame.mixer.Sound('resources\AUDIO\swoosh.wav')
    GAME_SOUNDS['wing'] = pygame.mixer.Sound('resources\AUDIO\wing.wav')
    while True:
        welcomeScreen() #Shows a welcomescreen to the user until they starts the game
        mainGame() #This is our main game funtion

CREATING OUR MAIN GAME FUNCTION

So far we have done a lot of things we have successfully created our welcome screen. But now we are going to create our main game function so that now we can also play the Flappy Bird In Pygame Python.

But before starting let me give you a summarized idea of what we are going to do in this particular functions. We’ll work on a bunch of things because it’s the main function by which we would be able to play the game because we can play the game even without a welcome screen but it adds beauty to the game and gives a sense of professionalism.

So let’s make a table of what we are going to do in this maingame() function.

  • We would blit all the sprites
  • After then we’ll make our player which is bird movable and will give a realistic feel.
  • Then our next task is to generate random pipes which would be our obstacles for the game
  • After doing that we would make the pipes movable.
  • We would make functions for collisions
  • After collisions we will make the game over and will give them the option whether they want to play again or return to the home screen. It would be in our gameover functions not in this we will just call it after the collision.
  • We would have some sound effects and some background music.

Now we are going to create our main game so let’s start.

def mainGame():
    score = 0
    playerx = int(SCREENWIDTH/5)
    playery = int (SCREENHEIGHT/2)
    basex = 0
Share:

Author: Ayush Purawr

Related Articles