Flappy bird код python

Create Flappy Bird Game using Python- Project

Flappy Bird using Python

You could have obviously played or at least heard of the most famous of its time “The Flappy Bird Game”. Those were the days of your childhood, but you are a grown-up techie now. So, not only we can play but we can also create it. In this article, I have shared the Source Code of Flappy Bird Game using Python along with its complete installation guide.

Required Modules

Before sharing the code make sure you have installed the required modules.

random: For generating random numbers
sys: We will use sys to exit the program
pygame: To build 2D games in Python

Library Installation

Before getting started with code we need to install the necessary required module or library. By default random and sys come preinstalled in python. we need to install pygame. For that, you need to write the following command in your terminal or command prompt.

Читайте также:  Javascript функции графики которых

Resources and Source code

Now you need to download the resources, like image assets and audio for the game. Click Here To Download. Once the zip file has been downloaded make sure you extract it. This zip file contains images, audio and a .py file where the Flappy Bird game is written.

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 = [ , , ] # my List of lower pipes lowerPipes = [ , , ] 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") GAME_SOUNDS['point'].play() if playerVelY GROUNDY - 25 or playery 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 = [ , #upper Pipe #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 Codehub') 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 

Hope that you liked this Flappy Bird Game using Python for sure. You should include this amazing game in your python projects list. Do share your thoughts in the comment section below.

Читайте также:  Javascript кавычки внутри кавычек

Post You May Also Like:

Источник

Flappy Bird Game in Python with Source Code

Flappy Bird Game in Python with Source Code

A Flappy Bird Game in Python is free to download the open source code and it is created for the beginners who wants to learn python.

The project system used a Pygame and Random module. Pygame is a cross-platform set of Python modules designed for writing video games.

Flappy Bird Code in Python – Project Information’s

This Flappy Bird Code has a task record that contains an images file, sounds file and python contents file (flappy.py). The ongoing interaction Graphics is sufficient and the controls are straightforward for the clients.

Discussing the ongoing interaction, it’s one of the most addictive and messed around for all. All the playing strategies are too straightforward simply like the genuine one.

You should simply attempt to remain in the screen until long green channels show up before you. Here, the client needs to control the winged animal fluttering up, down utilizing Spacebar, without contacting pipes so as to score game focuses. See the video below.

This implies the more you go through green funnels, the more will be the game focuses. A straightforward GUI has accommodated the simple ongoing interaction.

The ongoing interaction configuration is easy to such an extent that the client won’t think that it’s hard to utilize and explore.

Before you start on how to create Flappy Bird Game in Python, make sure that you have PyCharm IDE and Pygame installed on your computer.

Steps on How To Create Flappy Bird in Python.

    Step 1: Create a project name.

Creating a project name in Floppy Birds Game in Python

First, when you finished installing the Pycharm IDE in your computer, open it and then create a “project name” after creating a project name click the “create” button.

Creating a python file name in Flappy Bird Game in Python

Second after creating a project name, “right click” your project name and then click “new” after that click the “python file“.
Step 3: Name your python file.

Naming a python file name in Flappy Bird Game in Python

Third after creating a python file, Name your python file after that click “enter
Step 4: The actual code.

This is the actual coding on how to create Flappy Bird Game in Python, and you are free to copy this code and download the full source code given below.

Code Explanations

1. Importing Random Module

Explanation:

In the code given below. which is for the random() function, which generates random numbers between 0 and 1.

2. Importing Pygame Module

import pygame from pygame.locals import *

Explanation:

In the code given below, which is pygame library is an open-source module for the Python programming language specifically intended to help you make games and other multimedia applications. Pygame can run across many platforms and operating systems.

3. Importing Sys Module

Explanation:

In the code given below, which is for the function of sys module. We will use sys.exit to exit the program.

4. This module is for the global variables

FPS = 32 scr_width = 289 scr_height = 511 display_screen_window = pygame.display.set_mode((scr_width, scr_height)) play_ground = scr_height * 0.8 game_image = <> game_audio_sound = <> player = 'images/bird.png' bcg_image = 'images/background.png' pipe_image = 'images/pipe.png'

Explanation:

In the code given below, which is for the global variables for the game.

5. This module is for the welcome main screen

def welcome_main_screen(): """ Shows welcome images on the screen """ p_x = int(scr_width / 5) p_y = int((scr_height - game_image['player'].get_height()) / 2) msgx = int((scr_width - game_image['message'].get_width()) / 2) msgy = int(scr_height * 0.13) b_x = 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: display_screen_window.blit(game_image['background'], (0, 0)) display_screen_window.blit(game_image['player'], (p_x, p_y)) display_screen_window.blit(game_image['message'], (msgx, msgy)) display_screen_window.blit(game_image['base'], (b_x, play_ground)) pygame.display.update() time_clock.tick(FPS)

Explanation:

In the code given below, which is for the function of welcome main screen. It shows welcome images on the screen.

6. This module is for the main gameplay

