import pygame
import random
import math
import sys
import os

# ==================== 初始化 ====================
pygame.init()
W, H = 1000, 680
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("🚀 火箭发射模拟器（视角跟随）")
clock = pygame.time.Clock()
FPS = 60

# ==================== 颜色 ====================
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (220, 60, 60)
GREEN = (60, 200, 100)
BLUE = (80, 140, 240)
YELLOW = (255, 220, 80)
ORANGE = (255, 150, 60)
GOLD = (255, 215, 0)
GRAY = (120, 120, 130)
DARK_GRAY = (50, 50, 60)
LIGHT_GRAY = (180, 180, 190)
SKY_TOP = (10, 20, 50)
SKY_BOTTOM = (40, 80, 140)
GROUND = (60, 80, 50)
GROUND_DARK = (40, 55, 35)
PANEL_BG = (15, 20, 35)
PANEL_BORDER = (80, 140, 200)
TEXT_LIGHT = (230, 235, 245)
TEXT_DIM = (160, 170, 185)
FLAME_YELLOW = (255, 240, 100)
FLAME_ORANGE = (255, 140, 40)
FLAME_RED = (220, 60, 40)
STAR_COLOR = (200, 210, 230)

# ==================== 字体 ====================
def find_font():
    for p in ["C:/Windows/Fonts/msyh.ttc", "C:/Windows/Fonts/simhei.ttf",
              "C:/Windows/Fonts/simsun.ttc", "C:/Windows/Fonts/Deng.ttf",
              "/System/Library/Fonts/PingFang.ttc",
              "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
              "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"]:
        if os.path.exists(p):
            return p
    return None

FONT_PATH = find_font()

def load_font(size, bold=False):
    if FONT_PATH:
        try:
            f = pygame.font.Font(FONT_PATH, size)
            if bold: f.set_bold(True)
            return f
        except: pass
    f = pygame.font.Font(None, size + 4)
    if bold: f.set_bold(True)
    return f

fT = load_font(28, True)
fB = load_font(22, True)
fM = load_font(18, True)
fS = load_font(15)
fX = load_font(13)

# ==================== 星星背景（世界坐标固定） ====================
stars = [{'x': random.uniform(0, W * 3), 'y': random.uniform(-20000, 0),
          'r': random.uniform(0.5, 2), 'twinkle': random.uniform(0, 6.28)}
         for _ in range(200)]

# ==================== 云层（世界坐标） ====================
clouds = []
for _ in range(20):
    clouds.append({
        'x': random.uniform(0, W * 2),
        'y': random.uniform(-3000, -300),
        'w': random.uniform(100, 220),
        'h': random.uniform(40, 70),
    })

