import pygame
import sys
import math
import random

pygame.init()
pygame.mixer.init()

WIDTH, HEIGHT = 900, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("飞行模拟 · 多视角版")
clock = pygame.time.Clock()

# ★ 中文显示：指定具体字体文件，避免 SysFont 扫描崩溃
def load_font(size):
    candidates = [
        "C:/Windows/Fonts/simhei.ttf",
        "C:/Windows/Fonts/msyh.ttc",
        "C:/Windows/Fonts/simsun.ttc",
        "/System/Library/Fonts/PingFang.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
    ]
    for path in candidates:
        try:
            return pygame.font.Font(path, size)
        except Exception:
            continue
    return pygame.font.Font(None, size)

font = load_font(22)
big_font = load_font(44)

WHITE = (255, 255, 255)
SKY_HI = (30, 90, 180)
SKY_LO = (150, 210, 255)
GREEN = (60, 170, 80)
GRAY = (150, 150, 150)
RED = (220, 50, 50)
YELLOW = (255, 220, 80)

VIEWS = ["俯视视角", "第一人称", "仪表盘"]
view_index = 0

# ---------- 音效 ----------
def try_make_sound(freq, dur):
    try:
        import array
        sr = 44100
        n = int(sr * dur)
        samples = array.array('h',
            [int(32767 * 0.3 * math.sin(2 * math.pi * freq * (i / sr))) for i in range(n)])
        return pygame.mixer.Sound(buffer=samples.tobytes())
    except Exception:
        return None

snd_shoot = try_make_sound(660, 0.08)
snd_hit = try_make_sound(150, 0.25)
snd_ok = try_make_sound(880, 0.2)

def play(s):
    if s:
        try:
            s.play()
        except Exception:
            pass

# ---------- 飞机 ----------
class Plane:
    def __init__(self):
        self.reset()

    def reset(self):
        self.x = WIDTH / 2
        self.y = HEIGHT / 2
        self.altitude = 300
        self.speed = 200
        self.heading = 0          # 度，0=朝北(上)
        self.pitch = 0
        self.roll = 0
        self.fuel = 100
        self.score = 0
        self.time_left = 90
        self.bullets = 20
        self.alive = True
        self.msg = ""
        self.msg_color = WHITE
        self.landed = False

    def update(self, keys):
        if not self.alive or self.landed:
            return
        self.time_left -= 1 / 60

        # ---- WASD：W/S 俯仰，A/D 转向；同时方向键也可用 ----
        if keys[pygame.K_w] or keys[pygame.K_UP]:
            self.pitch = min(self.pitch + 2, 25)
        elif keys[pygame.K_s] or keys[pygame.K_DOWN]:
            self.pitch = max(self.pitch - 2, -25)
        else:
            self.pitch *= 0.9

        if keys[pygame.K_a] or keys[pygame.K_LEFT]:
            self.heading -= 3
            self.roll = max(self.roll - 4, -30)
        elif keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            self.heading += 3
            self.roll = min(self.roll + 4, 30)
        else:
            self.roll *= 0.9

        if keys[pygame.K_SPACE]:
            self.speed = min(self.speed + 3, 500)
            self.fuel -= 0.15
        else:
            self.speed = max(self.speed - 1, 100)
        self.fuel -= 0.03

        climb = self.pitch * (self.speed / 200) * 2
        self.altitude += climb - 1.5
        self.altitude = max(0, min(self.altitude, 2000))

        # 按航向移动（俯视图中用得上）
        rad = math.radians(self.heading)
        move = self.speed / 40
        self.x += math.sin(rad) * move
        self.y -= math.cos(rad) * move
        self.x %= WIDTH
        self.y = max(20, min(HEIGHT - 20, self.y))

plane = Plane()

