# main.py  —— 用 Pygame 做的飞行模拟器（中文显示）
import pygame
import math
import sys

# 初始化
pygame.init()

# 中文字体（Windows 系统字体，路径通用）
FONT_PATH = "C:/Windows/Fonts/msyh.ttc"   # 微软雅黑
try:
    font_big   = pygame.font.Font(FONT_PATH, 36)
    font_mid   = pygame.font.Font(FONT_PATH, 24)
    font_small = pygame.font.Font(FONT_PATH, 18)
except:
    # 如果找不到字体，用默认（中文可能显示为方块）
    font_big   = pygame.font.SysFont("simhei", 36)
    font_mid   = pygame.font.SysFont("simhei", 24)
    font_small = pygame.font.SysFont("simhei", 18)

# 屏幕
W, H = 1000, 700
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("飞行模拟器 - 中文版")
clock = pygame.time.Clock()

# 颜色
SKY_TOP    = (100, 170, 240)
SKY_BOTTOM = (200, 230, 255)
GROUND     = (60, 120, 60)
WHITE      = (255, 255, 255)
BLACK      = (0, 0, 0)
RED        = (220, 60, 60)
YELLOW     = (255, 220, 80)
GRAY       = (80, 80, 80)

# 飞机状态
plane = {
    "x": 300.0,
    "y": 350.0,
    "speed": 3.0,        # 前进速度
    "angle": 0.0,        # 机头角度（弧度，0 = 朝右）
    "vx": 0.0,
    "vy": 0.0,
}
GRAVITY = 0.15           # 重力
THRUST  = 0.30           # 推力加速度
MAX_SPEED = 12.0
MIN_SPEED = 1.0

# 云朵（背景装饰）
clouds = [{"x": 100 + i*180, "y": 80 + (i % 3)*60} for i in range(8)]

# 相机偏移（让飞机居中）
def world_to_screen(wx, wy):
    return int(wx), int(wy)

# 绘制渐变天空
def draw_sky():
    for y in range(H):
        t = y / H
        r = int(SKY_TOP[0]*(1-t) + SKY_BOTTOM[0]*t)
        g = int(SKY_TOP[1]*(1-t) + SKY_BOTTOM[1]*t)
        b = int(SKY_TOP[2]*(1-t) + SKY_BOTTOM[2]*t)
        pygame.draw.line(screen, (r, g, b), (0, y), (W, y))

# 绘制地面
def draw_ground():
    pygame.draw.rect(screen, GROUND, (0, H-100, W, 100))
    # 地面装饰（跑道）
    pygame.draw.rect(screen, (100, 100, 100), (0, H-80, W, 8))
    for x in range(0, W, 60):
        pygame.draw.rect(screen, WHITE, (x, H-78, 30, 4))

# 绘制云朵
def draw_clouds(offset_x):
    for c in clouds:
        cx = (c["x"] - offset_x * 0.3) % (W + 200) - 100
        cy = c["y"]
        pygame.draw.ellipse(screen, WHITE, (cx, cy, 120, 50))
        pygame.draw.ellipse(screen, WHITE, (cx+30, cy-20, 80, 50))
        pygame.draw.ellipse(screen, WHITE, (cx+60, cy, 90, 45))

# 绘制飞机（用多边形画一个简易飞机）
def draw_plane():
    px, py = plane["x"], plane["y"]
    ang = plane["angle"]
    # 机头方向向量
    cos_a, sin_a = math.cos(ang), math.sin(ang)

    # 机身（长条形）
    body_len, body_w = 50, 14
    p1 = (px + cos_a*body_len/2, py + sin_a*body_len/2)              # 机头
    p2 = (px - cos_a*body_len/2 + sin_a*body_w/2, py - sin_a*body_len/2 - cos_a*body_w/2)
    p3 = (px - cos_a*body_len/2 - sin_a*body_w/2, py - sin_a*body_len/2 + cos_a*body_w/2)
    pygame.draw.polygon(screen, (220, 220, 230), [p1, p2, p3])
    pygame.draw.polygon(screen, GRAY, [p1, p2, p3], 2)

    # 机翼（垂直于机身）
    wing_span = 46
    wing_pos = 0
    wx1 = px + cos_a*wing_pos + sin_a*wing_span/2
    wy1 = py + sin_a*wing_pos - cos_a*wing_span/2
    wx2 = px + cos_a*wing_pos - sin_a*wing_span/2
    wy2 = py + sin_a*wing_pos + cos_a*wing_span/2
    wing_w = 10
    w1 = (wx1 + cos_a*wing_w/2, wy1 + sin_a*wing_w/2)
    w2 = (wx2 + cos_a*wing_w/2, wy2 + sin_a*wing_w/2)
    w3 = (wx2 - cos_a*wing_w/2, wy2 - sin_a*wing_w/2)
    w4 = (wx1 - cos_a*wing_w/2, wy1 - sin_a*wing_w/2)
    pygame.draw.polygon(screen, (150, 180, 220), [w1, w2, w3, w4])
    pygame.draw.polygon(screen, GRAY, [w1, w2, w3, w4], 2)

    # 尾翼
    tail_x = px - cos_a*body_len/2
    tail_y = py - sin_a*body_len/2
    t1 = (tail_x + sin_a*16, tail_y - cos_a*16)
    t2 = (tail_x - sin_a*16, tail_y + cos_a*16)
    t3 = (tail_x + cos_a*14, tail_y + sin_a*14)
    pygame.draw.polygon(screen, (200, 200, 220), [t1, t2, t3])
    pygame.draw.polygon(screen, GRAY, [t1, t2, t3], 2)

    # 螺旋桨（机头前方的小圆 + 线条）
    prop_x = px + cos_a*(body_len/2 + 4)
    prop_y = py + sin_a*(body_len/2 + 4)
    pygame.draw.circle(screen, (60, 60, 60), (int(prop_x), int(prop_y)), 5)
    # 动态旋转线条
    t = pygame.time.get_ticks() / 30
    for i in range(3):
        a = t + i * math.pi * 2 / 3
        lx = prop_x + math.cos(a)*10
        ly = prop_y + math.sin(a)*10
        pygame.draw.line(screen, (40, 40, 40),
                         (int(prop_x), int(prop_y)), (int(lx), int(ly)), 2)

