make a flappy bird game in python

To make a Flappy Bird game in Python, you can use the Pygame library. Here are the general steps:

  1. Set up the game window and background.
main.py
import pygame
pygame.init()

WINDOW_WIDTH = 500
WINDOW_HEIGHT = 600
FPS = 60

screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
clock = pygame.time.Clock()

background = pygame.image.load("background.png")
background = pygame.transform.scale(background, (WINDOW_WIDTH, WINDOW_HEIGHT))
299 chars
13 lines
  1. Create the bird character and its movement.
main.py
bird = pygame.image.load("bird.png")
bird_rect = bird.get_rect(center=(WINDOW_WIDTH/2, WINDOW_HEIGHT/2))

bird_movement = 0
gravity = 0.25
139 chars
6 lines
  1. Set up the pipes and their movement.
main.py
pipe = pygame.image.load("pipe.png")
pipe_list = []
pipe_spawn_time = pygame.USEREVENT
pygame.time.set_timer(pipe_spawn_time, 1200)

class Pipe:
    def __init__(self, height):
        self.top_pipe = pygame.transform.flip(pipe, False, True)
        self.bottom_pipe = pipe
        self.top_pipe_rect = self.top_pipe.get_rect(midbottom=(WINDOW_WIDTH, height - 150))
        self.bottom_pipe_rect = self.bottom_pipe.get_rect(midtop=(WINDOW_WIDTH, height))
    
    def move(self):
        self.top_pipe_rect.x -= 5
        self.bottom_pipe_rect.x -= 5
    
    def draw(self):
        screen.blit(self.top_pipe, self.top_pipe_rect)
        screen.blit(self.bottom_pipe, self.bottom_pipe_rect)

def create_pipe():
    height = random.randint(200, 450)
    pipe = Pipe(height)
    pipe_list.append(pipe)
801 chars
25 lines
  1. Handle user input and collisions.
main.py
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                bird_movement = 0
                bird_movement -= 6
        
        if event.type == pipe_spawn_time:
            create_pipe()
    
    # Move the bird
    bird_movement += gravity
    bird_rect.centery += bird_movement
    
    # Move the pipes and delete them when they go off-screen
    for pipe in pipe_list:
        pipe.move()
        if pipe.top_pipe_rect.right < 0:
            pipe_list.remove(pipe)
    
    # Check for collisions
    for pipe in pipe_list:
        if bird_rect.colliderect(pipe.top_pipe_rect) or bird_rect.colliderect(pipe.bottom_pipe_rect):
            game_over = True
    
    # Draw the background, pipes, and bird
    screen.blit(background, (0, 0))
    for pipe in pipe_list:
        pipe.draw()
    screen.blit(bird, bird_rect)
    
    pygame.display.update()
    clock.tick(FPS)
1065 chars
38 lines

Of course, this is just a basic skeleton of a Flappy Bird game, and you can add more features (like scorekeeping, sound effects, or animations) to make it more engaging.

gistlibby LogSnag