clouds = [[random.randint(0, WIDTH), random.randint(0, HEIGHT // 2), random.randint(1, 3)]
          for _ in range(12)]
enemies = [[random.randint(100, WIDTH - 100), random.randint(50, 250), random.randint(1, 4)]
           for _ in range(5)]
bullets = []
explosions = []

# ================= 视角 1：俯视 =================
def view_topdown():
    # 地面底
    screen.fill((90, 160, 90))
    # 网格随飞机位置滚动
    ox = int(plane.x) % 60
    oy = int(plane.y) % 60
    for gx in range(-60, WIDTH + 60, 60):
        pygame.draw.line(screen, (70, 140, 75), (gx - ox, 0), (gx - ox, HEIGHT))
    for gy in range(-60, HEIGHT + 60, 60):
        pygame.draw.line(screen, (70, 140, 75), (0, gy - oy), (WIDTH, gy - oy))

    # 云
    for c in clouds:
        pygame.draw.circle(screen, (230, 235, 240), (c[0], c[1]), 22)

    # 敌机（相对飞机位置）
    for e in enemies:
        ex = e[0] - plane.x + WIDTH / 2
        ey = e[1] - plane.y + HEIGHT / 2
        if -40 < ex < WIDTH + 40 and -40 < ey < HEIGHT + 40:
            pygame.draw.polygon(screen, (200, 60, 60), [
                (ex, ey + 10), (ex - 16, ey - 10), (ex + 16, ey - 10)])

    # 子弹
    for b in bullets:
        bx = b[0] - plane.x + WIDTH / 2
        by = b[1] - plane.y + HEIGHT / 2
        if 0 < bx < WIDTH and 0 < by < HEIGHT:
            pygame.draw.circle(screen, YELLOW, (int(bx), int(by)), 3)

    # 玩家飞机（中心）
    surf = pygame.Surface((70, 46), pygame.SRCALPHA)
    pygame.draw.polygon(surf, (50, 55, 65), [(35, 0), (0, 42), (70, 42)])
    pygame.draw.polygon(surf, (90, 95, 110), [(35, 8), (12, 40), (58, 40)])
    rotated = pygame.transform.rotate(surf, -plane.heading)
    rect = rotated.get_rect(center=(WIDTH / 2, HEIGHT / 2))
    screen.blit(rotated, rect)


# ================= 视角 2：第一人称 =================
def view_first_person():
    t = min(plane.altitude / 1000, 1)
    top = tuple(int(SKY_HI[i] * (1 - t) + 20 * t) for i in range(3))
    bot = tuple(int(SKY_LO[i] * (1 - t) + 120 * t) for i in range(3))
    horizon = HEIGHT // 2 - int(plane.pitch * 4)
    for y in range(HEIGHT):
        r = y / HEIGHT
        c = tuple(int(top[i] * (1 - r) + bot[i] * r) for i in range(3))
        pygame.draw.line(screen, c, (0, y), (WIDTH, y))

    if plane.altitude > 1200:
        for _ in range(25):
            pygame.draw.circle(screen, WHITE,
                               (random.randint(0, WIDTH), random.randint(0, horizon)), 1)
    pygame.draw.circle(screen, (255, 240, 180), (WIDTH - 130, horizon - 60), 38)

    # 地面
    pygame.draw.rect(screen, GREEN, (0, horizon, WIDTH, HEIGHT - horizon))
    shift = int(plane.heading) % 60
    for i in range(1, 14):
        yy = horizon + (i ** 2) * 3
        if yy < HEIGHT:
            pygame.draw.line(screen, (50, 140, 65), (0, yy), (WIDTH, yy))
    for i in range(-12, 13):
        x1 = WIDTH / 2 + (i * 40 - shift * 3)
        pygame.draw.line(screen, (50, 140, 65), (WIDTH / 2, horizon), (x1, HEIGHT))

    # 跑道
    rw = 45 + (1 - t) * 130
    pygame.draw.polygon(screen, GRAY, [
        (WIDTH / 2 - 22, horizon), (WIDTH / 2 + 22, horizon),
        (WIDTH / 2 + rw, HEIGHT), (WIDTH / 2 - rw, HEIGHT)])

    # 云
    for c in clouds:
        pygame.draw.circle(screen, WHITE, (c[0] % WIDTH, c[1] % max(1, horizon)), 18)

    # 敌机（第一人称：随航向偏移）
    for e in enemies:
        dx = (e[0] - plane.x)
        if abs(dx) > WIDTH:
            continue
        ex = WIDTH / 2 + dx - math.sin(math.radians(plane.roll)) * 40
        ey = e[1] - plane.altitude * 0.1 + horizon
        if 0 < ex < WIDTH and horizon - 60 < ey < HEIGHT:
            pygame.draw.polygon(screen, (200, 60, 60), [
                (ex, ey + 10), (ex - 18, ey - 10), (ex + 18, ey - 10)])

    # 子弹
    for b in bullets:
        bx = WIDTH / 2 + (b[0] - plane.x) * 0.5
        by = b[1] * 0.6
        if 0 < bx < WIDTH and 0 < by < HEIGHT:
            pygame.draw.circle(screen, YELLOW, (int(bx), int(by)), 3)

    # 机翼（座舱框）
    wing = pygame.Surface((WIDTH, 90), pygame.SRCALPHA)
    pygame.draw.polygon(wing, (45, 50, 60), [
        (0, 20), (WIDTH * 0.3, 45), (WIDTH * 0.7, 45), (WIDTH, 20),
        (WIDTH, 90), (0, 90)])
    rotated = pygame.transform.rotate(wing, plane.roll * 0.5)
    screen.blit(rotated, (0, HEIGHT - 90))


# ================= 视角 3：仪表盘 =================
def view_panel():
    screen.fill((20, 26, 34))
    # 大姿态仪
    cx, cy, r = WIDTH // 2, HEIGHT // 2 + 20, 180
    pygame.draw.circle(screen, (40, 48, 58), (cx, cy), r)
    pygame.draw.circle(screen, WHITE, (cx, cy), r, 3)
    # 地平线随俯仰滚转
    ang = math.radians(plane.roll)
    off = int(plane.pitch * 3)
    sky = pygame.Surface((r * 2, r), pygame.SRCALPHA)
    sky.fill((90, 170, 230))
    grd = pygame.Surface((r * 2, r), pygame.SRCALPHA)
    grd.fill((110, 80, 50))
    sky_rot = pygame.transform.rotate(sky, plane.roll)
    grd_rot = pygame.transform.rotate(grd, plane.roll)
    screen.blit(sky_rot, (cx - r, cy - r - off))
    screen.blit(grd_rot, (cx - r, cy - off))
    pygame.draw.circle(screen, (20, 26, 34), (cx, cy), r - 2)
    pygame.draw.line(screen, YELLOW, (cx - 40, cy), (cx + 40, cy), 3)
    pygame.draw.circle(screen, WHITE, (cx, cy), 4)
    # 刻度
    for a in range(0, 360, 30):
        rad = math.radians(a)
        x1 = cx + math.cos(rad) * (r - 6)
        y1 = cy + math.sin(rad) * (r - 6)
        x2 = cx + math.cos(rad) * r
        y2 = cy + math.sin(rad) * r
        pygame.draw.line(screen, WHITE, (x1, y1), (x2, y2), 2)

    # 左侧数据
    info = [
        f"高度: {int(plane.altitude)} 米",
        f"速度: {int(plane.speed)} km/h",
        f"航向: {int(plane.heading) % 360:03d}",
        f"俯仰: {int(plane.pitch)}",
        f"横滚: {int(plane.roll)}",
        f"得分: {plane.score}",
        f"剩余: {max(0, int(plane.time_left))} 秒",
    ]
    for i, s in enumerate(info):
        screen.blit(font.render(s, True, WHITE), (20, 20 + i * 26))

    # 油量 / 弹药
    pygame.draw.rect(screen, WHITE, (20, 240, 140, 14), 1)
    color = RED if plane.fuel < 20 else WHITE
    pygame.draw.rect(screen, color, (21, 241, int(max(0, plane.fuel) * 1.38), 12))
    screen.blit(font.render(f"油量   弹药:{plane.bullets}", True, WHITE), (20, 260))


# ---------- 通用 HUD ----------
def draw_hud():
    info = [
        f"高度: {int(plane.altitude)} 米",
        f"速度: {int(plane.speed)} km/h",
        f"航向: {int(plane.heading) % 360:03d}",
        f"得分: {plane.score}",
        f"剩余: {max(0, int(plane.time_left))} 秒",
    ]
    for i, s in enumerate(info):
        screen.blit(font.render(s, True, WHITE), (10, 10 + i * 22))

    pygame.draw.rect(screen, WHITE, (10, 135, 110, 10), 1)
    color = RED if plane.fuel < 20 else WHITE
    pygame.draw.rect(screen, color, (11, 136, int(max(0, plane.fuel) * 1.08), 8))
    screen.blit(font.render(f"弹药:{plane.bullets}", True, WHITE), (10, 150))

    # 视角提示
    tip = font.render(f"视角: {VIEWS[view_index]}  (Tab 切换)", True, YELLOW)
    screen.blit(tip, (WIDTH - tip.get_width() - 12, 12))

    # 操作说明
    help1 = font.render("WASD/方向键 移动  空格 加速  F 射击  R 重置", True, (200, 210, 220))
    screen.blit(help1, (WIDTH / 2 - help1.get_width() / 2, HEIGHT - 28))


def draw_center_text(text, color=RED):
    surf = big_font.render(text, True, color)
    screen.blit(surf, (WIDTH / 2 - surf.get_width() / 2, HEIGHT / 2 - 40))


# ---------- 主循环 ----------
running = True
while running:
    clock.tick(60)
    keys = pygame.key.get_pressed()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_TAB:
                view_index = (view_index + 1) % len(VIEWS)
            if event.key == pygame.K_r:
                plane.reset()
                bullets.clear()
                explosions.clear()
            if event.key == pygame.K_f and plane.alive and not plane.landed:
                if plane.bullets > 0:
                    plane.bullets -= 1
                    bullets.append([plane.x, plane.y - 20])
                    play(snd_shoot)

    plane.update(keys)

    # 子弹 / 命中
    for b in bullets[:]:
        b[1] -= 14
        if b[1] < 0:
            bullets.remove(b)
    for e in enemies[:]:
        for b in bullets[:]:
            if abs(e[0] - b[0]) < 18 and abs(e[1] - b[1]) < 18:
                plane.score += 100
                play(snd_hit)
                explosions.append([e[0], e[1], 12])
                if b in bullets:
                    bullets.remove(b)
                if e in enemies:
                    enemies.remove(e)
                break
    while len(enemies) < 5:
        enemies.append([random.randint(100, WIDTH - 100), random.randint(50, 250),
                        random.randint(1, 4)])

    # 撞机
    for e in enemies:
        if abs(e[0] - plane.x) < 26 and abs(e[1] - plane.y) < 26:
            plane.alive = False
            plane.msg = "撞机！按 R 重试"
            plane.msg_color = RED

    # 着陆
    if plane.altitude <= 0 and plane.alive and not plane.landed:
        if plane.speed < 160 and abs(plane.roll) < 8 and abs(plane.pitch) < 8:
            plane.score += max(0, int(plane.time_left)) * 10
            plane.fuel = min(100, plane.fuel + 50)
            plane.landed = True
            plane.msg = "成功降落！按 R 继续"
            plane.msg_color = (80, 220, 120)
            play(snd_ok)
        else:
            plane.alive = False
            plane.msg = "坠机！按 R 重试"
            plane.msg_color = RED
            play(snd_hit)

    if plane.fuel <= 0 and plane.alive:
        plane.alive = False
        plane.msg = "燃油耗尽！按 R 重试"
        plane.msg_color = RED
    if plane.time_left <= 0 and plane.alive and not plane.landed:
        plane.alive = False
        plane.msg = "时间到！按 R 重试"
        plane.msg_color = RED

    # 按视角渲染
    if view_index == 0:
        view_topdown()
    elif view_index == 1:
        view_first_person()
    else:
        view_panel()
    draw_hud()
    if plane.msg:
        draw_center_text(plane.msg, plane.msg_color)

    pygame.display.flip()

pygame.quit()
sys.exit()