Untitled
import pygame import random # Define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) # Game settings SCREEN_WIDTH = 288 SCREEN_HEIGHT = 512 BIRD_WIDTH = 34 BIRD_HEIGHT = 24 PIPE_WIDTH = 52 PIPE_GAP_SIZE = 100 GAME_SPEED = 5 class Bird: def __init__(self): self.x = int(SCREEN_WIDTH / 5) self.y = int(SCREEN_HEIGHT / 2) self.velocity = 0 self.gravity = 0.25 self.lift = -7 def jump(self): self.velocity += self.lift def update(self): self.velocity += self.gravity self.y += self.velocity # Keep bird within screen boundaries if self.y + BIRD_HEIGHT > SCREEN_HEIGHT: self.y = SCREEN_HEIGHT - BIRD_HEIGHT def draw(self, screen): pygame.draw.rect(screen, RED, (self.x, self.y, BIRD_WIDTH, BIRD_HEIGHT)) class Pipe: def __init__(self, x): self.x = x self.height = random.randint(50, 450) self.top = 0 self.bottom = 0 self.passed = False def update(self): self.x -= GAME_SPEED def draw(self, screen): self.top = self.height - PIPE_GAP_SIZE self.bottom = self.height + PIPE_GAP_SIZE pygame.draw.rect(screen, GREEN, (self.x, 0, PIPE_WIDTH, self.top)) pygame.draw.rect(screen, GREEN, (self.x, self.bottom, PIPE_WIDTH, SCREEN_HEIGHT)) def check_collision(bird, pipes): for pipe in pipes: if (bird.x + BIRD_WIDTH > pipe.x and bird.x < pipe.x + PIPE_WIDTH) and ( bird.y < pipe.top or bird.y + BIRD_HEIGHT > pipe.bottom ): return True return False def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Flappy Bird") clock = pygame.time.Clock() bird = Bird() pipes = [Pipe(SCREEN_WIDTH)] score = 0 running = True while running: 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() # Update game objects bird.update() for pipe in pipes: pipe.update() if pipe.x + PIPE_WIDTH < 0: pipes.remove(pipe) if not pipe.passed and pipe.x < bird.x: pipe.passed = True score += 1 if 0 < len(pipes) < 5: pipes.append(Pipe(SCREEN_WIDTH + 300)) # Check for collisions if check_collision(bird, pipes) or bird.y + BIRD_HEIGHT < 0: running = False # Draw everything screen.fill(WHITE) for pipe in pipes: pipe.draw(screen) bird.draw(screen) font = pygame.font.SysFont('sans-serif', 30) text = font.render(f"Score: {score}", True, BLACK) text_rect = text.get_rect(center=(SCREEN_WIDTH / 2, 50)) screen.blit(text, text_rect) pygame.display.update() clock.tick(60) pygame.quit() if __name__ == "__main__": main()
Leave a Comment