Untitled
unknown
plain_text
a year ago
2.3 kB
2
Indexable
import pygame import random # Initialize pygame pygame.init() # Constants WIDTH, HEIGHT = 500, 600 WHITE = (255, 255, 255) BLACK = (0, 0, 0) FPS = 60 GRAVITY = 0.25 BIRD_JUMP = -7 PIPE_SPEED = 3 # Create game window screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Flappy Bird") # Load images bird_img = pygame.image.load('bird.png').convert_alpha() pipe_img = pygame.image.load('pipe.png').convert_alpha() # Bird class class Bird(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = bird_img self.rect = self.image.get_rect(center=(100, HEIGHT // 2)) self.velocity = 0 def update(self): self.velocity += GRAVITY self.rect.y += self.velocity def jump(self): self.velocity = BIRD_JUMP def is_off_screen(self): return self.rect.top > HEIGHT or self.rect.bottom < 0 # Pipe class class Pipe(pygame.sprite.Sprite): def __init__(self, inverted, xpos, ysize): super().__init__() self.image = pipe_img self.image = pygame.transform.scale(self.image, (80, 600)) self.rect = self.image.get_rect(topleft=(xpos, -ysize) if inverted else (xpos, HEIGHT - ysize)) self.inverted = inverted def update(self): self.rect.x -= PIPE_SPEED # Main function def main(): clock = pygame.time.Clock() bird_group = pygame.sprite.GroupSingle(Bird()) pipe_group = pygame.sprite.Group() spawn_pipe_event = pygame.USEREVENT + 1 pygame.time.set_timer(spawn_pipe_event, 1500) running = True while running: 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_group.sprite.jump() if event.type == spawn_pipe_event: pipe_group.add(Pipe(False, WIDTH, random.randint(200, 400))) pipe_group.add(Pipe(True, WIDTH, random.randint(200, 400))) screen.fill(BLACK) bird_group.update() bird_group.draw(screen) pipe_group.update() pipe_group.draw(screen) pygame.display.flip() clock.tick(FPS) if __name__ == "__main__": main()
Editor is loading...
Leave a Comment