Untitled
unknown
plain_text
2 years ago
3.2 kB
2
Indexable
import pygame import sys import random # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 400, 600 GROUND_HEIGHT = 50 FPS = 60 GRAVITY = 0.25 JUMP = -5 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Create the game window screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Flappy Bird") # Load images bird_img = pygame.image.load("bird.png") background_img = pygame.image.load("background.png") pipe_img = pygame.image.load("pipe.png") ground_img = pygame.image.load("ground.png") # Scale images bird_img = pygame.transform.scale(bird_img, (50, 50)) pipe_img = pygame.transform.scale(pipe_img, (50, 300)) ground_img = pygame.transform.scale(ground_img, (WIDTH, GROUND_HEIGHT)) # Bird class class Bird(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = bird_img self.rect = self.image.get_rect() self.rect.center = (100, HEIGHT // 2) self.velocity = 0 def update(self): self.velocity += GRAVITY self.rect.y += self.velocity def jump(self): self.velocity = JUMP # Pipe class class Pipe(pygame.sprite.Sprite): def __init__(self, x): super().__init__() self.image = pipe_img self.rect = self.image.get_rect() self.rect.height = random.randint(100, 400) self.rect.width = 50 self.rect.x = x self.rect.y = 0 def update(self): self.rect.x -= 5 if self.rect.right < 0: self.rect.x = WIDTH self.rect.height = random.randint(100, 400) # Ground class class Ground(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = ground_img self.rect = self.image.get_rect() self.rect.y = HEIGHT - GROUND_HEIGHT def update(self): self.rect.x -= 5 if self.rect.right < 0: self.rect.x = WIDTH # Create sprite groups all_sprites = pygame.sprite.Group() pipes = pygame.sprite.Group() # Create game objects bird = Bird() ground = Ground() all_sprites.add(bird, ground) # Game loop clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: bird.jump() # Update all_sprites.update() pipes.update() # Check for collisions if pygame.sprite.spritecollide(bird, pipes, False): pygame.quit() sys.exit() # Create new pipes if random.randint(1, 100) < 5: pipe = Pipe(WIDTH) pipes.add(pipe) all_sprites.add(pipe) # Remove off-screen pipes for pipe in pipes.copy(): if pipe.rect.right < 0: pipes.remove(pipe) all_sprites.remove(pipe) # Draw screen.blit(background_img, (0, 0)) all_sprites.draw(screen) pipes.draw(screen) # Refresh screen pygame.display.flip() # Cap the frame rate clock.tick(FPS)
Editor is loading...
Leave a Comment