def main_gameplay(): score = 0 p_x = int(scr_width / 5) p_y = int(scr_width / 2) b_x = 0 n_pip1 = get_Random_Pipes() n_pip2 = get_Random_Pipes() up_pips = [ , , ] low_pips = [ , , ] pip_Vx = -4 p_vx = -9 p_mvx = 10 p_mvy = -8 p_accuracy = 1 p_flap_accuracy = -8 p_flap = False 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 p_y > 0: p_vx = p_flap_accuracy p_flap = True game_audio_sound['wing'].play() cr_tst = is_Colliding(p_x, p_y, up_pips, low_pips) if cr_tst: return p_middle_positions = p_x + game_image['player'].get_width() / 2 for pipe in up_pips: pip_middle_positions = pipe['x'] + game_image['pipe'][0].get_width() / 2 if pip_middle_positions ") game_audio_sound['point'].play() if p_vx < p_mvx and not p_flap: p_vx += p_accuracy if p_flap: p_flap = False p_height = game_image['player'].get_height() p_y = p_y + min(p_vx, play_ground - p_y - p_height) for pip_upper, pip_lower in zip(up_pips, low_pips): pip_upper['x'] += pip_Vx pip_lower['x'] += pip_Vx if 0 < up_pips[0]['x'] < 5: new_pip = get_Random_Pipes() up_pips.append(new_pip[0]) low_pips.append(new_pip[1]) if up_pips[0]['x'] < -game_image['pipe'][0].get_width(): up_pips.pop(0) low_pips.pop(0) display_screen_window.blit(game_image['background'], (0, 0)) for pip_upper, pip_lower in zip(up_pips, low_pips): display_screen_window.blit(game_image['pipe'][0], (pip_upper['x'], pip_upper['y'])) display_screen_window.blit(game_image['pipe'][1], (pip_lower['x'], pip_lower['y'])) display_screen_window.blit(game_image['base'], (b_x, play_ground)) display_screen_window.blit(game_image['player'], (p_x, p_y)) d = [int(x) for x in list(str(score))] w = 0 for digit in d: w += game_image['numbers'][digit].get_width() Xoffset = (scr_width - w) / 2 for digit in d: display_screen_window.blit(game_image['numbers'][digit], (Xoffset, scr_height * 0.12)) Xoffset += game_image['numbers'][digit].get_width() pygame.display.update() time_clock.tick(FPS)

Explanation:

In the code given below, which is for the function of main gameplay of a game. Create 2 pipes for blitting on the screen. Includes the list of upper and lower pipes. Checking for score function, Add a new pipe when the first is about to cross the leftmost part of the screen.

7. This module is for the get random pipes

def get_Random_Pipes(): pip_h = game_image['pipe'][0].get_height() off_s = scr_height / 3 yes2 = off_s + random.randrange(0, int(scr_height - game_image['base'].get_height() - 1.2 * off_s)) pipeX = scr_width + 10 y1 = pip_h - yes2 + off_s pipe = [ , # upper Pipe # lower Pipe ] return pipe

Explanation:

In the code given below, which is for the function of get random pipes. Generate positions of two pipes(one bottom straight and one top rotated ) for blitting on the screen.

8. This module is for images

if __name__ == "__main__": pygame.init() time_clock = pygame.time.Clock() pygame.display.set_caption('Flappy Bird Game') game_image['numbers'] = ( pygame.image.load('images/0.png').convert_alpha(), pygame.image.load('images/1.png').convert_alpha(), pygame.image.load('images/2.png').convert_alpha(), pygame.image.load('images/3.png').convert_alpha(), pygame.image.load('images/4.png').convert_alpha(), pygame.image.load('images/5.png').convert_alpha(), pygame.image.load('images/6.png').convert_alpha(), pygame.image.load('images/7.png').convert_alpha(), pygame.image.load('images/8.png').convert_alpha(), pygame.image.load('images/9.png').convert_alpha(), ) game_image['message'] = pygame.image.load('images/message.png').convert_alpha() game_image['base'] = pygame.image.load('images/base.png').convert_alpha() game_image['pipe'] = (pygame.transform.rotate(pygame.image.load(pipe_image).convert_alpha(), 180), pygame.image.load(pipe_image).convert_alpha() )

Explanation:

In the code given below, which is for the function of images use in a game.

9. This module is for the sound

game_audio_sound['die'] = pygame.mixer.Sound('sounds/die.wav') game_audio_sound['hit'] = pygame.mixer.Sound('sounds/hit.wav') game_audio_sound['point'] = pygame.mixer.Sound('sounds/point.wav') game_audio_sound['swoosh'] = pygame.mixer.Sound('sounds/swoosh.wav') game_audio_sound['wing'] = pygame.mixer.Sound('sounds/wing.wav')

Explanation:

In the code given below, which is for the function of sound/audio use in a game.

Downloadable Source Code

I have here the list of Best Python Project with Source code free to download for free, I hope this can help you a lot.

Summary

That’s how you create Flappy Bird Game in Python in your projects. You can always expand and try different ways in implementing the Flappy Bird Code in your Python projects. Flappy Bird Python is free to download the open source code and it is use for educational purposes only.

Inquiries

If you have any questions or suggestions about Flappy Bird Game in Python with Source Code , please feel free to leave a comment below.

Источник

Оцените статью