i wanna make flappy bird game in python
- User
i wanna make flappy bird game in python
- Assistant
i wanna make flappy bird game in python
Creating a Flappy Bird clone in Python is a fun way to learn programming and game development. Below is a step-by-step guide using the Pygame library, which is widely used for building games in Python. We'll cover setting up the environment, creating game elements, handling user input, implementing game mechanics, and running the game loop.
First, ensure you have Python installed on your computer. Then, install Pygame using pip:
pip install pygame
Create a new Python file, e.g., flappy_bird.py, and start by importing necessary modules and initializing Pygame.
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Game Constants
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
FPS = 60
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Set up the display
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Clock to control the frame rate
clock = pygame.time.Clock()
Define a Bird class to manage the bird's properties and behaviors.
class Bird:
def __init__(self):
self.image = pygame.Surface((34, 24)) # Placeholder for the bird
self.image.fill((255, 255, 0)) # Yellow bird
self.rect = self.image.get_rect()
self.rect.center = (100, SCREEN_HEIGHT // 2)
self.velocity = 0
self.gravity = 0.5
self.flap_strength = -10
def flap(self):
self.velocity = self.flap_strength
def update(self):
self.velocity += self.gravity
self.rect.y += self.velocity
def draw(self, surface):
surface.blit(self.image, self.rect)
Instead of using a plain surface, you can load an image for the bird using pygame.image.load() for better visuals.
Define a Pipe class to handle the obstacles.
class Pipe:
GAP = 150
VELOCITY = 3
def __init__(self, x):
self.width = 80
self.color = (0, 255, 0) # Green pipes
self.x = x
self.height = random.randint(50, SCREEN_HEIGHT - self.GAP - 50)
self.top_rect = pygame.Rect(self.x, 0, self.width, self.height)
self.bottom_rect = pygame.Rect(
self.x, self.height + self.GAP, self.width, SCREEN_HEIGHT - self.height - self.GAP
)
def update(self):
self.x -= self.VELOCITY
self.top_rect.x = self.x
self.bottom_rect.x = self.x
def draw(self, surface):
pygame.draw.rect(surface, self.color, self.top_rect)
pygame.draw.rect(surface, self.color, self.bottom_rect)
def off_screen(self):
return self.x + self.width < 0
def collision(self, bird):
return self.top_rect.colliderect(bird.rect) or self.bottom_rect.colliderect(bird.rect)
Adding a ground can make the game more interesting.
class Ground:
VELOCITY = 3
def __init__(self):
self.image = pygame.Surface((SCREEN_WIDTH, 100))
self.image.fill((150, 75, 0)) # Brown ground
self.rect1 = self.image.get_rect(topleft=(0, SCREEN_HEIGHT - 100))
self.rect2 = self.image.get_rect(topleft=(SCREEN_WIDTH, SCREEN_HEIGHT - 100))
def update(self):
self.rect1.x -= self.VELOCITY
self.rect2.x -= self.VELOCITY
if self.rect1.right < 0:
self.rect1.x = self.rect2.right
if self.rect2.right < 0:
self.rect2.x = self.rect1.right
def draw(self, surface):
surface.blit(self.image, self.rect1)
surface.blit(self.image, self.rect2)
Detect when the player wants the bird to flap (usually by pressing the spacebar or clicking the mouse).
def handle_input(bird):
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.flap()
if event.type == pygame.MOUSEBUTTONDOWN:
bird.flap()
Check if the bird collides with any pipes or the ground/top boundaries.
def check_collision(bird, pipes, ground):
# Collision with ground
if bird.rect.bottom >= ground.rect1.top:
return True
# Collision with top boundary
if bird.rect.top <= 0:
return True
# Collision with pipes
for pipe in pipes:
if pipe.collision(bird):
return True
return False
Combine everything into the main game loop.
def main():
bird = Bird()
pipes = []
ground = Ground()
spawn_pipe_event = pygame.USEREVENT + 1
pygame.time.set_timer(spawn_pipe_event, 1500) # Spawn a pipe every 1.5 seconds
score = 0
font = pygame.font.SysFont(None, 36)
while True:
handle_input(bird)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == spawn_pipe_event:
pipes.append(Pipe(SCREEN_WIDTH))
# Update game objects
bird.update()
ground.update()
for pipe in pipes:
pipe.update()
# Update score
if pipe.x + pipe.width < bird.rect.x and not hasattr(pipe, 'passed'):
pipe.passed = True
score += 1
# Remove off-screen pipes
pipes = [pipe for pipe in pipes if not pipe.off_screen()]
# Check for collisions
if check_collision(bird, pipes, ground):
print(f"Game Over! Your score: {score}")
pygame.quit()
sys.exit()
# Drawing
screen.fill(WHITE)
bird.draw(screen)
for pipe in pipes:
pipe.draw(screen)
ground.draw(screen)
# Render score
score_surface = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_surface, (10, 10))
pygame.display.flip()
clock.tick(FPS)
if __name__ == "__main__":
main()
To make your game more engaging, consider the following enhancements:
Graphics: Replace placeholder rectangles with actual images for the bird, pipes, and ground.
self.image = pygame.image.load('bird.png').convert_alpha()
Animations: Animate the bird's wings to simulate flapping.
Sound Effects: Add sound effects for flapping, collisions, and scoring.
Scrolling Background: Implement a moving background to give a sense of motion.
Difficulty Scaling: Increase pipe speed or decrease gap size as the score increases.
Restart Mechanism: Allow the player to restart the game after a collision instead of closing the window.
Here's the complete code incorporating all the elements discussed:
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Game Constants
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
FPS = 60
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Set up the display
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Bird")
# Clock to control the frame rate
clock = pygame.time.Clock()
class Bird:
def __init__(self):
self.image = pygame.Surface((34, 24)) # Placeholder for the bird
self.image.fill((255, 255, 0)) # Yellow bird
self.rect = self.image.get_rect()
self.rect.center = (100, SCREEN_HEIGHT // 2)
self.velocity = 0
self.gravity = 0.5
self.flap_strength = -10
def flap(self):
self.velocity = self.flap_strength
def update(self):
self.velocity += self.gravity
self.rect.y += self.velocity
def draw(self, surface):
surface.blit(self.image, self.rect)
class Pipe:
GAP = 150
VELOCITY = 3
def __init__(self, x):
self.width = 80
self.color = (0, 255, 0) # Green pipes
self.x = x
self.height = random.randint(50, SCREEN_HEIGHT - self.GAP - 50)
self.top_rect = pygame.Rect(self.x, 0, self.width, self.height)
self.bottom_rect = pygame.Rect(
self.x, self.height + self.GAP, self.width, SCREEN_HEIGHT - self.height - self.GAP
)
self.passed = False
def update(self):
self.x -= self.VELOCITY
self.top_rect.x = self.x
self.bottom_rect.x = self.x
def draw(self, surface):
pygame.draw.rect(surface, self.color, self.top_rect)
pygame.draw.rect(surface, self.color, self.bottom_rect)
def off_screen(self):
return self.x + self.width < 0
def collision(self, bird):
return self.top_rect.colliderect(bird.rect) or self.bottom_rect.colliderect(bird.rect)
class Ground:
VELOCITY = 3
def __init__(self):
self.image = pygame.Surface((SCREEN_WIDTH, 100))
self.image.fill((150, 75, 0)) # Brown ground
self.rect1 = self.image.get_rect(topleft=(0, SCREEN_HEIGHT - 100))
self.rect2 = self.image.get_rect(topleft=(SCREEN_WIDTH, SCREEN_HEIGHT - 100))
def update(self):
self.rect1.x -= self.VELOCITY
self.rect2.x -= self.VELOCITY
if self.rect1.right < 0:
self.rect1.x = self.rect2.right
if self.rect2.right < 0:
self.rect2.x = self.rect1.right
def draw(self, surface):
surface.blit(self.image, self.rect1)
surface.blit(self.image, self.rect2)
def handle_input(bird):
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.flap()
if event.type == pygame.MOUSEBUTTONDOWN:
bird.flap()
def check_collision(bird, pipes, ground):
# Collision with ground
if bird.rect.bottom >= ground.rect1.top:
return True
# Collision with top boundary
if bird.rect.top <= 0:
return True
# Collision with pipes
for pipe in pipes:
if pipe.collision(bird):
return True
return False
def main():
bird = Bird()
pipes = []
ground = Ground()
spawn_pipe_event = pygame.USEREVENT + 1
pygame.time.set_timer(spawn_pipe_event, 1500) # Spawn a pipe every 1.5 seconds
score = 0
font = pygame.font.SysFont(None, 36)
while True:
handle_input(bird)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == spawn_pipe_event:
pipes.append(Pipe(SCREEN_WIDTH))
# Update game objects
bird.update()
ground.update()
for pipe in pipes:
pipe.update()
# Update score
if not pipe.passed and pipe.x + pipe.width < bird.rect.x:
pipe.passed = True
score += 1
# Remove off-screen pipes
pipes = [pipe for pipe in pipes if not pipe.off_screen()]
# Check for collisions
if check_collision(bird, pipes, ground):
print(f"Game Over! Your score: {score}")
pygame.quit()
sys.exit()
# Drawing
screen.fill(WHITE)
bird.draw(screen)
for pipe in pipes:
pipe.draw(screen)
ground.draw(screen)
# Render score
score_surface = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_surface, (10, 10))
pygame.display.flip()
clock.tick(FPS)
if __name__ == "__main__":
main()
Save your Python script and run it using the command line:
python flappy_bird.py
Use the spacebar or mouse clicks to make the bird flap. Avoid the pipes and try to achieve the highest score possible!
To enhance your game further, you might explore the following topics:
Creating a Flappy Bird game in Python with Pygame is an excellent project to improve your programming and game development skills. Experiment with different features and customizations to make the game uniquely yours. Happy coding!