# ==================== 火箭参数 ====================
class Rocket:
    def __init__(self):
        self.reset()

    def reset(self):
        self.x = W // 2
        self.y = 0                 # 世界坐标（y=0为发射台高度，向上为负）
        self.vy = 0                # 垂直速度（向上为正）
        self.vx = 0                # 水平速度
        self.angle = 0             # 倾斜角度（弧度）
        self.fuel = 100.0          # 燃料 0~100
        self.throttle = 0.0        # 推力 0~1
        self.launched = False
        self.crashed = False
        self.in_orbit = False
        self.grounded = True
        self.altitude = 0.0        # 真实海拔（米）
        self.speed = 0.0
        self.max_altitude = 0.0
        self.time = 0.0
        self.stage = 1
        self.exhaust_timer = 0
        self.particles = []
        self.gravity = 9.8 / 50

    def update(self, dt):
        if self.crashed or self.in_orbit:
            self.update_particles()
            return

        self.time += dt

        if self.fuel > 0 and self.throttle > 0:
            thrust = self.throttle * 30 * dt
            self.vy += thrust * math.cos(self.angle)
            self.vx += thrust * math.sin(self.angle)
            self.fuel -= self.throttle * 0.8 * dt
            if self.fuel < 0:
                self.fuel = 0
            if self.throttle > 0.1:
                self.exhaust_timer += dt
                if self.exhaust_timer > 0.02:
                    self.exhaust_timer = 0
                    self.spawn_exhaust()

        # 重力
        if not self.grounded or self.vy > 0:
            self.vy -= self.gravity * dt * 60

        # 位置（世界坐标，向上为负）
        self.x += self.vx * dt * 60
        self.y -= self.vy * dt * 60

        # 地面（世界坐标 y=0 是地面）
        if self.y >= 0:
            self.y = 0
            if self.vy < -3:
                self.crashed = True
                self.vy = 0
                self.throttle = 0
            else:
                self.vy = 0
                self.vx *= 0.9
                self.grounded = True
        else:
            self.grounded = False

        self.speed = math.hypot(self.vx, self.vy)
        self.altitude = max(0, -self.y * 10)  # 世界坐标 y 乘 10 作为米
        if self.altitude > self.max_altitude:
            self.max_altitude = self.altitude

        if self.altitude > 5000:
            self.stage = 3
        elif self.altitude > 1500:
            self.stage = 2
        else:
            self.stage = 1

        if self.altitude > 8000 and self.speed > 800:
            self.in_orbit = True
            self.throttle = 0

        if self.x < -100 or self.x > W + 100:
            self.crashed = True

        # 重力转向
        if self.vy > 0 and self.stage >= 2:
            target_angle = min(0.6, self.altitude / 15000)
            self.angle += (target_angle - self.angle) * 0.5 * dt

        self.update_particles()

    def spawn_exhaust(self):
        angle = self.angle
        ox = -math.sin(angle) * 20
        oy = math.cos(angle) * 20 + 15
        px = self.x + ox
        py = self.y + oy
        life = random.uniform(0.3, 0.8)
        self.particles.append({
            'x': px, 'y': py,
            'vx': random.uniform(-30, 30),
            'vy': random.uniform(20, 80),
            'life': life, 'max_life': life,
            'size': random.uniform(4, 10),
            'color': random.choice([FLAME_YELLOW, FLAME_ORANGE, FLAME_RED])
        })

    def update_particles(self):
        for p in self.particles[:]:
            p['x'] += p['vx'] * 0.016
            p['y'] += p['vy'] * 0.016
            p['life'] -= 0.016
            if p['life'] <= 0:
                self.particles.remove(p)

    def draw(self, surf, cam_x, cam_y):
        # 世界坐标转屏幕坐标
        sx = self.x - cam_x
        sy = self.y - cam_y

        # 尾焰粒子
        for p in self.particles:
            alpha = max(0, p['life'] / p['max_life'])
            r = max(1, int(p['size'] * alpha))
            ps = pygame.Surface((r * 2, r * 2), pygame.SRCALPHA)
            pygame.draw.circle(ps, (*p['color'], int(200 * alpha)), (r, r), r)
            surf.blit(ps, (int(p['x'] - cam_x - r), int(p['y'] - cam_y - r)))

        if self.crashed:
            t = self.time
            for i in range(20):
                angle = i * math.pi / 10
                dist = (t * 100) % 150
                ex = sx + math.cos(angle) * dist
                ey = sy + math.sin(angle) * dist
                r = max(1, int(15 * (1 - dist / 150)))
                pygame.draw.circle(surf, ORANGE, (int(ex), int(ey)), r)
            return

        cx, cy = sx, sy

        # 影子（仅靠近地面时）
        if self.altitude < 300:
            shadow_y = -cam_y
            if 0 <= shadow_y < H:
                pygame.draw.ellipse(surf, (0, 0, 0), (cx - 25, shadow_y - 4, 50, 10))

        cos_a = math.cos(self.angle)
        sin_a = math.sin(self.angle)

        def rot(px, py):
            return (cx + px * cos_a - py * sin_a,
                    cy + px * sin_a + py * cos_a)

        body_pts = [rot(-18, 0), rot(-18, -80), rot(18, -80), rot(18, 0)]
        pygame.draw.polygon(surf, LIGHT_GRAY, body_pts)
        pygame.draw.polygon(surf, (100, 100, 110), body_pts, 2)

        nose_pts = [rot(-18, -80), rot(0, -120), rot(18, -80)]
        pygame.draw.polygon(surf, RED, nose_pts)
        pygame.draw.polygon(surf, (180, 40, 40), nose_pts, 2)

        fin_l = [rot(-18, -15), rot(-35, 5), rot(-18, 5)]
        fin_r = [rot(18, -15), rot(35, 5), rot(18, 5)]
        pygame.draw.polygon(surf, RED, fin_l)
        pygame.draw.polygon(surf, RED, fin_r)
        pygame.draw.polygon(surf, (180, 40, 40), fin_l, 2)
        pygame.draw.polygon(surf, (180, 40, 40), fin_r, 2)

        win_x, win_y = rot(0, -55)
        pygame.draw.circle(surf, BLUE, (int(win_x), int(win_y)), 6)
        pygame.draw.circle(surf, (200, 220, 255), (int(win_x), int(win_y)), 6, 2)

        stripe1 = [rot(-18, -35), rot(18, -35), rot(18, -30), rot(-18, -30)]
        pygame.draw.polygon(surf, BLUE, stripe1)

        if self.throttle > 0.05 and self.fuel > 0:
            flame_len = 25 + self.throttle * 45 + random.uniform(-5, 5)
            f1 = rot(-12, 0)
            f2 = rot(12, 0)
            f3 = rot(0, flame_len)
            pygame.draw.polygon(surf, FLAME_ORANGE, [f1, f2, f3])
            f4 = rot(0, flame_len * 0.6)
            pygame.draw.polygon(surf, FLAME_YELLOW, [rot(-7, 0), rot(7, 0), f4])

    def draw_hud(self, surf):
        panel = pygame.Surface((320, 300), pygame.SRCALPHA)
        panel.fill((15, 20, 35, 220))
        pygame.draw.rect(panel, PANEL_BORDER, (0, 0, 320, 300), 2, border_radius=12)
        surf.blit(panel, (20, 20))

        title = fB.render("📊 飞行仪表盘", True, GOLD)
        surf.blit(title, (35, 30))

        y = 70
        alt_text = fB.render(f"高度: {self.altitude:.0f} m", True, TEXT_LIGHT)
        surf.blit(alt_text, (40, y)); y += 30
        max_alt = fS.render(f"最高: {self.max_altitude:.0f} m", True, TEXT_DIM)
        surf.blit(max_alt, (40, y)); y += 30

        spd_color = GREEN if self.speed < 800 else YELLOW if self.speed < 1500 else RED
        spd_text = fB.render(f"速度: {self.speed:.0f} m/s", True, spd_color)
        surf.blit(spd_text, (40, y)); y += 32

        fuel_label = fS.render(f"燃料: {self.fuel:.0f}%", True, TEXT_LIGHT)
        surf.blit(fuel_label, (40, y))
        bar_x, bar_y, bar_w, bar_h = 130, y + 2, 150, 16
        pygame.draw.rect(surf, (40, 40, 50), (bar_x, bar_y, bar_w, bar_h), border_radius=8)
        fuel_color = GREEN if self.fuel > 50 else YELLOW if self.fuel > 20 else RED
        pygame.draw.rect(surf, fuel_color, (bar_x, bar_y, int(bar_w * self.fuel / 100), bar_h), border_radius=8)
        pygame.draw.rect(surf, (100, 120, 150), (bar_x, bar_y, bar_w, bar_h), 2, border_radius=8)
        y += 36

        thr_label = fS.render(f"推力: {self.throttle * 100:.0f}%", True, TEXT_LIGHT)
        surf.blit(thr_label, (40, y))
        pygame.draw.rect(surf, (40, 40, 50), (bar_x, y + 2, bar_w, 16), border_radius=8)
        pygame.draw.rect(surf, ORANGE, (bar_x, y + 2, int(bar_w * self.throttle), 16), border_radius=8)
        pygame.draw.rect(surf, (100, 120, 150), (bar_x, y + 2, bar_w, 16), 2, border_radius=8)
        y += 36

        stage_names = {1: "① 大气层内", 2: "② 接近轨道", 3: "③ 已入轨道"}
        stage_colors = {1: GREEN, 2: YELLOW, 3: GOLD}
        stage_text = fM.render(f"阶段: {stage_names[self.stage]}", True, stage_colors[self.stage])
        surf.blit(stage_text, (40, y)); y += 28

        # 视角提示
        view_text = fS.render(f"视角跟随中 (世界Y: {self.y:.0f})", True, TEXT_DIM)
        surf.blit(view_text, (40, y))

    def draw_controls(self, surf):
        ctrl = pygame.Surface((W - 40, 120), pygame.SRCALPHA)
        ctrl.fill((15, 20, 35, 220))
        pygame.draw.rect(ctrl, PANEL_BORDER, (0, 0, W - 40, 120), 2, border_radius=12)
        surf.blit(ctrl, (20, H - 140))

        if not self.launched:
            hint = fB.render("按 [空格] 点火发射！", True, GOLD)
            surf.blit(hint, (40, H - 125))
        elif self.in_orbit:
            hint = fB.render("🎉 恭喜！火箭成功进入轨道！", True, GOLD)
            surf.blit(hint, (40, H - 125))
        elif self.crashed:
            hint = fB.render("💥 火箭坠毁！按 [R] 重新开始", True, RED)
            surf.blit(hint, (40, H - 125))
        else:
            hint = fM.render("使用 [↑↓] 调节推力    [←→] 微调方向    [空格] 紧急关闭/开启推力", True, TEXT_LIGHT)
            surf.blit(hint, (40, H - 125))

        hints = ["空格: 点火/发射", "↑/↓: 增加/减少推力", "←/→: 倾斜火箭", "R: 重新开始"]
        for i, h in enumerate(hints):
            t = fS.render(h, True, TEXT_DIM)
            surf.blit(t, (40 + i * 230, H - 95))

        gauge_x = W - 260
        gauge_y = H - 130
        gauge_w = 220
        gauge_h = 24

        label = fS.render("推力控制", True, TEXT_LIGHT)
        surf.blit(label, (gauge_x, gauge_y - 20))
        pygame.draw.rect(surf, (40, 40, 50), (gauge_x, gauge_y, gauge_w, gauge_h), border_radius=12)
        fill = int(gauge_w * self.throttle)
        if fill > 0:
            color = GREEN if self.throttle < 0.5 else YELLOW if self.throttle < 0.8 else RED
            pygame.draw.rect(surf, color, (gauge_x, gauge_y, fill, gauge_h), border_radius=12)
        pygame.draw.rect(surf, (100, 120, 150), (gauge_x, gauge_y, gauge_w, gauge_h), 2, border_radius=12)
        for i in range(11):
            mx = gauge_x + gauge_w * i // 10
            pygame.draw.line(surf, (150, 160, 180), (mx, gauge_y), (mx, gauge_y + gauge_h), 1)
        pct = fB.render(f"{self.throttle * 100:.0f}%", True, WHITE)
        surf.blit(pct, (gauge_x + gauge_w // 2 - pct.get_width() // 2, gauge_y + gauge_h + 8))


# ==================== 背景绘制（跟随镜头） ====================
def draw_background(surf, cam_x, cam_y, rocket):
    altitude_factor = min(1.0, rocket.altitude / 10000)

    # 天空渐变（屏幕坐标，随高度变化）
    for y in range(H):
        ratio = y / H
        top_r = int(SKY_TOP[0] + (10 - SKY_TOP[0]) * altitude_factor)
        top_g = int(SKY_TOP[1] + (5 - SKY_TOP[1]) * altitude_factor)
        top_b = int(SKY_TOP[2] + (25 - SKY_TOP[2]) * altitude_factor)
        bot_r = int(SKY_BOTTOM[0] + (30 - SKY_BOTTOM[0]) * altitude_factor)
        bot_g = int(SKY_BOTTOM[1] + (40 - SKY_BOTTOM[1]) * altitude_factor)
        bot_b = int(SKY_BOTTOM[2] + (80 - SKY_BOTTOM[2]) * altitude_factor)
        r = int(top_r + (bot_r - top_r) * ratio)
        g = int(top_g + (bot_g - top_g) * ratio)
        b = int(top_b + (bot_b - top_b) * ratio)
        pygame.draw.line(surf, (r, g, b), (0, y), (W, y))

    # 星空（世界坐标，随镜头滚动）
    if altitude_factor > 0.15:
        alpha = int(255 * (altitude_factor - 0.15) / 0.85)
        t = pygame.time.get_ticks() / 1000
        for s in stars:
            sx = s['x'] - cam_x
            sy = s['y'] - cam_y
            if -10 < sx < W + 10 and -10 < sy < H + 10:
                twinkle = 0.5 + 0.5 * math.sin(t * 2 + s['twinkle'])
                star_alpha = int(alpha * twinkle)
                if star_alpha > 10:
                    star_surf = pygame.Surface((int(s['r'] * 4) + 2, int(s['r'] * 4) + 2), pygame.SRCALPHA)
                    pygame.draw.circle(star_surf, (*STAR_COLOR, star_alpha),
                                       (int(s['r'] * 2) + 1, int(s['r'] * 2) + 1), int(s['r']))
                    surf.blit(star_surf, (int(sx - s['r'] * 2), int(sy - s['r'] * 2)))

    # 云层（世界坐标）
    if rocket.altitude < 3000:
        cloud_alpha = int(180 * (1 - rocket.altitude / 3000))
        for c in clouds:
            cx = c['x'] - cam_x
            cy = c['y'] - cam_y
            if -300 < cx < W + 300 and -100 < cy < H + 100:
                cloud_surf = pygame.Surface((int(c['w']), int(c['h'])), pygame.SRCALPHA)
                pygame.draw.ellipse(cloud_surf, (220, 230, 250, cloud_alpha),
                                    (0, c['h'] // 3, c['w'] * 0.5, c['h'] * 0.7))
                pygame.draw.ellipse(cloud_surf, (220, 230, 250, cloud_alpha),
                                    (c['w'] * 0.2, 0, c['w'] * 0.6, c['h']))
                pygame.draw.ellipse(cloud_surf, (220, 230, 250, cloud_alpha),
                                    (c['w'] * 0.4, c['h'] // 3, c['w'] * 0.5, c['h'] * 0.6))
                surf.blit(cloud_surf, (int(cx), int(cy)))

    # 地面和发射台（世界坐标 y=0，屏幕坐标 = -cam_y）
    ground_screen_y = -cam_y
    if ground_screen_y < H:
        # 地面填充
        ground_rect = pygame.Rect(0, int(ground_screen_y), W, H - int(ground_screen_y))
        if ground_rect.height > 0:
            pygame.draw.rect(surf, GROUND, ground_rect)
            # 地面纹理
            for i in range(50):
                gx = (i * 73) % W
                gy = int(ground_screen_y) + 10 + (i * 41) % 130
                if gy < H:
                    pygame.draw.circle(surf, GROUND_DARK, (gx, gy), 2 + i % 3)

        # 发射台
        pad_x = W // 2
        pad_top = int(ground_screen_y) - 20
        pygame.draw.rect(surf, (80, 80, 90), (pad_x - 80, pad_top, 160, 20))
        pygame.draw.rect(surf, (100, 100, 110), (pad_x - 80, pad_top, 160, 5))

        # 发射塔
        tower_top = int(ground_screen_y) - 200
        if tower_top < H:
            pygame.draw.rect(surf, (60, 65, 75), (pad_x + 70, tower_top, 20, min(200, H - tower_top)))
            pygame.draw.rect(surf, (80, 85, 95), (pad_x + 70, tower_top, 20, min(200, H - tower_top)), 2)
            for i in range(6):
                ty = tower_top + i * 30
                if ty < H:
                    pygame.draw.line(surf, (100, 105, 115), (pad_x + 70, ty), (pad_x + 50, ty), 2)
            # 塔顶灯
            blink = int(pygame.time.get_ticks() / 300) % 2
            if tower_top - 10 < H:
                pygame.draw.circle(surf, RED if blink else (100, 30, 30),
                                   (pad_x + 80, tower_top - 10), 5)

        # 地面线
        pygame.draw.line(surf, (30, 40, 25), (0, int(ground_screen_y)), (W, int(ground_screen_y)), 2)


# ==================== 游戏主类 ====================
class Game:
    def __init__(self):
        self.rocket = Rocket()
        self.cam_x = 0
        self.cam_y = 0
        self.msg = ""
        self.msg_timer = 0
        self.msg_color = GOLD
        self._last_stage = 0

    def reset(self):
        self.rocket = Rocket()
        self.cam_x = 0
        self.cam_y = 0
        self.msg = ""
        self.msg_timer = 0
        self._last_stage = 0

    def show_msg(self, text, color=GOLD):
        self.msg = text
        self.msg_color = color
        self.msg_timer = 120

    def update(self, dt):
        if self.msg_timer > 0:
            self.msg_timer -= 1

        r = self.rocket
        r.update(dt)

        # 摄像机跟随（平滑）
        # 目标：让火箭位于屏幕中偏下（露出更多上方空间观察升空）
        target_cam_x = r.x - W // 2
        target_cam_y = r.y - H * 0.62  # 火箭显示在屏幕62%高度处
        self.cam_x += (target_cam_x - self.cam_x) * 0.12
        self.cam_y += (target_cam_y - self.cam_y) * 0.12

        # 阶段提示
        if r.stage == 2 and self._last_stage != 2:
            self.show_msg("⚡ 进入高层大气！注意重力转向", YELLOW)
        elif r.stage == 3 and self._last_stage != 3:
            self.show_msg("🛰 接近轨道速度！", GOLD)
        self._last_stage = r.stage

        if r.fuel <= 0 and not r.in_orbit and not r.crashed:
            if r.speed < 100 and r.altitude < 200:
                self.show_msg("燃料耗尽！按 R 重新开始", RED)

    def draw(self, surf):
        draw_background(surf, self.cam_x, self.cam_y, self.rocket)
        self.rocket.draw(surf, self.cam_x, self.cam_y)
        self.rocket.draw_hud(surf)
        self.rocket.draw_controls(surf)

        # 屏幕中央参考准星（跟随效果指示）
        cx, cy = W // 2, int(H * 0.62)
        pygame.draw.line(surf, (100, 150, 200), (cx - 15, cy), (cx - 5, cy), 1)
        pygame.draw.line(surf, (100, 150, 200), (cx + 5, cy), (cx + 15, cy), 1)
        pygame.draw.line(surf, (100, 150, 200), (cx, cy - 15), (cx, cy - 5), 1)
        pygame.draw.line(surf, (100, 150, 200), (cx, cy + 5), (cx, cy + 15), 1)

        # 消息
        if self.msg_timer > 0 and self.msg:
            alpha = min(255, self.msg_timer * 3)
            mt = fT.render(self.msg, True, self.msg_color)
            bg = pygame.Surface((mt.get_width() + 40, mt.get_height() + 20), pygame.SRCALPHA)
            bg.fill((20, 25, 40, int(alpha * 0.85)))
            pygame.draw.rect(bg, self.msg_color, (0, 0, bg.get_width(), bg.get_height()), 2, border_radius=10)
            surf.blit(bg, (W // 2 - bg.get_width() // 2, H // 2 - 150))
            mt.set_alpha(alpha)
            surf.blit(mt, (W // 2 - mt.get_width() // 2, H // 2 - 140))

        # 结束遮罩
        if self.rocket.crashed:
            overlay = pygame.Surface((W, H), pygame.SRCALPHA)
            overlay.fill((100, 20, 20, 60))
            surf.blit(overlay, (0, 0))
        elif self.rocket.in_orbit:
            overlay = pygame.Surface((W, H), pygame.SRCALPHA)
            overlay.fill((255, 215, 0, 30))
            surf.blit(overlay, (0, 0))
            t = pygame.time.get_ticks() / 1000
            for i in range(30):
                angle = i * 0.21 + t
                dist = 100 + math.sin(t * 2 + i) * 50
                px = W // 2 + math.cos(angle) * dist
                py = H // 2 - 100 + math.sin(angle) * dist
                pygame.draw.circle(surf, GOLD, (int(px), int(py)), 2)

    def handle_key(self, key, down):
        r = self.rocket
        if r.crashed or r.in_orbit:
            return
        if key == pygame.K_SPACE and down:
            if not r.launched:
                r.launched = True
                r.throttle = 1.0
                self.show_msg("🚀 点火！发射！", GOLD)
            else:
                if r.throttle > 0:
                    r.throttle = 0
                    self.show_msg("推力已关闭", YELLOW)
                else:
                    r.throttle = 1.0
                    self.show_msg("推力全开！", GREEN)
        if key == pygame.K_UP:
            r.throttle = min(1.0, r.throttle + 0.05)
        if key == pygame.K_DOWN:
            r.throttle = max(0.0, r.throttle - 0.05)
        if key == pygame.K_LEFT:
            r.angle = max(-0.6, r.angle - 0.02)
        if key == pygame.K_RIGHT:
            r.angle = min(0.6, r.angle + 0.02)


# ==================== 主循环 ====================
def main():
    game = Game()
    running = True
    while running:
        dt = clock.tick(FPS) / 1000.0
        for ev in pygame.event.get():
            if ev.type == pygame.QUIT:
                running = False
            elif ev.type == pygame.KEYDOWN:
                if ev.key == pygame.K_ESCAPE:
                    running = False
                elif ev.key == pygame.K_r:
                    game.reset()
                else:
                    game.handle_key(ev.key, True)
            elif ev.type == pygame.KEYUP:
                game.handle_key(ev.key, False)

        game.update(dt)
        game.draw(screen)
        pygame.display.flip()

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()