import pygame
import random

# 初始化pygame
pygame.init()

# 窗口设置
WIDTH, HEIGHT = 480, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("飞行躲避小游戏")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 120, 255)

# 玩家飞机
player_w = 60
player_h = 70
player_x = WIDTH // 2 - player_w // 2
player_y = HEIGHT - player_h - 30
player_speed = 7

# 障碍物（陨石）
obstacle_list = []
obstacle_speed = 4
obstacle_w = 50
obstacle_h = 50
obstacle_spawn_rate = 40

# 分数、时钟
score = 0
clock = pygame.time.Clock()
# 字体兼容兜底
try:
    font = pygame.font.SysFont("simhei", 32)
    game_over_font = pygame.font.SysFont("simhei", 48)
except:
    font = pygame.font.Font(None,32)
    game_over_font = pygame.font.Font(None,48)

# 生成障碍物
def create_obstacle():
    x = random.randint(0, WIDTH - obstacle_w)
    y = -obstacle_h
    obstacle_list.append([x, y])

# 碰撞检测
def check_collision(px, py, pw, ph, ox, oy, ow, oh):
    if px < ox + ow and px + pw > ox and py < oy + oh and py + ph > oy:
        return True
    return False

# 游戏状态
running = True
frame_count = 0
game_over = False

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

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if game_over and event.key == pygame.K_SPACE:
                # 重置游戏
                player_x = WIDTH // 2 - player_w // 2
                player_y = HEIGHT - player_h - 30
                obstacle_list.clear()
                score = 0
                frame_count = 0
                game_over = False

    if not game_over:
        # 玩家移动
        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 < WIDTH - player_w:
            player_x += player_speed
        if keys[pygame.K_UP] and player_y > 0:
            player_y -= player_speed
        if keys[pygame.K_DOWN] and player_y < HEIGHT - player_h:
            player_y += player_speed

        # 生成障碍物
        frame_count += 1
        if frame_count % obstacle_spawn_rate == 0:
            create_obstacle()

        # 更新障碍物
        for obs in obstacle_list[:]:
            obs[1] += obstacle_speed
            # 出屏幕加分并删除
            if obs[1] > HEIGHT:
                obstacle_list.remove(obs)
                score += 1
            # 碰撞判断
            if check_collision(player_x, player_y, player_w, player_h, obs[0], obs[1], obstacle_w, obstacle_h):
                game_over = True

        # 绘制玩家飞机
        pygame.draw.rect(screen, BLUE, (player_x, player_y, player_w, player_h))
        # 绘制障碍物
        for obs in obstacle_list:
            pygame.draw.rect(screen, RED, (obs[0], obs[1], obstacle_w, obstacle_h))

        # 绘制分数
        score_text = font.render(f"分数：{score}", True, WHITE)
        screen.blit(score_text, (10, 10))

    else:
        # 游戏结束界面
        over_text = game_over_font.render("游戏结束!", True, RED)
        tip_text = font.render("按空格重新开始", True, WHITE)
        final_score = font.render(f"最终分数: {score}", True, WHITE)
        screen.blit(over_text, (WIDTH//2 - 120, HEIGHT//2 - 80))
        screen.blit(final_score, (WIDTH//2 - 90, HEIGHT//2 - 20))
        screen.blit(tip_text, (WIDTH//2 - 130, HEIGHT//2 + 30))

    pygame.display.update()

pygame.quit()
