Make a flappybird clone
- User
Make a flappybird clone
- Assistant
Make a flappybird clone
Certainly! Below is a step-by-step guide to creating a Flappy Bird clone using Python and the Pygame library. This clone will mimic the basic mechanics of the original game, where the player controls a bird, navigating it through gaps between moving pipes.
Goal: Create a functional Flappy Bird clone with basic graphics and gameplay.
Tools:
Python Installation: Ensure you have Python 3.x installed. You can download it from python.org.
Pygame Installation: Install Pygame by running the following command in your terminal or command prompt:
pip install pygame
For some systems, you might need to use pip3 instead of pip.
We'll start by importing the necessary libraries.
import pygame
import sys
import random
Initialize Pygame and create the main game window.
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Flappy Bird Clone')
Set up constants and variables that control the game's mechanics.
# Game variables
GRAVITY = 0.5
BIRD_FLAP_POWER = -10
PIPE_SPEED = -3
PIPE_GAP = 150 # Gap between upper and lower pipes
PIPE_FREQUENCY = 1500 # Milliseconds between pipe generations
# Load images (simple colored surfaces for this clone)
BIRD_WIDTH = 34
BIRD_HEIGHT = 24
BIRD_IMG = pygame.Surface((BIRD_WIDTH, BIRD_HEIGHT))
BIRD_IMG.fill((255, 255, 0)) # Yellow bird
PIPE_WIDTH = 52
PIPE_HEIGHT = 320
PIPE_IMG = pygame.Surface((PIPE_WIDTH, PIPE_HEIGHT))
PIPE_IMG.fill((0, 255, 0)) # Green pipes
BACKGROUND_IMG = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
BACKGROUND_IMG.fill((135, 206, 250)) # Sky blue background
Manage the game's timing and events.
# Clock and timer
clock = pygame.time.Clock()
SPAWNPIPE = pygame.USEREVENT
pygame.time.set_timer(SPAWNPIPE, PIPE_FREQUENCY)
Define the bird's properties and behaviors.
# Bird class
class Bird:
def __init__(self):
self.x = 50 # Starting X position
self.y = SCREEN_HEIGHT // 2 # Starting Y position
self.vel_y = 0 # Initial vertical velocity
self.img = BIRD_IMG
self.rect = self.img.get_rect(center=(self.x, self.y))
def flap(self):
self.vel_y = BIRD_FLAP_POWER # Move up when flapping
def update(self):
self.vel_y += GRAVITY # Apply gravity
self.y += self.vel_y # Update position
self.rect.center = (self.x, self.y) # Update rectangle position
def draw(self, screen):
screen.blit(self.img, self.rect)
Define the pipes' properties and behaviors.
# Pipe class
class Pipe:
def __init__(self):
self.x = SCREEN_WIDTH # Start at the right edge of the screen
# Random height for the top pipe
self.height = random.randint(50, SCREEN_HEIGHT - PIPE_GAP - 50)
self.top_rect = PIPE_IMG.get_rect(midbottom=(self.x, self.height))
self.bottom_rect = PIPE_IMG.get_rect(midtop=(self.x, self.height + PIPE_GAP))
self.passed = False # For score tracking
def update(self):
self.x += PIPE_SPEED # Move left
# Update pipe positions
self.top_rect.midbottom = (self.x, self.height)
self.bottom_rect.midtop = (self.x, self.height + PIPE_GAP)
def draw(self, screen):
screen.blit(PIPE_IMG, self.top_rect) # Draw top pipe
screen.blit(PIPE_IMG, self.bottom_rect) # Draw bottom pipe
Check for collisions between the bird and pipes or screen boundaries.
# Function to check collision
def check_collision(bird, pipes):
for pipe in pipes:
if bird.rect.colliderect(pipe.top_rect) or bird.rect.colliderect(pipe.bottom_rect):
return True # Collision detected
if bird.rect.top <= 0 or bird.rect.bottom >= SCREEN_HEIGHT:
return True # Bird has hit the top or bottom of the screen
return False # No collision
Encapsulate the main game loop and logic.
def main():
bird = Bird()
pipes = []
score = 0
font = pygame.font.Font(None, 36)
running = True
while running:
clock.tick(60) # Limit the frame rate to 60 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False # Exit the game loop
pygame.quit()
sys.exit()
if event.type == SPAWNPIPE:
pipes.append(Pipe()) # Add a new pipe
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird.flap() # Make the bird flap
# Update bird
bird.update()
# Update pipes
for pipe in pipes:
pipe.update()
# Remove pipes that have gone off-screen
pipes = [pipe for pipe in pipes if pipe.x + PIPE_WIDTH > 0]
# Check for collisions
if check_collision(bird, pipes):
running = False # End the game loop
# Update score
for pipe in pipes:
if pipe.x + PIPE_WIDTH < bird.x and not pipe.passed:
score += 1
pipe.passed = True
# Draw background
SCREEN.blit(BACKGROUND_IMG, (0, 0))
# Draw pipes
for pipe in pipes:
pipe.draw(SCREEN)
# Draw bird
bird.draw(SCREEN)
# Draw score
score_surface = font.render(f'Score: {score}', True, (255, 255, 255))
SCREEN.blit(score_surface, (10, 10))
# Update the display
pygame.display.update()
# Game over display
game_over_font = pygame.font.Font(None, 64)
game_over_surface = game_over_font.render('Game Over', True, (255, 0, 0))
SCREEN.blit(game_over_surface, (
SCREEN_WIDTH//2 - game_over_surface.get_width()//2,
SCREEN_HEIGHT//2 - game_over_surface.get_height()//2))
pygame.display.update()
pygame.time.wait(2000) # Pause for 2 seconds before exiting
Ensure the game runs when the script is executed.
if __name__ == '__main__':
main()
Here's the complete code for reference:
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Flappy Bird Clone')
# Game variables
GRAVITY = 0.5
BIRD_FLAP_POWER = -10
PIPE_SPEED = -3
PIPE_GAP = 150
PIPE_FREQUENCY = 1500 # milliseconds
# Load images
BIRD_WIDTH = 34
BIRD_HEIGHT = 24
BIRD_IMG = pygame.Surface((BIRD_WIDTH, BIRD_HEIGHT))
BIRD_IMG.fill((255, 255, 0))
PIPE_WIDTH = 52
PIPE_HEIGHT = 320
PIPE_IMG = pygame.Surface((PIPE_WIDTH, PIPE_HEIGHT))
PIPE_IMG.fill((0, 255, 0))
BACKGROUND_IMG = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
BACKGROUND_IMG.fill((135, 206, 250))
# Clock and timer
clock = pygame.time.Clock()
SPAWNPIPE = pygame.USEREVENT
pygame.time.set_timer(SPAWNPIPE, PIPE_FREQUENCY)
# Bird class
class Bird:
def __init__(self):
self.x = 50
self.y = SCREEN_HEIGHT // 2
self.vel_y = 0
self.img = BIRD_IMG
self.rect = self.img.get_rect(center=(self.x, self.y))
def flap(self):
self.vel_y = BIRD_FLAP_POWER
def update(self):
self.vel_y += GRAVITY
self.y += self.vel_y
self.rect.center = (self.x, self.y)
def draw(self, screen):
screen.blit(self.img, self.rect)
# Pipe class
class Pipe:
def __init__(self):
self.x = SCREEN_WIDTH
self.height = random.randint(50, SCREEN_HEIGHT - PIPE_GAP - 50)
self.top_rect = PIPE_IMG.get_rect(midbottom=(self.x, self.height))
self.bottom_rect = PIPE_IMG.get_rect(midtop=(self.x, self.height + PIPE_GAP))
self.passed = False
def update(self):
self.x += PIPE_SPEED
self.top_rect.midbottom = (self.x, self.height)
self.bottom_rect.midtop = (self.x, self.height + PIPE_GAP)
def draw(self, screen):
screen.blit(PIPE_IMG, self.top_rect)
screen.blit(PIPE_IMG, self.bottom_rect)
# Function to check collision
def check_collision(bird, pipes):
for pipe in pipes:
if bird.rect.colliderect(pipe.top_rect) or bird.rect.colliderect(pipe.bottom_rect):
return True
if bird.rect.top <= 0 or bird.rect.bottom >= SCREEN_HEIGHT:
return True
return False
def main():
bird = Bird()
pipes = []
score = 0
font = pygame.font.Font(None, 36)
running = True
while running:
clock.tick(60) # FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit()
if event.type == SPAWNPIPE:
pipes.append(Pipe())
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird.flap()
# Update bird
bird.update()
# Update pipes
for pipe in pipes:
pipe.update()
# Remove off-screen pipes
pipes = [pipe for pipe in pipes if pipe.x + PIPE_WIDTH > 0]
# Check collision
if check_collision(bird, pipes):
running = False
# Increase score
for pipe in pipes:
if pipe.x + PIPE_WIDTH < bird.x and not pipe.passed:
score += 1
pipe.passed = True
# Draw background
SCREEN.blit(BACKGROUND_IMG, (0, 0))
# Draw pipes
for pipe in pipes:
pipe.draw(SCREEN)
# Draw bird
bird.draw(SCREEN)
# Draw score
score_surface = font.render(f'Score: {score}', True, (255, 255, 255))
SCREEN.blit(score_surface, (10, 10))
pygame.display.update()
# Game Over
game_over_font = pygame.font.Font(None, 64)
game_over_surface = game_over_font.render('Game Over', True, (255, 0, 0))
SCREEN.blit(game_over_surface, (
SCREEN_WIDTH//2 - game_over_surface.get_width()//2,
SCREEN_HEIGHT//2 - game_over_surface.get_height()//2))
pygame.display.update()
pygame.time.wait(2000)
if __name__ == '__main__':
main()
Save the Code: Copy the entire code above into a new file and save it as flappy_bird_clone.py.
Run the Game:
Open a terminal or command prompt.
Navigate to the directory containing flappy_bird_clone.py.
Run the following command:
python flappy_bird_clone.py
If you have multiple versions of Python installed, you might need to specify python3 instead of python.
Controls:
Now that you have a basic Flappy Bird clone, consider enhancing it:
This project provides a foundation for understanding game development concepts such as event handling, game loops, collision detection, and rendering graphics with Pygame. Experiment with the code to learn more and create your own unique version of the game.
Enjoy your new Flappy Bird clone! If you have any questions or need further assistance, feel free to ask.