import pygame
import random
import sys

# 初始化pygame
pygame.init()

# 窗口尺寸
WIDTH, HEIGHT = 480, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flight Dodge")

# 颜色常量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 50, 50)
BLUE = (50, 120, 255)
YELLOW = (255, 220, 0)
GRAY = (80, 80, 80)

clock = pygame.time.Clock()
FPS = 60

# 重点！用 None 内置默认字体，不调用SysFont，不会触发你的bug
font = pygame.font.Font(None, 36)
small_font = pygame.font.Font(None, 24)


class Player:
    def __init__(self):
        self.w = 50
        self.h = 60
        self.x = WIDTH // 2 - self.w // 2
        self.y = HEIGHT - 100
        self.speed = 7

    def move(self, dx):
        self.x += dx
        # 边界限制
        if self.x < 0:
            self.x = 0
        if self.x + self.w > WIDTH:
            self.x = WIDTH - self.w

    def draw(self):
        # 三角形飞机
        pygame.draw.polygon(screen, BLUE, [
            (self.x + self.w // 2, self.y),
            (self.x, self.y + self.h),
            (self.x + self.w, self.y + self.h)
        ])

    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.w, self.h)


class Enemy:
    def __init__(self):
        self.w = random.randint(30, 60)
        self.h = random.randint(30, 60)
        self.x = random.randint(0, WIDTH - self.w)
        self.y = -self.h
        self.speed = random.randint(4, 8)

    def update(self):
        self.y += self.speed

    def draw(self):
        pygame.draw.rect(screen, RED, (self.x, self.y, self.w, self.h))

    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.w, self.h)


def draw_text(text, x, y, color=WHITE, f=font):
    surf = f.render(text, True, color)
    screen.blit(surf, (x, y))


def main():
    player = Player()
    enemies = []
    score = 0
    game_over = False
    running = True

    spawn_timer = 0
    spawn_interval = 40

    while running:
        screen.fill(BLACK)
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if game_over:
                    if event.key == pygame.K_r:
                        # 重置游戏
                        player = Player()
                        enemies = []
                        score = 0
                        game_over = False
                        spawn_timer = 0
                        spawn_interval = 40
                    if event.key == pygame.K_ESCAPE:
                        running = False

        if not game_over:
            # 仅左右方向键控制
            keys = pygame.key.get_pressed()
            if keys[pygame.K_LEFT]:
                player.move(-player.speed)
            if keys[pygame.K_RIGHT]:
                player.move(player.speed)

            # 生成障碍物
            spawn_timer += 1
            if spawn_timer >= spawn_interval:
                enemies.append(Enemy())
                spawn_timer = 0
                if spawn_interval > 15:
                    spawn_interval -= 0.1

            # 更新障碍物
            for e in enemies[:]:
                e.update()
                if e.y > HEIGHT:
                    enemies.remove(e)
                    score += 1

            # 碰撞判断
            p_rect = player.get_rect()
            for e in enemies:
                if p_rect.colliderect(e.get_rect()):
                    game_over = True
                    break

            player.draw()
            for e in enemies:
                e.draw()
            draw_text(f"Score: {score}", 10, 10, YELLOW, small_font)

        else:
            draw_text("GAME OVER!", WIDTH//2 - 90, HEIGHT//2 - 60, RED, font)
            draw_text(f"Final Score: {score}", WIDTH//2 - 100, HEIGHT//2, WHITE, font)
            draw_text("R = Restart | ESC = Quit", WIDTH//2 - 160, HEIGHT//2 + 60, GRAY, small_font)

        pygame.display.flip()

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()
