import pygame
import math

pygame.init()
WIDTH, HEIGHT = 900, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("052. Flight Sim")

clock = pygame.time.Clock()

GRAVITY = 0.4
LIFT_COEFF = 0.0015
DRAG_COEFF = 0.01
THRUST_POWER = 0.25

class Plane:
    def reset(self):
        self.x = 150
        self.y = 300
        self.vx = 50
        self.vy = 0
        self.angle = 0
        self.thrust = 0

    def __init__(self):
        self.reset()

plane = Plane()

def draw_plane(p):
    dx = math.cos(p.angle) * 30
    dy = math.sin(p.angle) * 30
    pygame.draw.line(screen, (255, 0, 0), (p.x, p.y), (p.x + dx, p.y + dy), 4)

def draw_hud():
    # 用方块和线条代替文字（防字体崩溃）
    pygame.draw.rect(screen, (0, 0, 0), (10, 10, 200, 80), 1)
    pygame.draw.circle(screen, (255, 0, 0), (30, 30), 5)
    pygame.draw.circle(screen, (0, 200, 0), (60, 30), 5)

running = True
while running:
    dt = clock.tick(60) / 1000

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
        if e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE:
            plane.reset()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        plane.angle -= 0.03
    if keys[pygame.K_DOWN]:
        plane.angle += 0.03
    if keys[pygame.K_RIGHT]:
        plane.thrust += 0.5
    if keys[pygame.K_LEFT]:
        plane.thrust = max(0, plane.thrust - 0.5)

    speed = math.hypot(plane.vx, plane.vy)
    lift = LIFT_COEFF * speed ** 2
    drag = DRAG_COEFF * speed ** 2

    ax = math.cos(plane.angle) * plane.thrust * THRUST_POWER - drag * (plane.vx / max(speed, 0.1))
    ay = math.sin(plane.angle) * plane.thrust * THRUST_POWER - GRAVITY + lift * (-math.sin(plane.angle))

    plane.vx += ax * dt * 60
    plane.vy += ay * dt * 60
    plane.x += plane.vx * dt * 60
    plane.y += plane.vy * dt * 60

    if plane.y > HEIGHT - 40:
        plane.y = HEIGHT - 40
        plane.vy = 0
        plane.vx *= 0.7

    screen.fill((135, 206, 250))
    pygame.draw.rect(screen, (34, 139, 34), (0, HEIGHT - 40, WIDTH, 40))
    draw_plane(plane)
    draw_hud()
    pygame.display.flip()

pygame.quit()