Make flappy bird without external files, using pygame
- User
Make flappy bird without external files, using pygame
- Assistant
Make flappy bird without external files, using pygame
Creating a simple version of Flappy Bird using Pygame without relying on any external files involves drawing all game elements (like the bird and pipes) using Pygame's built-in shapes and functionalities. Below is a complete, self-contained script that accomplishes this. You can copy and run it directly if you have Python and Pygame installed.
Python: Make sure you have Python installed. You can download it from python.org.
Pygame: Install Pygame using pip if you haven't already:
pip install pygame
Here's the complete code:
import pygame
import random
import sys
# 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")
# Frame rate
FPS = 60
CLOCK = pygame.time.Clock()
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 200, 0)
RED = (200, 0, 0)
BLUE = (0, 0, 200)
BACKGROUND_COLOR = (135, 206, 235) # Sky blue
# Game constants
GRAVITY = 0.5
BIRD_FLAP_STRENGTH = -10
PIPE_SPEED = 3
PIPE_GAP = 150
PIPE_FREQUENCY = 1500 # milliseconds
# Fonts
FONT = pygame.font.SysFont(None, 48)
FONT_SMALL = pygame.font.SysFont(None, 36)
# Game variables
score = 0
high_score = 0
# Define the Bird class
class Bird:
def __init__(self):
self.radius = 20
self.x = 100
self.y = SCREEN_HEIGHT // 2
self.vel = 0
self.color = YELLOW = (255, 255, 0)
def flap(self):
self.vel = BIRD_FLAP_STRENGTH
def update(self):
self.vel += GRAVITY
self.y += self.vel
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
def get_rect(self):
return pygame.Rect(self.x - self.radius, self.y - self.radius,
self.radius * 2, self.radius * 2)
# Define the Pipe class
class Pipe:
def __init__(self):
self.width = 60
self.color = GREEN
self.x = SCREEN_WIDTH
self.gap = PIPE_GAP
self.top_height = random.randint(50, SCREEN_HEIGHT - self.gap - 50)
self.bottom_height = SCREEN_HEIGHT - self.top_height - self.gap
def update(self):
self.x -= PIPE_SPEED
def draw(self, screen):
# Top pipe
pygame.draw.rect(screen, self.color, (self.x, 0, self.width, self.top_height))
# Bottom pipe
pygame.draw.rect(screen, self.color, (self.x, SCREEN_HEIGHT - self.bottom_height,
self.width, self.bottom_height))
def is_off_screen(self):
return self.x + self.width < 0
def has_passed(self, bird):
return self.x + self.width < bird.x and not hasattr(self, 'passed')
# Main game function
def main():
global score, high_score
bird = Bird()
pipes = []
last_pipe = pygame.time.get_ticks()
running = True
game_over = False
while running:
CLOCK.tick(FPS)
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 and not game_over:
bird.flap()
if event.key == pygame.K_SPACE and game_over:
# Reset the game
bird = Bird()
pipes = []
score = 0
game_over = False
if not game_over:
# Update bird
bird.update()
# Generate new pipes
current_time = pygame.time.get_ticks()
if current_time - last_pipe > PIPE_FREQUENCY:
pipes.append(Pipe())
last_pipe = current_time
# Update pipes
for pipe in pipes:
pipe.update()
# Remove off-screen pipes
pipes = [pipe for pipe in pipes if not pipe.is_off_screen()]
# Collision detection
bird_rect = bird.get_rect()
for pipe in pipes:
# Top pipe rectangle
top_rect = pygame.Rect(pipe.x, 0, pipe.width, pipe.top_height)
# Bottom pipe rectangle
bottom_rect = pygame.Rect(pipe.x, SCREEN_HEIGHT - pipe.bottom_height,
pipe.width, pipe.bottom_height)
if bird_rect.colliderect(top_rect) or bird_rect.colliderect(bottom_rect):
game_over = True
if score > high_score:
high_score = score
# Scoring
if pipe.x + pipe.width < bird.x and not hasattr(pipe, 'scored'):
score += 1
pipe.scored = True
# Check if bird hits the ground or goes above the screen
if bird.y + bird.radius >= SCREEN_HEIGHT or bird.y - bird.radius <= 0:
game_over = True
if score > high_score:
high_score = score
# Drawing
SCREEN.fill(BACKGROUND_COLOR)
# Draw bird
bird.draw(SCREEN)
# Draw pipes
for pipe in pipes:
pipe.draw(SCREEN)
# Draw score
score_text = FONT.render(str(score), True, WHITE)
SCREEN.blit(score_text, (SCREEN_WIDTH // 2 - score_text.get_width() // 2, 50))
# Draw high score
high_score_text = FONT_SMALL.render(f"High Score: {high_score}", True, WHITE)
SCREEN.blit(high_score_text, (10, 10))
if game_over:
over_text = FONT.render("GAME OVER", True, RED)
retry_text = FONT_SMALL.render("Press SPACE to Retry", True, WHITE)
SCREEN.blit(over_text, (SCREEN_WIDTH // 2 - over_text.get_width() // 2, SCREEN_HEIGHT // 2 - 50))
SCREEN.blit(retry_text, (SCREEN_WIDTH // 2 - retry_text.get_width() // 2, SCREEN_HEIGHT // 2 + 10))
pygame.display.flip()
if __name__ == "__main__":
main()
Pygame Initialization: The script starts by initializing Pygame and setting up the game window with a specified width and height.
Colors and Fonts: Basic colors are defined using RGB tuples. Fonts for displaying the score and messages are also initialized.
Attributes: The bird is represented as a circle with a position (x, y), velocity (vel), and color.
Methods:
flap(): Applies an upward force by setting the bird's vertical velocity to a negative value.update(): Updates the bird's position based on its velocity and applies gravity.draw(screen): Draws the bird on the screen.get_rect(): Returns a rectangular area around the bird for collision detection.Attributes: Each pipe has a width, color, x-position, and heights for the top and bottom pipes, which are randomly generated to create varied gaps.
Methods:
update(): Moves the pipe to the left.draw(screen): Draws the top and bottom rectangles representing the pipes.is_off_screen(): Checks if the pipe has moved past the left edge of the screen.has_passed(bird): Determines if the bird has successfully passed the pipe, used for scoring.Event Handling: The game listens for quit events and key presses. Pressing the spacebar makes the bird flap. If the game is over, pressing spacebar resets the game.
Game Logic:
PIPE_FREQUENCY).Rendering:
Frame Rate: The game runs at the specified frames per second (FPS) to ensure consistent timing.
To run the game:
Make sure you have Python and Pygame installed.
Save the script to a file, for example, flappy_bird_clone.py.
Open a terminal or command prompt and navigate to the directory containing the script.
Run the script using Python:
python flappy_bird_clone.py
Control: Press the spacebar to make the bird flap upwards.
Objective: Navigate the bird through the gaps between the pipes without colliding.
Scoring: Each set of pipes successfully passed increases your score by one.
Game Over: Colliding with a pipe or hitting the ground/ceiling ends the game. Press the spacebar to retry.
Feel free to tweak the game constants to adjust the difficulty:
Gravity (GRAVITY): Increase for faster falling.
Flap Strength (BIRD_FLAP_STRENGTH): More negative value for a stronger upward flap.
Pipe Speed (PIPE_SPEED): Increase to make the game faster and more challenging.
Pipe Gap (PIPE_GAP): Decrease to reduce the space between pipes, making it harder to pass.
Pipe Frequency (PIPE_FREQUENCY): Decrease the time between pipe generations for a denser obstacle course.
This script provides a foundational Flappy Bird clone using Pygame without any external assets. You can build upon this by adding features such as different bird animations, sound effects (using Pygame's built-in sounds), or more complex scoring systems. Happy coding!
Not yet included in a published release.