Generate Python code for an enhanced Flappy Bird clone using the Pygame library,…
- User
Generate Python code for an enhanced Flappy Bird clone using the Pygame library, featuring increased complexity and polish. Core Constraint: The game must be entirely self-contained, using no external asset files (no images, sounds, or custom fonts). All visual elements, including backgrounds and effects, must be generated programmatically using Pygame's drawing functions (pygame.draw.*) and standard system fonts (pygame.font.SysFont). Key Features to Implement: Game Structure & States: Title Screen: A simple starting screen displaying the game title (drawn text) and instructions (e.g., "Press Space to Start"). Gameplay State: The main interactive game loop. Pause State: Ability to pause/unpause the game (e.g., using the 'P' key), overlaying a "Paused" message. Game Over Screen: Displayed upon collision, showing the final score, the high score, and instructions to restart (e.g., "Press Space to Retry"). Visuals & Presentation (Programmatic): Enhanced Bird: Represent the bird using multiple combined primitive shapes (e.g., a circle body, a triangle beak) to give it more character than a single shape. Implement a simple flapping animation (e.g., slightly changing the shape, position, or color of a 'wing' element upon flapping). Procedural Background: Create a multi-layered background using solid colors and drawn shapes (e.g., simple rectangles for distant buildings, circles for clouds or stars). Parallax Scrolling: Implement parallax scrolling for the background layers. Elements further 'away' should move slower than elements closer to the foreground (like pipes). Visual Feedback: Add simple visual cues, like a screen flash (briefly change background color) on collision or a subtle particle effect (small drawn squares/circles) when flapping or scoring (optional, if feasible without impacting performance). Gameplay Mechanics: Physics: Implement smoother gravity and flap mechanics (e.g., variable jump height based on press duration, or diminishing returns on rapid flaps). Dynamic Pipes: Pipes should still move right-to-left. Introduce vertical movement to some pipes (pipes slowly oscillating up and down as they approach). Vary the gap size between pipe pairs randomly within a defined range. Collision Detection: Accurate collision detection between the bird (consider its multi-shape form if applicable) and pipes/screen boundaries. Difficulty Scaling: The game difficulty should increase progressively over time or based on score. This could involve: Increasing pipe scrolling speed. Decreasing the gap size between pipes (down to a minimum). Increasing the frequency or amplitude of vertical pipe movement. Increasing the rate at which pipes are generated. Scoring & Progression: Score: Increment score for passing pipes. Display prominently using pygame.font.SysFont. High Score: Implement a persistent high score saved locally to a simple text file (e.g., highscore.txt). Load it on startup and save it when a new high score is achieved. Display the high score on the Title and Game Over screens. Medal System (Optional): Based on the final score, display a simple text-based medal (e.g., "Bronze", "Silver", "Gold") on the Game Over screen using different colors drawn with SysFont. Code Quality: Employ Object-Oriented Programming (OOP): Use classes for Bird, Pipe, and potentially a GameManager or state handler to structure the code logically. Include clear comments and use descriptive variable names. Ensure the code is reasonably efficient to maintain smooth gameplay.
- Assistant
Certainly! Below is a complete, self-contained Python script for an enhanced Flappy Bird clone using Pygame. It includes:
✅ No external assets — all visuals are generated with
pygame.draw.*andpygame.font.SysFont.✅ Game states: Title Screen, Gameplay, Pause, Game Over.
✅ Enhanced bird with flapping animation and composed of multiple shapes.
✅ Procedural parallax background with clouds and buildings.
✅ Dynamic pipes with vertical oscillation and variable gaps.
✅ Difficulty scaling over time.
✅ Score and high score tracking (saved to
highscore.txt).✅ Optional medal system based on score.
✅ Visual feedback: screen flash on collision, particles on flap.
✅ Object-Oriented Design with clear comments.
📦 Requirements:
- Python 3.x
- Pygame (
pip install pygame)
import pygame import random import math import os # Initialize Pygame pygame.init() pygame.font.init() # Constants WIDTH, HEIGHT = 400, 600 FPS = 60 GRAVITY = 0.4 FLAP_STRENGTH = -7 PIPE_WIDTH = 60 PIPE_GAP_MIN = 100 PIPE_GAP_MAX = 160 PIPE_INTERVAL = 1500 # milliseconds PIPE_SPEED_START = 2 PIPE_SPEED_MAX = 6 PIPE_OSCILLATION_AMPLITUDE = 30 PIPE_OSCILLATION_SPEED = 0.02 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) SKY_BLUE = (135, 206, 235) DARK_BLUE = (70, 130, 180) GREEN = (0, 200, 0) DARK_GREEN = (0, 150, 0) RED = (255, 0, 0) GOLD = (255, 215, 0) SILVER = (192, 192, 192) BRONZE = (205, 127, 50) FLASH_COLOR = (255, 255, 255) # Fonts FONT = pygame.font.SysFont("Arial", 24) BIG_FONT = pygame.font.SysFont("Arial", 48) # High Score File HIGHSCORE_FILE = "highscore.txt" # Load high score def load_highscore(): if os.path.exists(HIGHSCORE_FILE): with open(HIGHSCORE_FILE, "r") as f: try: return int(f.read()) except: return 0 return 0 # Save high score def save_highscore(score): with open(HIGHSCORE_FILE, "w") as f: f.write(str(score)) # Bird Class class Bird: def __init__(self, x, y): self.x = x self.y = y self.radius = 12 self.vel = 0 self.flap_timer = 0 self.particles = [] def update(self, keys): self.vel += GRAVITY self.y += self.vel # Flap if keys[pygame.K_SPACE]: if self.flap_timer == 0: self.vel = FLAP_STRENGTH self.flap_timer = 10 self.spawn_particles() if self.flap_timer > 0: self.flap_timer -= 1 # Update particles for p in self.particles: p[0][1] += p[1][1] p[0][0] += p[1][0] p[2] -= 1 self.particles = [p for p in self.particles if p[2] > 0] def spawn_particles(self): for _ in range(5): pos = [self.x, self.y] vel = [random.uniform(-1, 1), random.uniform(1, 3)] life = random.randint(10, 20) self.particles.append([pos, vel, life]) def draw(self, screen): # Body pygame.draw.circle(screen, YELLOW, (int(self.x), int(self.y)), self.radius) # Wing (flap animation) wing_offset = -5 if self.flap_timer > 0 else 0 pygame.draw.polygon(screen, DARK_GREEN, [ (self.x - 5, self.y), (self.x - 15, self.y + 5 + wing_offset), (self.x - 5, self.y + 10 + wing_offset) ]) # Beak pygame.draw.polygon(screen, ORANGE, [ (self.x + self.radius, self.y), (self.x + self.radius + 6, self.y - 3), (self.x + self.radius + 6, self.y + 3) ]) # Eye pygame.draw.circle(screen, WHITE, (int(self.x + 4), int(self.y - 4)), 3) pygame.draw.circle(screen, BLACK, (int(self.x + 4), int(self.y - 4)), 1) # Particles for p in self.particles: pygame.draw.rect(screen, WHITE, (*p[0], 2, 2)) def get_rect(self): return pygame.Rect(self.x - self.radius, self.y - self.radius, self.radius*2, self.radius*2) # Pipe Class class Pipe: def __init__(self, x, gap_size, speed, oscillate=False): self.x = x self.gap_size = gap_size self.top_height = random.randint(50, HEIGHT - gap_size - 100) self.speed = speed self.oscillate = oscillate self.osc_phase = random.uniform(0, math.pi * 2) def update(self): self.x -= self.speed if self.oscillate: self.osc_phase += PIPE_OSCILLATION_SPEED offset = math.sin(self.osc_phase) * PIPE_OSCILLATION_AMPLITUDE self.top_height = max(30, min(HEIGHT - self.gap_size - 30, self.top_height + offset)) def draw(self, screen): # Top pipe pygame.draw.rect(screen, DARK_GREEN, (self.x, 0, PIPE_WIDTH, self.top_height)) # Bottom pipe bottom_y = self.top_height + self.gap_size pygame.draw.rect(screen, DARK_GREEN, (self.x, bottom_y, PIPE_WIDTH, HEIGHT - bottom_y)) def collides_with(self, bird_rect): top_rect = pygame.Rect(self.x, 0, PIPE_WIDTH, self.top_height) bottom_rect = pygame.Rect(self.x, self.top_height + self.gap_size, PIPE_WIDTH, HEIGHT) return bird_rect.colliderect(top_rect) or bird_rect.colliderect(bottom_rect) def passed_by(self, bird_x): return self.x + PIPE_WIDTH < bird_x # Background Layer class BackgroundLayer: def __init__(self, speed, color, shape_func): self.speed = speed self.color = color self.shape_func = shape_func self.offset = 0 self.elements = [random.randint(0, WIDTH) for _ in range(10)] def update(self): self.offset += self.speed if self.offset > WIDTH: self.offset = 0 def draw(self, screen): for x in self.elements: self.shape_func(screen, (x - self.offset) % WIDTH, self.color) # Game Manager class GameManager: def __init__(self): self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Flappy Bird Clone") self.clock = pygame.time.Clock() self.running = True self.state = "TITLE" self.bird = Bird(100, HEIGHT//2) self.pipes = [] self.pipe_timer = 0 self.score = 0 self.highscore = load_highscore() self.flash_timer = 0 self.pipe_speed = PIPE_SPEED_START self.pipe_gap = PIPE_GAP_MAX self.last_pipe_time = pygame.time.get_ticks() # Background layers self.bg_layers = [ BackgroundLayer(0.2, (200, 200, 255), self.draw_cloud), BackgroundLayer(0.5, (100, 100, 150), self.draw_building) ] def reset(self): self.bird = Bird(100, HEIGHT//2) self.pipes = [] self.pipe_timer = 0 self.score = 0 self.pipe_speed = PIPE_SPEED_START self.pipe_gap = PIPE_GAP_MAX self.last_pipe_time = pygame.time.get_ticks() def draw_cloud(self, screen, x, color): pygame.draw.circle(screen, color, (int(x), 100), 20) def draw_building(self, screen, x, color): height = random.randint(50, 150) pygame.draw.rect(screen, color, (int(x), HEIGHT - height, 30, height)) def run(self): while self.running: dt = self.clock.tick(FPS) keys = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if self.state == "TITLE": self.update_title(keys) elif self.state == "PLAYING": self.update_gameplay(keys) elif self.state == "PAUSED": self.update_pause(keys) elif self.state == "GAMEOVER": self.update_gameover(keys) pygame.display.flip() def update_title(self, keys): self.screen.fill(SKY_BLUE) self.draw_background() title = BIG_FONT.render("Flappy Bird", True, WHITE) instr = FONT.render("Press SPACE to Start", True, WHITE) self.screen.blit(title, (WIDTH//2 - title.get_width()//2, HEIGHT//3)) self.screen.blit(instr, (WIDTH//2 - instr.get_width()//2, HEIGHT//2)) if keys[pygame.K_SPACE]: self.reset() self.state = "PLAYING" def update_gameplay(self, keys): if keys[pygame.K_p]: self.state = "PAUSED" return self.screen.fill(SKY_BLUE) self.draw_background() self.bird.update(keys) self.bird.draw(self.screen) # Pipes now = pygame.time.get_ticks() if now - self.last_pipe_time > PIPE_INTERVAL: gap = random.randint(self.pipe_gap - 20, self.pipe_gap + 20) oscillate = random.random() < 0.5 self.pipes.append(Pipe(WIDTH, gap, self.pipe_speed, oscillate)) self.last_pipe_time = now for pipe in self.pipes: pipe.update() pipe.draw(self.screen) # Remove off-screen pipes self.pipes = [p for p in self.pipes if p.x + PIPE_WIDTH > 0] # Collision bird_rect = self.bird.get_rect() for pipe in self.pipes: if pipe.collides_with(bird_rect): self.flash_timer = 5 self.state = "GAMEOVER" if self.score > self.highscore: self.highscore = self.score save_highscore(self.highscore) return if self.bird.y > HEIGHT or self.bird.y < 0: self.flash_timer = 5 self.state = "GAMEOVER" if self.score > self.highscore: self.highscore = self.score save_highscore(self.highscore) return # Scoring for pipe in self.pipes: if not hasattr(pipe, "scored") and pipe.passed_by(self.bird.x): self.score += 1 pipe.scored = True # Difficulty scaling self.pipe_speed = min(PIPE_SPEED_MAX, self.pipe_speed + 0.1) self.pipe_gap = max(PIPE_GAP_MIN, self.pipe_gap - 2) # Flash effect if self.flash_timer > 0: self.screen.fill(FLASH_COLOR) self.flash_timer -= 1 # Score score_text = FONT.render(f"Score: {self.score}", True, BLACK) self.screen.blit(score_text, (10, 10)) def update_pause(self, keys): self.screen.fill(SKY_BLUE) self.draw_background() pause_text = BIG_FONT.render("Paused", True, WHITE) self.screen.blit(pause_text, (WIDTH//2 - pause_text.get_width()//2, HEIGHT//2)) if keys[pygame.K_p]: self.state = "PLAYING" def update_gameover(self, keys): self.screen.fill(SKY_BLUE) self.draw_background() over = BIG_FONT.render("Game Over", True, RED) score = FONT.render(f"Score: {self.score}", True, WHITE) high = FONT.render(f"High Score: {self.highscore}", True, WHITE) retry = FONT.render("Press SPACE to Retry", True, WHITE) self.screen.blit(over, (WIDTH//2 - over.get_width()//2, HEIGHT//4)) self.screen.blit(score, (WIDTH//2 - score.get_width()//2, HEIGHT//2 - 30)) self.screen.blit(high, (WIDTH//2 - high.get_width()//2, HEIGHT//2)) self.screen.blit(retry, (WIDTH//2 - retry.get_width()//2, HEIGHT//2 + 40)) # Medal medal = None if self.score >= 30: medal = ("Gold", GOLD) elif self.score >= 20: medal = ("Silver", SILVER) elif self.score >= 10: medal = ("Bronze", BRONZE) if medal: medal_text = FONT.render(f"Medal: {medal[0]}", True, medal[1]) self.screen.blit(medal_text, (WIDTH//2 - medal_text.get_width()//2, HEIGHT//2 + 80)) if keys[pygame.K_SPACE]: self.reset() self.state = "PLAYING" def draw_background(self): for layer in self.bg_layers: layer.update() layer.draw(self.screen) # Colors used in bird YELLOW = (255, 255, 0) ORANGE = (255, 165, 0) # Run the game if __name__ == "__main__": GameManager().run() pygame.quit()
📝 Notes:
- The bird is composed of a circle (body), triangle (beak), and a flapping wing.
- Background includes parallax layers: clouds and buildings.
- Pipes oscillate vertically and have variable gaps.
- Difficulty increases as score increases.
- High score is saved to
highscore.txtin the same directory. - Press
Pto pause/unpause,SPACEto flap or start/retry.
Enjoy your enhanced Flappy Bird clone! 🐤🚀
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.