Untitled
import pygame import random import sys # Initialize pygame pygame.init() # Game constants SCREEN_WIDTH = 400 SCREEN_HEIGHT = 600 BIRD_WIDTH = 40 BIRD_HEIGHT = 40 PIPE_WIDTH = 60 PIPE_GAP = 150 PIPE_VELOCITY = 3 GRAVITY = 0.5 JUMP_VELOCITY = -10 # Set up the display screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Flappy Bird") # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # Font font = pygame.font.SysFont("Arial", 30) # Bird class class Bird: def __init__(self): self.x = SCREEN_WIDTH // 4 self.y = SCREEN_HEIGHT // 2 self.velocity = 0 def jump(self): self.velocity = JUMP_VELOCITY def move(self): self.velocity += GRAVITY self.y += self.velocity def draw(self): pygame.draw.rect(screen, BLUE, (self.x, self.y, BIRD_WIDTH, BIRD_HEIGHT)) # Pipe class class Pipe: def __init__(self): self.x = SCREEN_WIDTH self.height = random.randint(100, SCREEN_HEIGHT - PIPE_GAP - 100) self.top = pygame.Rect(self.x, 0, PIPE_WIDTH, self.height) self.bottom = pygame.Rect(self.x, self.height + PIPE_GAP, PIPE_WIDTH, SCREEN_HEIGHT - self.height - PIPE_GAP) def move(self): self.x -= PIPE_VELOCITY self.top.x = self.x self.bottom.x = self.x def draw(self): pygame.draw.rect(screen, GREEN, self.top) pygame.draw.rect(screen, GREEN, self.bottom) def off_screen(self): return self.x + PIPE_WIDTH < 0 # Main game function def game(): bird = Bird() pipes = [Pipe()] clock = pygame.time.Clock() score = 0 running = True while running: screen.fill(WHITE) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: bird.jump() bird.move() bird.draw() # Move pipes for pipe in pipes[:]: pipe.move() pipe.draw() if pipe.off_screen(): pipes.remove(pipe) pipes.append(Pipe()) score += 1 # Check for collisions if bird.y > SCREEN_HEIGHT - BIRD_HEIGHT or bird.y < 0: running = False for pipe in pipes: if bird.x + BIRD_WIDTH > pipe.x and bird.x < pipe.x + PIPE_WIDTH: if bird.y < pipe.height or bird.y + BIRD_HEIGHT > pipe.height + PIPE_GAP: running = False # Draw the score score_text = font.render(f"Score: {score}", True, BLACK) screen.blit(score_text, (10, 10)) # Update the display pygame.display.update() # Frame rate clock.tick(60) pygame.quit() sys.exit() # Run the game if __name__ == "__main__": game()
Leave a Comment