Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.4 kB
2
Indexable
import pygame
import sys
import random

# Initialize Pygame
pygame.init()

# Constants
WIDTH, HEIGHT = 288, 512
BIRD_WIDTH, BIRD_HEIGHT = 34, 24
PIPE_WIDTH = 52
PIPE_GAP = 100
GRAVITY = 0.25
BIRD_JUMP = 4.5

# Colors
WHITE = (255, 255, 255)

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

# Load assets
bg = pygame.image.load("background.png")
bird_img = pygame.image.load("bird.png")
pipe_img = pygame.image.load("pipe.png")

# Bird class
class Bird:
    def __init__(self):
        self.x = 50
        self.y = HEIGHT // 2
        self.vel_y = 0
        self.image = bird_img
        self.rect = bird_img.get_rect()

    def jump(self):
        self.vel_y = -BIRD_JUMP

    def move(self):
        self.vel_y += GRAVITY
        self.y += self.vel_y

    def draw(self):
        screen.blit(self.image, (self.x, self.y))
        self.rect.topleft = (self.x, self.y)

# Pipe class
class Pipe:
    def __init__(self, x):
        self.x = x
        self.height = random.randint(100, 300)
        self.image = pipe_img
        self.rect = pipe_img.get_rect()

    def move(self):
        self.x -= 2

    def draw(self):
        screen.blit(self.image, (self.x, 0), (0, 0, PIPE_WIDTH, self.height))
        screen.blit(self.image, (self.x, self.height + PIPE_GAP), (0, 320 - self.height, PIPE_WIDTH, self.height))
        self.rect.topleft = (self.x, 0)

# Game variables
bird = Bird()
pipes = [Pipe(WIDTH + i * 200) for i in range(2)]
score = 0

# Main game loop
while True:
    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.jump()

    bird.move()

    # Collision detection
    if bird.rect.colliderect(pipes[0].rect) or bird.rect.colliderect(pipes[1].rect) or bird.y >= HEIGHT:
        print(f"Game Over! Score: {score}")
        pygame.quit()
        sys.exit()

    # Update pipes
    for pipe in pipes:
        pipe.move()
        if pipe.x < -PIPE_WIDTH:
            pipe.x = WIDTH
            pipe.height = random.randint(100, 300)
            score += 1

    # Draw everything
    screen.blit(bg, (0, 0))
    bird.draw()
    for pipe in pipes:
        pipe.draw()

    pygame.display.update()
    pygame.time.delay(20)