import pygame
import random
import sys

# --- 初始化 Pygame ---
pygame.init()

# --- 常量定义 ---
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60

# 颜色定义 (R, G, B)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 100)  # 玩家颜色
RED = (255, 50, 50)    # 敌人颜色
BLUE = (100, 100, 255) # 背景色

# 玩家设置
PLAYER_SIZE = 50
PLAYER_SPEED = 7

# 敌人设置
ENEMY_SIZE = 50
ENEMY_SPEED_BASE = 5
ENEMY_SPAWN_RATE = 30  # 帧数间隔，数值越小生成越快

# --- 设置屏幕 ---
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("飞行躲避游戏")
clock = pygame.time.Clock()
font = pygame.font.SysFont("Arial", 24)
game_over_font = pygame.font.SysFont("Arial", 48)

def draw_text(text, font, color, surface, x, y):
    textobj = font.render(text, True, color)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

def main():
    # 玩家初始位置
    player_x = SCREEN_WIDTH // 2 - PLAYER_SIZE // 2
    player_y = SCREEN_HEIGHT - PLAYER_SIZE - 10
    
    enemies = [] # 存储敌人列表，每个元素是 [x, y]
    score = 0
    frame_count = 0
    game_over = False
    
    # 游戏主循环
    running = True
    while running:
        clock.tick(FPS)
        
        # 1. 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            # 游戏结束后按 R 重启
            if game_over and event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    main() # 递归调用重新开始
                    return

        if not game_over:
            # 2. 玩家移动
            keys = pygame.key.get_pressed()
            if keys[pygame.K_LEFT] and player_x > 0:
                player_x -= PLAYER_SPEED
            if keys[pygame.K_RIGHT] and player_x < SCREEN_WIDTH - PLAYER_SIZE:
                player_x += PLAYER_SPEED

            # 3. 生成敌人
            frame_count += 1
            # 随着分数增加，生成速度略微加快
            current_spawn_rate = max(10, ENEMY_SPAWN_RATE - (score // 500))
            
            if frame_count >= current_spawn_rate:
                e_x = random.randint(0, SCREEN_WIDTH - ENEMY_SIZE)
                e_y = -ENEMY_SIZE
                enemies.append([e_x, e_y])
                frame_count = 0

            # 4. 更新敌人位置
            # 随着分数增加，敌人下落速度略微加快
            current_enemy_speed = ENEMY_SPEED_BASE + (score // 1000)
            
            for enemy in enemies[:]: # 使用切片复制列表以便安全删除
                enemy[1] += current_enemy_speed
                
                # 移除超出屏幕的敌人并加分
                if enemy[1] > SCREEN_HEIGHT:
                    enemies.remove(enemy)
                    score += 10

                # 碰撞检测 (矩形碰撞)
                player_rect = pygame.Rect(player_x, player_y, PLAYER_SIZE, PLAYER_SIZE)
                enemy_rect = pygame.Rect(enemy[0], enemy[1], ENEMY_SIZE, ENEMY_SIZE)
                
                if player_rect.colliderect(enemy_rect):
                    game_over = True

        # 5. 绘图渲染
        screen.fill(BLUE) # 绘制背景

        # 绘制玩家
        pygame.draw.rect(screen, GREEN, (player_x, player_y, PLAYER_SIZE, PLAYER_SIZE))
        
        # 绘制敌人
        for enemy in enemies:
            pygame.draw.rect(screen, RED, (enemy[0], enemy[1], ENEMY_SIZE, ENEMY_SIZE))

        # 绘制 UI
        draw_text(f"Score: {score}", font, WHITE, screen, 10, 10)

        if game_over:
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
            overlay.set_alpha(150)
            overlay.fill(BLACK)
            screen.blit(overlay, (0, 0))
            
            draw_text("GAME OVER", game_over_font, RED, screen, SCREEN_WIDTH//2 - 140, SCREEN_HEIGHT//2 - 50)
            draw_text(f"Final Score: {score}", font, WHITE, screen, SCREEN_WIDTH//2 - 80, SCREEN_HEIGHT//2 + 10)
            draw_text("Press 'R' to Restart", font, WHITE, screen, SCREEN_WIDTH//2 - 90, SCREEN_HEIGHT//2 + 50)

        pygame.display.flip()

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()