Untitled

 avatar
unknown
plain_text
a year ago
2.3 kB
3
Indexable
import pygame
import sys
import random

pygame.init()

# Constants
WIDTH, HEIGHT = 600, 400
GRAVITY = 0.25
BIRD_SPEED = 5
JUMP_HEIGHT = -8
PIPE_WIDTH = 50
PIPE_GAP = 150

# Colors
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)

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

# Load images
bird_image = pygame.image.load("bird.png")
pipe_image = pygame.image.load("pipe.png")

# Bird class
class Bird:
    def __init__(self):
        self.x = 100
        self.y = HEIGHT // 2
        self.velocity = 0

    def jump(self):
        self.velocity = JUMP_HEIGHT

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

    def draw(self):
        screen.blit(bird_image, (self.x, self.y))

# Pipe class
class Pipe:
    def __init__(self, x):
        self.x = x
        self.height = random.randint(50, HEIGHT - PIPE_GAP - 50)

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

    def draw(self):
        screen.blit(pipe_image, (self.x, 0), (0, 0, PIPE_WIDTH, self.height))
        screen.blit(pipe_image, (self.x, self.height + PIPE_GAP), (0, self.height + PIPE_GAP, PIPE_WIDTH, HEIGHT))

def main():
    bird = Bird()
    pipes = [Pipe(WIDTH + i * 200) for i in range(3)]
    clock = pygame.time.Clock()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                bird.jump()

        bird.move()
        for pipe in pipes:
            pipe.move()

        if pipes[0].x < -PIPE_WIDTH:
            pipes.pop(0)
            pipes.append(Pipe(WIDTH))

        if bird.y > HEIGHT or bird.y < 0:
            pygame.quit()
            sys.exit()

        for pipe in pipes:
            if pipe.x < bird.x + 50 < pipe.x + PIPE_WIDTH:
                if bird.y < pipe.height or bird.y + 50 > pipe.height + PIPE_GAP:
                    pygame.quit()
                    sys.exit()

        screen.fill(WHITE)
        bird.draw()
        for pipe in pipes:
            pipe.draw()

        pygame.display.flip()
        clock.tick(30)

if __name__ == "__main__":
    main()

Editor is loading...
Leave a Comment