0% found this document useful (0 votes)
95 views14 pages

Project File (Flappy Bird)

This document provides instructions for building a side-scrolling bird game using Python and Pygame. It discusses the prerequisites of basic Python knowledge and using Pygame for graphics and sound. The game objective is to fly a bird between rows of green pipes without touching them, earning a point for each successful pass. The bird falls due to gravity and can briefly fly up when the player taps a key.

Uploaded by

Cadever Y.T
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views14 pages

Project File (Flappy Bird)

This document provides instructions for building a side-scrolling bird game using Python and Pygame. It discusses the prerequisites of basic Python knowledge and using Pygame for graphics and sound. The game objective is to fly a bird between rows of green pipes without touching them, earning a point for each successful pass. The bird falls due to gravity and can briefly fly up when the player taps a key.

Uploaded by

Cadever Y.T
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Prerequisite

The prerequisite of this project is the basic knowledge of


python.
For this project, we are going to use the Virtual Studio Code
IDE and the pygame module. Pygame is a library that is used
in creating games in Python. It has four important things.
 Game Loop
 Events
 Sprites
 Sound
INTRODUCTION

Game is a side scroller where the player controls a bird


attempting to fly between rows of green pipes which are
equally sized gaps placed at random heights, without coming
into contact. Each successful pass through a pair of pipes
awards a player one point. If the player touches the pipes, it
ends the game. The bird briefly flaps upward each time the
player taps the key. If the key is not taped, the bird falls due to
gravity.

Compatibility: Any system with python


installed can compile, execute and play this game.
WORKING DESCRIPTION

For the successful execution of any game, the logic has to be


concrete and in accordance with the fundamentals of the game.

We have 50 pixels, white


pillars, which move from
right to left. And every next
pillar has a different random
height. In order to make
them moving logically, after
each iteration, we need to
clear the screen and redraw
the graphic with the pillars at
their new position. However,
we cannot do that because
of the low refresh rate of the
screen. Which would
causeway flickering of the
graphics in order to activate
all its pixels. The screen
needs a bit more time.

The graphics we follow in the standard


system, where the screen moves in X
direction and the user will have to
trigger the up, down movement by the
press of the key.
The bird’s Y position moves down by a certain speed each
frame. Each frame the speed is increased to simulate gravity.
When a key is pressed, the bird’s speed is set to a high number
in the upward direction. The pipes share the same width, and
the same space height between the segments. Each pipe has
its own X position and Y position the in space.
Since there are only two pipes in the playing area. At one time,
the information for only two pipes need to stored. Once a pipe
goes out of the playing area, it gets a new space positioned
and its X position is set to the right edge of the playing area.
The bird has collided with the top segment if……
 The left edge of the bird is to the left of the right edge of
the pipe.
 The right edge of the bird is the right of the left chopped
up.
 The top edge of the bird is above the bottom edge of the
pipe segment.
BIRD and GRAVITY:

The birds by position are made into


a variable, and every frame
increases by 30 multiplied by DT,
making the bird move down 30
pixels per second. Instead of
moving at a constant speed, the
number added to the bird’s wipe
position also increases overtime. The word speed is made into
a variable which starts at zero, and every frame it increases by
a fixed scalar. Gravity times the frame height.
PIPES:
By the most important part of the game, because they have to
be made sensitive to collision with the bird. Their appearance
in the game is totally randomized, thereby making a
exceedingly difficult for the player to cope as the game
proceeds.
Two rectangles are drawn from the upper and
lower segments.
The top rectangle height is set to where the
space between the two segments starts, the
bottom rectangle starts at the Y position of the
top rectangle height, plus the amount of space
between them.
The bottom rectangles height is the playing
areas height. The height of the top rectangle and
the space.
The pipe width is the same for both segments.
So, this is made into a variable.

Display Screen:
As the player keeps on crossing the
hurdles, his score gets incremented
by one.
The background is a PNG file that is
attached, and it keeps on re looping
as the bird progresses throughout the
game. Varies other packets are there
in the game that give a complete look of the dynamism of the
key.
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 = 'gallery/sprites/bird.png'
BACKGROUND = 'gallery/sprites/background.png'
PIPE = 'gallery/sprites/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']) <
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
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 )
for blitting on the screen
    """
    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 CodeWithHarry')
    GAME_SPRITES['numbers'] = (
        pygame.image.load('gallery/sprites/0.png').convert_alpha(),
        pygame.image.load('gallery/sprites/1.png').convert_alpha(),
        pygame.image.load('gallery/sprites/2.png').convert_alpha(),
        pygame.image.load('gallery/sprites/3.png').convert_alpha(),
        pygame.image.load('gallery/sprites/4.png').convert_alpha(),
        pygame.image.load('gallery/sprites/5.png').convert_alpha(),
        pygame.image.load('gallery/sprites/6.png').convert_alpha(),
        pygame.image.load('gallery/sprites/7.png').convert_alpha(),
        pygame.image.load('gallery/sprites/8.png').convert_alpha(),
        pygame.image.load('gallery/sprites/9.png').convert_alpha(),
    )

    GAME_SPRITES['message']
=pygame.image.load('gallery/sprites/message.png').convert_alpha()
    GAME_SPRITES['base']
=pygame.image.load('gallery/sprites/base.png').convert_alpha()
    GAME_SPRITES['pipe']
=(pygame.transform.rotate(pygame.image.load( PIPE).convert_alpha(), 180),
    pygame.image.load(PIPE).convert_alpha()
    )

    # Game sounds
    GAME_SOUNDS['die'] = pygame.mixer.Sound('gallery/audio/die.wav')
    GAME_SOUNDS['hit'] = pygame.mixer.Sound('gallery/audio/hit.wav')
    GAME_SOUNDS['point'] = pygame.mixer.Sound('gallery/audio/point.wav')
    GAME_SOUNDS['swoosh'] = pygame.mixer.Sound('gallery/audio/swoosh.wav')
    GAME_SOUNDS['wing'] = pygame.mixer.Sound('gallery/audio/wing.wav')

    GAME_SPRITES['background'] = pygame.image.load(BACKGROUND).convert()
    GAME_SPRITES['player'] = pygame.image.load(PLAYER).convert_alpha()

    while True:
        welcomeScreen() # Shows welcome screen to the user until he presses a
button
        mainGame() # This is the main game function
OUTPUT SCREENS
BIBLIOGRAPHY

 https://copyassignment.com/flappy-bird-in-python-
pygame/
 https://www.slideshare.net/
 https://www.youtube.com/watch?v=itB6VsP5UnA
 https://youtu.be/oNq9QKX3lMs

You might also like