# 显示 HUD 信息（中文）
def draw_hud():
    # 半透明底
    hud_surf = pygame.Surface((260, 130), pygame.SRCALPHA)
    hud_surf.fill((0, 0, 0, 140))
    screen.blit(hud_surf, (W-280, 20))
    pygame.draw.rect(screen, (0, 200, 255), (W-280, 20, 260, 130), 2)

    alt = max(0, int((H - 100 - plane["y"]) / 2))       # 模拟高度
    spd = int(plane["speed"] * 30)                       # 模拟速度 km/h
    head = int((math.degrees(plane["angle"]) + 360) % 360)  # 航向角

    t1 = font_small.render(f"速度: {spd} km/h", True, (0, 255, 180))
    t2 = font_small.render(f"高度: {alt} m",     True, (0, 255, 180))
    t3 = font_small.render(f"航向: {head}°",     True, (0, 255, 180))
    screen.blit(t1, (W-260, 40))
    screen.blit(t2, (W-260, 75))
    screen.blit(t3, (W-260, 110))

# 显示操作说明（中文）
def draw_help():
    lines = [
        "操作说明:",
        "↑ / ↓ : 抬头 / 低头",
        "W / S : 加速 / 减速",
        "R : 重置飞机",
        "ESC : 退出",
    ]
    for i, line in enumerate(lines):
        color = YELLOW if i == 0 else WHITE
        f = font_mid if i == 0 else font_small
        surf = f.render(line, True, color)
        screen.blit(surf, (20, 20 + i*28))

# 主循环
def main():
    running = True
    while running:
        dt = clock.tick(60) / 16.67  # 归一化到60FPS

        # 事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                if event.key == pygame.K_r:
                    plane.update({"x": 300.0, "y": 350.0, "speed": 3.0,
                                  "angle": 0.0, "vx": 0.0, "vy": 0.0})

        # 按键（持续按压）
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            plane["angle"] -= 0.04 * dt        # 抬头
        if keys[pygame.K_DOWN]:
            plane["angle"] += 0.04 * dt        # 低头
        if keys[pygame.K_w]:
            plane["speed"] = min(MAX_SPEED, plane["speed"] + 0.1 * dt)
        if keys[pygame.K_s]:
            plane["speed"] = max(MIN_SPEED, plane["speed"] - 0.1 * dt)

        # 物理更新
        plane["x"] += math.cos(plane["angle"]) * plane["speed"] * dt
        plane["y"] += math.sin(plane["angle"]) * plane["speed"] * dt
        # 重力影响（简化的：速度越快越容易保持高度）
        plane["y"] += GRAVITY * dt * (5 - plane["speed"] * 0.3)
        # 速度太慢会往下掉
        if plane["speed"] < 2.0:
            plane["y"] += 1.5 * dt
        # 速度太快会往上飘
        if plane["speed"] > 8.0:
            plane["y"] -= 0.8 * dt

        # 边界处理（撞地 / 飞出屏幕）
        if plane["y"] > H - 120:        # 撞地
            plane["y"] = H - 120
            plane["speed"] = max(1.0, plane["speed"] * 0.5)
            plane["angle"] = -abs(plane["angle"]) * 0.5
        if plane["y"] < 40:
            plane["y"] = 40
            plane["angle"] = abs(plane["angle"]) * 0.5
        # 水平循环（左右出屏幕后从另一边回来）
        if plane["x"] < -60:
            plane["x"] = W + 60
        if plane["x"] > W + 60:
            plane["x"] = -60

        # 绘制
        draw_sky()
        draw_clouds(plane["x"])
        draw_ground()
        draw_plane()
        draw_hud()
        draw_help()

        pygame.display.flip()

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()