Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Flappy Bird Game using PyGame in Python



In the Flappy Bird game, players control a bird by tapping the screen to make it fly between pipes without hitting them. Here, we will design a flappy bird game using pygame library.

Steps to Design Flappy Bird Game using pygame

1. Install pygame Library

To installpygame library, use thePIP command. Here is the command to instant it −

pip install pygame

2. Import Libraries

You need to importpygame andrandom libraries using the import statement. The below are the code statements to import these libraries −

import pygameimport random

3. Initialize Pygame

To initialize thepygame, simply call the pygame.init() method after importing the libraries.

pygame.init()

4. Set Up Screen

Describe screen resolution and establish a window to a game throughpygame.display.set_mode() method.

5. Define Colors and Properties

You have to set colors and define properties for the bird and pipes.

6. Create Drawing Functions

Create functions that will be layouts for the bird and the pipes on the screen.

7. Implement Collision Detection

Now, incorporate a function to determine whether the bird collides with the pipes or the borders of the screen.

8. Manage Pipes

Develop a function that will allow for the changes and add new pipes that may be required.

9. Run Game Loop

Receive inputs from the user, manage game status, identify coincidences, and redraw interface.

10. End Game

Quit the game window when a collision is detected with the aid of `pygame. quit()`.

Python Code for Flappy Bird Game using PyGame

import pygameimport random# Initialize Pygamepygame.init()# Screen dimensionsSCREEN_WIDTH = 400SCREEN_HEIGHT = 600screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))pygame.display.set_caption("Flappy Bird")# ColorsWHITE = (255, 255, 255)BLACK = (0, 0, 0)GREEN = (0, 255, 0)# Bird propertiesBIRD_WIDTH = 40BIRD_HEIGHT = 30bird_x = 50bird_y = SCREEN_HEIGHT // 2bird_velocity = 0gravity = 0.5  # Gravityflap_strength = -7  # Moderate flap strength# Pipe propertiesPIPE_WIDTH = 70PIPE_HEIGHT = 500PIPE_GAP = 200  # Pipe gappipe_velocity = -2  # Pipe velocitypipes = []# Game variablesscore = 0clock = pygame.time.Clock()flap_cooldown = 0  # Time before the bird can flap againdef draw_bird():   pygame.draw.rect(screen, BLACK, (bird_x, bird_y, BIRD_WIDTH, BIRD_HEIGHT))def draw_pipes():   for pipe in pipes:      pygame.draw.rect(screen, GREEN, pipe['top'])      pygame.draw.rect(screen, GREEN, pipe['bottom'])def check_collision():   global score   bird_rect = pygame.Rect(bird_x, bird_y, BIRD_WIDTH, BIRD_HEIGHT)   for pipe in pipes:      if bird_rect.colliderect(pipe['top']) or bird_rect.colliderect(pipe['bottom']):         return True   if bird_y > SCREEN_HEIGHT or bird_y < 0:      return True   return Falsedef update_pipes():   global score   for pipe in pipes:      pipe['top'].x += pipe_velocity      pipe['bottom'].x += pipe_velocity      if pipe['top'].x + PIPE_WIDTH < 0:         pipes.remove(pipe)         score += 1   if len(pipes) == 0 or pipes[-1]['top'].x < SCREEN_WIDTH - 300:      pipe_height = random.randint(100, SCREEN_HEIGHT - PIPE_GAP - 100)      pipes.append({         'top': pygame.Rect(SCREEN_WIDTH, 0, PIPE_WIDTH, pipe_height),         'bottom': pygame.Rect(SCREEN_WIDTH, pipe_height + PIPE_GAP, PIPE_WIDTH, SCREEN_HEIGHT - pipe_height - PIPE_GAP)      })# Game looprunning = Truewhile running:   for event in pygame.event.get():      if event.type == pygame.QUIT:         running = False      if event.type == pygame.KEYDOWN:         if event.key == pygame.K_SPACE and flap_cooldown <= 0:            bird_velocity = flap_strength            flap_cooldown = 10  # Set cooldown to prevent rapid flapping      if event.type == pygame.MOUSEBUTTONDOWN and flap_cooldown <= 0:         bird_velocity = flap_strength         flap_cooldown = 10  # Set cooldown to prevent rapid flapping       # Update bird position   bird_velocity += gravity   bird_y += bird_velocity   # Update pipes   update_pipes()   # Check for collision   if check_collision():      running = False   # Manage flap cooldown   if flap_cooldown > 0:      flap_cooldown -= 1   # Draw everything   screen.fill(WHITE)   draw_bird()   draw_pipes()   # Display the score   font = pygame.font.SysFont(None, 36)   score_text = font.render(f'Score: {score}', True, BLACK)   screen.blit(score_text, (10, 10))   pygame.display.flip()   clock.tick(30)pygame.quit()

Output

Flappy BirdFlappy Bird

Click the Right click mouse button, you will score and played the game properly.

Flappy Bird Game Summary

When the game is run, a window opens with the title bar "Flappy Bird" and the bird, as well as the pipes are displayed. The bird becomes subjected to gravitational force and in order to make the bird flap, the player has to use the space bar key or the mouse. Tubes appear from the right side of the screen and shift to the left and the bird has to be controlled to avoid coming into contact with the tubes. The score is positioned on the top left of the pixel game and increase with the movement of the bird through pipes.

Conclusion

This Flappy Bird implementation in pygame is a simple yet very serviceable example of some of the concepts involved with game development. If the given code is analyzed and implemented into a game then the skills which developers can learn include sprite movement, collision detection and game state management. Possibilities of addition of such features as sound effects, different levels of complexities and improved graphics can also be incorporated to make the game more interesting.

python_projects_from_basic_to_advanced.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp