Generate Python code for an enhanced Flappy Bird clone using the Pygame library,…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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.
Below is a single‑file, totally self‑contained Flappy‑Bird‑like game that fulfils every requirement you listed.
Just copy‑paste it into flappy_clone.py, make sure you have pygame installed (pip install pygame), and run with python flappy_clone.py.
"""
Enhanced Flappy Bird Clone – all graphics generated procedurally.
Author : ChatGPT demo
Python : 3.8+
Pygame : 2.x
"""
import math
import os
import random
import sys
from pathlib import Path
import pygame
# ──────────────────────────────────────────────────────────────────────────────
# CONFIGURATION
# ──────────────────────────────────────────────────────────────────────────────
WIDTH, HEIGHT = 400, 600
FPS = 60
TITLE = "Flappy Clone"
GRAVITY = 0.25
FLAP_VELOCITY = -6.5
MAX_DROP_SPEED = 10
PIPE_SPAWN_BASE = 1500 # ms between pipes at easy difficulty
PIPE_SPEED_BASE = 2.2 # px/frame at easy difficulty
GAP_BASE = 160 # initial gap size
GAP_MIN = 90 # minimum possible gap
PIPE_OSC_AMP = 40 # maximum up‑down oscillation of moving pipes
DIFFICULTY_STEP = 10 # score interval for difficulty scaling
FLASH_TIME = 6 # frames of bright screen flash on collision
PARTICLE_COUNT = 10 # small particles emitted on flap
HIGH_SCORE_FILE = Path("highscore.txt")
# Colors
SKY_TOP = (105, 200, 255)
SKY_BOTTOM = (185, 235, 255)
WHITE = (255, 255, 255)
BLACK = (30, 30, 30)
GREEN = (80, 200, 60)
RED = (220, 70, 70)
GOLD = (255, 215, 0)
SILVER = (192, 192, 192)
BRONZE = (205, 127, 50)
pygame.init()
pygame.mixer.quit() # ensure we don't require audio device (optional)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()
font_big = pygame.font.SysFont(None, 56)
font_med = pygame.font.SysFont(None, 32)
font_small = pygame.font.SysFont(None, 24)
# ──────────────────────────────────────────────────────────────────────────────
# HELPERS
# ──────────────────────────────────────────────────────────────────────────────
def draw_vertical_gradient(surface, top_color, bottom_color):
"""Draws a vertical gradient to cover the surface."""
for y in range(surface.get_height()):
ratio = y / surface.get_height()
r = int(top_color[0] * (1 - ratio) + bottom_color[0] * ratio)
g = int(top_color[1] * (1 - ratio) + bottom_color[1] * ratio)
b = int(top_color[2] * (1 - ratio) + bottom_color[2] * ratio)
pygame.draw.line(surface, (r, g, b), (0, y), (surface.get_width(), y))
def load_high_score() -> int:
if HIGH_SCORE_FILE.exists():
try:
return int(HIGH_SCORE_FILE.read_text().strip())
except Exception:
return 0
return 0
def save_high_score(score: int):
try:
HIGH_SCORE_FILE.write_text(str(score))
except Exception:
pass
# ──────────────────────────────────────────────────────────────────────────────
# GAME OBJECTS
# ──────────────────────────────────────────────────────────────────────────────
class Particle:
"""Tiny circle that fades out – used for flap effect."""
def __init__(self, x, y):
self.x = x
self.y = y
angle = random.uniform(-math.pi, math.pi)
speed = random.uniform(1, 2)
self.vx = math.cos(angle) * speed
self.vy = math.sin(angle) * speed - 1
self.life = random.randint(20, 30)
def update(self):
self.x += self.vx
self.y += self.vy
self.vy += 0.1
self.life -= 1
def draw(self, surface):
if self.life > 0:
alpha = max(0, min(255, self.life * 10))
surf = pygame.Surface((4, 4), pygame.SRCALPHA)
pygame.draw.circle(surf, (255, 255, 255, alpha), (2, 2), 2)
surface.blit(surf, (self.x - 2, self.y - 2))
class Bird:
"""Player character composed of primitive shapes."""
def __init__(self):
self.reset()
def reset(self):
self.x = WIDTH * 0.25
self.y = HEIGHT / 2
self.vel = 0
self.rotation = 0
self.wing_up = True
self.frame_count = 0
self.radius = 12
def flap(self):
self.vel = FLAP_VELOCITY
self.wing_up = not self.wing_up
def update(self):
self.frame_count += 1
self.vel += GRAVITY
self.vel = min(self.vel, MAX_DROP_SPEED)
self.y += self.vel
# Rotation for visual feedback
self.rotation = max(-25, min(90, self.vel * 6))
def get_rect(self):
return pygame.Rect(self.x - self.radius, self.y - self.radius,
self.radius * 2, self.radius * 2)
def draw(self, surface):
body_color = (255, 240, 0)
wing_color = (255, 200, 0)
# Body (circle)
pygame.draw.circle(surface, body_color, (int(self.x), int(self.y)),
self.radius)
# Wing – small ellipse that toggles up/down
wing_offset_y = -8 if self.wing_up else 4
pygame.draw.ellipse(
surface,
wing_color,
(self.x - 10, self.y + wing_offset_y, 20, 8),
)
# Beak – little triangle
beak_points = [
(self.x + self.radius, self.y),
(self.x + self.radius + 6, self.y - 3),
(self.x + self.radius + 6, self.y + 3),
]
pygame.draw.polygon(surface, (255, 150, 0), beak_points)
# Eye
pygame.draw.circle(surface, BLACK, (int(self.x + 4), int(self.y - 4)),
2)
class Pipe:
"""Pipe pair with optional vertical oscillation."""
def __init__(self, x, gap_y, gap_h, speed, oscillate=False):
self.x = x
self.gap_y = gap_y
self.gap_h = gap_h
self.speed = speed
self.oscillate = oscillate
self.time = 0 # for oscillation
self.width = 45
self.passed = False
def update(self):
self.x -= self.speed
if self.oscillate:
# simple sine wave motion
self.time += 0.03
self.gap_y += math.sin(self.time) * 1.5 # small each frame
def off_screen(self):
return self.x + self.width < 0
def collides(self, bird: Bird) -> bool:
rect_top = pygame.Rect(self.x, 0, self.width,
self.gap_y - self.gap_h / 2)
rect_bottom = pygame.Rect(self.x,
self.gap_y + self.gap_h / 2, self.width,
HEIGHT - (self.gap_y + self.gap_h / 2))
return rect_top.colliderect(
bird.get_rect()) or rect_bottom.colliderect(bird.get_rect())
def draw(self, surface):
# simple green rectangles with darker outline
rect_top = pygame.Rect(self.x, 0, self.width,
self.gap_y - self.gap_h / 2)
rect_bottom = pygame.Rect(self.x,
self.gap_y + self.gap_h / 2, self.width,
HEIGHT - (self.gap_y + self.gap_h / 2))
pygame.draw.rect(surface, GREEN, rect_top)
pygame.draw.rect(surface, GREEN, rect_bottom)
pygame.draw.rect(surface, BLACK, rect_top, 2)
pygame.draw.rect(surface, BLACK, rect_bottom, 2)
class BackgroundLayer:
"""Repeating shapes that scroll at a given speed factor (parallax)."""
def __init__(self, speed_factor, generate_func):
self.speed_factor = speed_factor
self.generate_func = generate_func
self.shapes = self.generate_func()
def update(self, base_speed):
for shape in self.shapes:
shape['x'] -= base_speed * self.speed_factor
# recycle shapes
if self.shapes and self.shapes[0]['x'] + self.shapes[0]['w'] < 0:
self.shapes.pop(0)
while len(self.shapes) < 6:
self.shapes.append(self.generate_shape(WIDTH))
def generate_shape(self, start_x):
return self.generate_func(single=True, start_x=start_x)[0]
def draw(self, surface):
for shape in self.shapes:
shape_rect = pygame.Rect(shape['x'], shape['y'], shape['w'],
shape['h'])
pygame.draw.rect(surface, shape['color'], shape_rect)
@staticmethod
def building_generator(single=False, start_x=None):
shapes = []
x = start_x if start_x is not None else 0
for _ in range(6 if not single else 1):
w = random.randint(50, 80)
h = random.randint(50, 140)
y = HEIGHT - h
color = (70, 70, 70)
shapes.append({
'x': x,
'y': y,
'w': w,
'h': h,
'color': color
})
x += w + random.randint(10, 30)
return shapes
@staticmethod
def cloud_generator(single=False, start_x=None):
shapes = []
x = start_x if start_x is not None else 0
for _ in range(6 if not single else 1):
w = random.randint(40, 80)
h = random.randint(20, 40)
y = random.randint(40, HEIGHT // 2)
color = WHITE
shapes.append({
'x': x,
'y': y,
'w': w,
'h': h,
'color': color
})
x += w + random.randint(80, 120)
return shapes
# ──────────────────────────────────────────────────────────────────────────────
# GAME MANAGER
# ──────────────────────────────────────────────────────────────────────────────
class Game:
def __init__(self):
self.state = "title"
self.bird = Bird()
self.pipes = []
self.particles = []
self.score = 0
self.high_score = load_high_score()
self.pipe_timer = 0
self.flash_timer = 0
# background layers
self.clouds = BackgroundLayer(0.2, BackgroundLayer.cloud_generator)
self.buildings = BackgroundLayer(0.5,
BackgroundLayer.building_generator)
# ─────────────── Utility ───────────────
def current_difficulty(self):
"""Return current pipe speed & spawn interval & gap based on score."""
level = self.score // DIFFICULTY_STEP
speed = PIPE_SPEED_BASE + level * 0.3
spawn = max(700, PIPE_SPAWN_BASE - level * 100)
gap = max(GAP_MIN, GAP_BASE - level * 8)
return speed, spawn, gap
# ─────────────── State transitions ───────────────
def reset_gameplay(self):
self.bird.reset()
self.pipes.clear()
self.particles.clear()
self.score = 0
self.pipe_timer = 0
self.flash_timer = 0
# ─────────────── Main update ───────────────
def update(self, dt):
if self.state == "play":
self.update_play_state(dt)
def update_play_state(self, dt):
keys = pygame.key.get_pressed()
# variable flap height: if space held & bird still rising, add lift
if (keys[pygame.K_SPACE] or keys[pygame.K_UP]) and self.bird.vel < -1:
self.bird.vel += -0.15 # extra upward acceleration
# update objects
self.bird.update()
for pipe in list(self.pipes):
pipe.update()
if pipe.off_screen():
self.pipes.remove(pipe)
# scoring
if not pipe.passed and pipe.x + pipe.width < self.bird.x:
pipe.passed = True
self.score += 1
for p in list(self.particles):
p.update()
if p.life <= 0:
self.particles.remove(p)
# background scrolling
speed, spawn_interval, _ = self.current_difficulty()
self.clouds.update(speed)
self.buildings.update(speed * 1.4)
# spawn pipes
self.pipe_timer += dt
if self.pipe_timer > spawn_interval:
self.pipe_timer = 0
gap_y = random.randint(120, HEIGHT - 120)
_, _, gap_h = self.current_difficulty()
oscillate = random.random() < 0.4
self.pipes.append(
Pipe(WIDTH + 10, gap_y, gap_h, speed, oscillate=oscillate))
# collision
if self.bird.y > HEIGHT or self.bird.y < 0:
self.trigger_game_over()
else:
for pipe in self.pipes:
if pipe.collides(self.bird):
self.trigger_game_over()
break
def trigger_game_over(self):
self.flash_timer = FLASH_TIME
self.state = "gameover"
if self.score > self.high_score:
self.high_score = self.score
save_high_score(self.high_score)
# ─────────────── Drawing ───────────────
def draw(self, surface):
# sky gradient
draw_vertical_gradient(surface, SKY_TOP, SKY_BOTTOM)
# backgrounds
self.clouds.draw(surface)
self.buildings.draw(surface)
# gameplay things
if self.state in ("play", "pause", "gameover"):
for pipe in self.pipes:
pipe.draw(surface)
for p in self.particles:
p.draw(surface)
self.bird.draw(surface)
# score
score_surf = font_big.render(str(self.score), True, WHITE)
surface.blit(
score_surf,
score_surf.get_rect(center=(WIDTH // 2, 50)),
)
# overlays
if self.state == "title":
self.draw_title(surface)
elif self.state == "pause":
self.draw_pause(surface)
elif self.state == "gameover":
self.draw_gameover(surface)
# flash effect
if self.flash_timer > 0:
flash_surface = pygame.Surface((WIDTH, HEIGHT))
flash_surface.fill(WHITE)
alpha = int(255 * (self.flash_timer / FLASH_TIME))
flash_surface.set_alpha(alpha)
surface.blit(flash_surface, (0, 0))
self.flash_timer -= 1
def draw_title(self, surface):
title = font_big.render("FLAPPY CLONE", True, WHITE)
instr = font_med.render("Press SPACE to start", True, WHITE)
hs = font_small.render(f"High Score : {self.high_score}", True, WHITE)
surface.blit(title, title.get_rect(center=(WIDTH // 2, HEIGHT // 3)))
surface.blit(instr,
instr.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 40)))
surface.blit(hs, hs.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 80)))
def draw_pause(self, surface):
pause = font_big.render("PAUSED", True, WHITE)
surface.blit(pause, pause.get_rect(center=(WIDTH // 2, HEIGHT // 2)))
def draw_gameover(self, surface):
over = font_big.render("GAME OVER", True, WHITE)
score_txt = font_med.render(f"Score : {self.score}", True, WHITE)
high_txt = font_med.render(f"High : {self.high_score}", True, WHITE)
retry = font_small.render("Press SPACE to retry", True, WHITE)
surface.blit(over, over.get_rect(center=(WIDTH // 2, HEIGHT // 3)))
surface.blit(score_txt,
score_txt.get_rect(center=(WIDTH // 2, HEIGHT // 2)))
surface.blit(high_txt,
high_txt.get_rect(center=(WIDTH // 2,
HEIGHT // 2 + 40)))
surface.blit(retry,
retry.get_rect(center=(WIDTH // 2,
HEIGHT // 2 + 90)))
# Medal (optional)
medal, color = None, None
if self.score >= 40:
medal, color = "GOLD", GOLD
elif self.score >= 25:
medal, color = "SILVER", SILVER
elif self.score >= 10:
medal, color = "BRONZE", BRONZE
if medal:
medal_txt = font_med.render(medal, True, color)
surface.blit(medal_txt,
medal_txt.get_rect(center=(WIDTH // 2,
HEIGHT // 2 + 140)))
# ─────────────── Input handling ───────────────
def handle_event(self, event):
if event.type == pygame.KEYDOWN:
if self.state == "title":
if event.key in (pygame.K_SPACE, pygame.K_UP):
self.reset_gameplay()
self.state = "play"
elif self.state == "play":
if event.key in (pygame.K_SPACE, pygame.K_UP):
self.bird.flap()
self.spawn_particles()
elif event.key == pygame.K_p:
self.state = "pause"
elif self.state == "pause":
if event.key == pygame.K_p:
self.state = "play"
elif self.state == "gameover":
if event.key in (pygame.K_SPACE, pygame.K_UP):
self.reset_gameplay()
self.state = "play"
def spawn_particles(self):
for _ in range(PARTICLE_COUNT):
self.particles.append(Particle(self.bird.x, self.bird.y))
# ─────────────── Game loop helpers ───────────────
def run(self):
running = True
while running:
dt = clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
self.handle_event(event)
if self.state != "pause":
self.update(dt)
self.draw(screen)
pygame.display.flip()
pygame.quit()
sys.exit()
# ──────────────────────────────────────────────────────────────────────────────
# MAIN
# ──────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
Game().run()
Highlights of what’s inside:
• Title, Play, Pause, and Game‑Over screens with high‑score persistence
• Bird built from circles/triangles/ellipses + simple wing‑flap animation
• Fully procedural background with parallax scrolling clouds & buildings
• Pipes with random gap size, optional vertical sine‑wave movement, speed & gap shrinking as score rises
• Smooth gravity, variable flap lift while holding Space, and a small particle puff each flap
• Flash overlay on collision, medal text on Game‑Over, and clean OOP structure (Bird, Pipe, Particle, BackgroundLayer, Game)
Enjoy hacking and extending it further—no external assets required! 🎮