Skip to content

Feufeu #7

@yuzunehsy10

Description

@yuzunehsy10

import pygame
import random

Initialize Pygame

pygame.init()

Game Constants

WIDTH, HEIGHT = 400, 600
BIRD_X = 50
BIRD_WIDTH, BIRD_HEIGHT = 40, 30
PIPE_WIDTH = 70
PIPE_GAP = 150 # Space between top and bottom pipes
GRAVITY = 0.5
JUMP_STRENGTH = -10
PIPE_SPEED = 3
GROUND_HEIGHT = 50
FONT = pygame.font.Font(None, 36)

Colors

WHITE = (255, 255, 255)
BLUE = (135, 206, 250)
GREEN = (34, 139, 34)

Create Window

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird Clone")

Bird setup

bird = pygame.Rect(BIRD_X, HEIGHT // 2, BIRD_WIDTH, BIRD_HEIGHT)
bird_velocity = 0

Pipe setup

pipes = []
score = 0
pipe_timer = 0 # Timer for adding new pipes

Game Loop

running = True
clock = pygame.time.Clock()

while running:
screen.fill(BLUE) # Background color

# Event Handling
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            bird_velocity = JUMP_STRENGTH  # Jump when space is pressed

# Bird Physics
bird_velocity += GRAVITY  # Apply gravity
bird.y += bird_velocity  # Move bird

# Ground Collision
if bird.y >= HEIGHT - GROUND_HEIGHT - bird.height:
    bird.y = HEIGHT - GROUND_HEIGHT - bird.height
    running = False  # End game when hitting the ground

# Pipe Movement
pipes = [pipe for pipe in pipes if pipe.x > -PIPE_WIDTH]  # Remove off-screen pipes
for pipe in pipes:
    pipe.x -= PIPE_SPEED  # Move pipes left

# Generate New Pipes
pipe_timer += 1
if pipe_timer > 90:  # Add a new pipe every 90 frames
    pipe_timer = 0
    gap_y = random.randint(100, HEIGHT - PIPE_GAP - 100)  # Random gap position
    pipes.append(pygame.Rect(WIDTH, 0, PIPE_WIDTH, gap_y))  # Top pipe
    pipes.append(pygame.Rect(WIDTH, gap_y + PIPE_GAP, PIPE_WIDTH, HEIGHT - gap_y - PIPE_GAP - GROUND_HEIGHT))  # Bottom pipe

# Collision Detection
for pipe in pipes:
    if bird.colliderect(pipe):
        running = False  # End game if bird hits a pipe

# Scoring
for pipe in pipes:
    if pipe.x == BIRD_X and pipe.y == 0:  # Count only top pipes
        score += 1

# Draw Everything
pygame.draw.rect(screen, WHITE, bird)  # Bird
for pipe in pipes:
    pygame.draw.rect(screen, GREEN, pipe)  # Pipes
pygame.draw.rect(screen, GREEN, (0, HEIGHT - GROUND_HEIGHT, WIDTH, GROUND_HEIGHT))  # Ground

# Draw Score
score_text = FONT.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, 10))

pygame.display.update()
clock.tick(30)  # 30 FPS

pygame.quit()
print(f"Game Over! Final Score: {score}")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions