#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
航海模拟器 (Sailing Simulator) —— 海龟编辑器兼容版

为在「海龟编辑器 / ppg 沙盒 / 无窗口环境」里也能跑, 本版做了三件事:
  1. 所有绘制包了安全调用: alpha 表面、非法线宽/半径、缺字体都不会让画面崩掉
  2. 输入双通道: 键盘事件 + get_pressed 兜底; 键盘不生效时点右下角屏幕按钮也能玩
  3. 绝不静默失败: 初始化失败会往屏幕画提示, 而不是白屏/黑屏无反馈

操作:
    A / D      : 左右转向        (或点屏幕左下 ◀ ▶)
    W / S      : 前进 / 后退      (或点屏幕左下 ▲ ▼)
    空格        : 冲刺 + 溅起浪花
    P / R / ESC: 暂停 / 重开 / 退出
依赖: pygame   运行: pip install pygame && python main.py
"""

import pygame
import math
import random
import sys
import traceback
from dataclasses import dataclass, field
from typing import List, Tuple, Optional

# ----------------------------------------------------------------------------
# 全局配置
# ----------------------------------------------------------------------------
SCREEN_W, SCREEN_H = 1000, 660
FPS = 60
WORLD_W, WORLD_H = 7000, 7000
BOAT_MAX_HP = 100
BOAT_MAX_SPEED = 7.0
BOAT_REVERSE_SPEED = 3.2
TURN_SPEED = 2.7
ACCEL = 2.2
BRAKE = 3.0
SUPPLY_MAX = 8
ROCK_MAX = 70
ISLAND_MAX = 10
LIGHTHOUSE_MAX = 4
CLOUD_MAX = 9
SEAGULL_MAX = 7

COLOR_SEA_DEEP = (16, 74, 124)
COLOR_SEA = (34, 120, 170)
COLOR_SEA_LIGHT = (52, 145, 190)
COLOR_FOAM = (225, 245, 255)
COLOR_HULL = (236, 176, 96)
COLOR_HULL_DARK = (150, 92, 44)
COLOR_SAIL = (250, 248, 238)
COLOR_SAIL_STRIPE = (232, 96, 78)
COLOR_WHITE = (255, 255, 255)
COLOR_GOLD = (255, 205, 60)
COLOR_GREEN = (70, 220, 130)
COLOR_BLUE = (90, 180, 255)
COLOR_RED = (235, 80, 70)
COLOR_DARK = (24, 44, 62)


# ----------------------------------------------------------------------------
# 安全绘制封装: 任何一步失败都只跳过, 绝不打断整帧渲染
# ----------------------------------------------------------------------------
def make_font(size):
    """尽力创建一个字体对象; 完全不可用则返回 None。"""
    try:
        return pygame.font.Font(None, size)
    except Exception:
        pass
    try:
        return pygame.font.SysFont("", size)
    except Exception:
        return None


def safe_text(surface, font, text, pos, color):
    if surface is None or font is None:
        return
    try:
        img = font.render(text, True, color)
        surface.blit(img, pos)
    except Exception:
        pass


def safe_aalpha(w, h):
    """创建一个带 alpha 的表面; 不支持就返回 None(调用方需判空跳过)。"""
    try:
        s = pygame.Surface((w, h), pygame.SRCALPHA)
        s.fill((0, 0, 0, 0))
        return s
    except Exception:
        try:
            s = pygame.Surface((w, h))
            s.set_colorkey((0, 0, 0))
            s.fill((0, 0, 0))
            return s
        except Exception:
            return None


def safe_poly(surface, color, pts, width=0):
    if surface is None or not pts or len(pts) < 3:
        return
    try:
        pygame.draw.polygon(surface, color, pts, width)
    except Exception:
        pass


def safe_circle(surface, color, pos, r, width=0):
    if surface is None or r is None or r <= 0:
        return
    try:
        pygame.draw.circle(surface, color, (int(pos[0]), int(pos[1])), int(r), width)
    except Exception:
        pass


def safe_line(surface, color, a, b, width=1):
    if surface is None or width is None or width <= 0:
        return
    try:
        pygame.draw.line(surface, color, (int(a[0]), int(a[1])), (int(b[0]), int(b[1])), int(width))
    except Exception:
        pass


def safe_arrow(surface, color, cx, cy, angle, length, width=3, head=10):
    ex = cx + math.cos(angle) * length
    ey = cy + math.sin(angle) * length
    safe_line(surface, color, (cx, cy), (ex, ey), width)
    left = angle + math.pi * 0.85
    right = angle - math.pi * 0.85
    safe_line(surface, color, (ex, ey),
              (ex + math.cos(left) * head, ey + math.sin(left) * head), width)
    safe_line(surface, color, (ex, ey),
              (ex + math.cos(right) * head, ey + math.sin(right) * head), width)


def angle_diff(a, b):
    d = (a - b) % (2 * math.pi)
    if d > math.pi:
        d -= 2 * math.pi
    return d


# ----------------------------------------------------------------------------
# 风
# ----------------------------------------------------------------------------
class Wind:
    def __init__(self):
        self.angle = random.uniform(0, 2 * math.pi)
        self.target_angle = self.angle
        self.strength = 1.0
        self.timer = 0.0

    def update(self, dt):
        self.timer -= dt
        if self.timer <= 0:
            self.target_angle = self.angle + random.uniform(-1.2, 1.2)
            self.strength = random.uniform(1.0, 1.8)
            self.timer = random.uniform(6, 12)
        self.angle += angle_diff(self.target_angle, self.angle) * min(1.0, dt * 0.8)


# ----------------------------------------------------------------------------
# 帆船: AD 转向, WS 前后 (松手惯性滑行), 空格冲刺
# ----------------------------------------------------------------------------
class Boat:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.heading = -math.pi / 2
        self.throttle = 0.0
        self.speed = 0.0
        self.sail = 0.0
        self.hp = BOAT_MAX_HP
        self.honk_cd = 0.0
        self.bob = 0.0
        self.boat_len = 48
        self.boat_wid = 22

    def update(self, dt, wind, left, right, up, down, boost):
        turn = (1.0 if right else 0.0) - (1.0 if left else 0.0)
        reverse = 1.0 if self.speed >= -0.1 else -1.0
        self.heading = (self.heading + turn * TURN_SPEED * reverse * dt) % (2 * math.pi)

        if up:
            self.throttle = min(1.0, self.throttle + ACCEL * dt)
        elif down:
            self.throttle = max(-1.0, self.throttle - BRAKE * dt)
        else:
            if self.throttle > 0:
                self.throttle = max(0.0, self.throttle - ACCEL * 0.6 * dt)
            elif self.throttle < 0:
                self.throttle = min(0.0, self.throttle + BRAKE * 0.6 * dt)

        self.honk_cd = max(0.0, self.honk_cd - dt)
        honked = False
        if boost and self.honk_cd <= 0:
            self.speed += 2.2 if self.speed >= 0 else -1.4
            self.honk_cd = 1.2
            honked = True

        self.apply_physics(dt, wind)
        self.bob += dt * 2.2
        target_sail = max(0.0, min(1.0, self.speed / BOAT_MAX_SPEED))
        self.sail += (target_sail - self.sail) * min(1.0, dt * 4.0)
        return "honk" if honked else None

    def apply_physics(self, dt, wind):
        wind_to = wind.angle + math.pi
        diff = abs(angle_diff(self.heading, wind_to))
        factor = 0.6 + 0.65 * max(0.0, math.cos(diff))
        if self.throttle >= 0:
            target = self.throttle * BOAT_MAX_SPEED * factor
        else:
            target = self.throttle * BOAT_REVERSE_SPEED
        rate = 3.0 if abs(target) > abs(self.speed) else 4.0
        self.speed += (target - self.speed) * min(1.0, dt * rate)
        self.speed = max(-BOAT_REVERSE_SPEED, min(BOAT_MAX_SPEED * 1.3, self.speed))
        if abs(self.speed) < 0.02:
            self.speed = 0.0
        self.x += math.cos(self.heading) * self.speed
        self.y += math.sin(self.heading) * self.speed
        self.x = max(30, min(WORLD_W - 30, self.x))
        self.y = max(30, min(WORLD_H - 30, self.y))

    def damage(self, amount):
        self.hp = max(0, self.hp - amount)

    def draw(self, surface, cx, cy):
        cos_h = math.cos(self.heading)
        sin_h = math.sin(self.heading)

        def to_screen(lx, ly):
            return (cx + (lx * cos_h - ly * sin_h), cy + (lx * sin_h + ly * cos_h))

        bob_y = math.sin(self.bob) * 3
        cy += bob_y
        L, W = self.boat_len, self.boat_wid

        shadow = [to_screen(L * 0.9, 0), to_screen(-L * 0.7, W * 1.1),
                  to_screen(-L * 1.0, 0), to_screen(-L * 0.7, -W * 1.1)]
        safe_poly(surface, (18, 66, 104), [(px, cy + 8) for px, py in shadow])

        hull = [
            to_screen(L, 0), to_screen(L * 0.55, W * 0.95),
            to_screen(-L * 0.55, W * 0.9), to_screen(-L * 0.85, W * 0.45),
            to_screen(-L * 0.9, 0), to_screen(-L * 0.85, -W * 0.45),
            to_screen(-L * 0.55, -W * 0.9), to_screen(L * 0.55, -W * 0.95),
        ]
        safe_poly(surface, COLOR_HULL, hull)
        safe_poly(surface, COLOR_HULL_DARK, hull, 3)
        safe_line(surface, (255, 214, 150), hull[1], hull[2], 2)
        safe_line(surface, (255, 214, 150), hull[2], hull[3], 2)

        for sx in (0.15, -0.35):
            wxp, wyp = to_screen(L * sx, -W * 0.35)
            safe_circle(surface, (150, 220, 255), (wxp, wyp), 4)
            safe_circle(surface, COLOR_DARK, (wxp, wyp), 4, 1)

        ex, ey = to_screen(L * 0.62, -W * 0.28)
        ex2, ey2 = to_screen(L * 0.62, W * 0.28)
        safe_circle(surface, COLOR_WHITE, (ex, ey), 5)
        safe_circle(surface, COLOR_WHITE, (ex2, ey2), 5)
        pdx, pdy = math.cos(self.heading) * 2, math.sin(self.heading) * 2
        safe_circle(surface, COLOR_DARK, (ex + pdx, ey + pdy), 2)
        safe_circle(surface, COLOR_DARK, (ex2 + pdx, ey2 + pdy), 2)

        mx, my = to_screen(L * 0.1, 0)
        safe_line(surface, (120, 80, 40), (mx, my), (mx, my - 46), 3)
        if self.sail > 0.03:
            base = to_screen(L * 0.12, 0)
            tip = (mx, my - 44)
            belly = 12 + 14 * self.sail
            bow = to_screen(-L * 0.35, -belly)
            safe_poly(surface, COLOR_SAIL, [base, tip, bow])
            safe_poly(surface, COLOR_HULL_DARK, [base, tip, bow], 2)
            safe_line(surface, COLOR_SAIL_STRIPE, base, to_screen(-L * 0.2, -belly * 0.5), 3)
        fx, fy = mx, my - 44
        wave = math.sin(self.bob * 2) * 4
        safe_poly(surface, COLOR_RED, [(fx, fy), (fx + 16, fy + 4 + wave), (fx, fy + 8)])


# ----------------------------------------------------------------------------
# 礁石
# ----------------------------------------------------------------------------
@dataclass
class Rock:
    x: float
    y: float
    r: float
    points: List[Tuple[float, float]] = field(default_factory=list)

    @staticmethod
    def make(x, y):
        r = random.uniform(22, 48)
        pts = []
        n = random.randint(6, 9)
        for i in range(n):
            a = i / n * 2 * math.pi
            rr = r * random.uniform(0.7, 1.15)
            pts.append((math.cos(a) * rr, math.sin(a) * rr))
        return Rock(x, y, r, pts)

    def draw(self, surface, cx, cy):
        poly = [(cx + px, cy + py) for px, py in self.points]
        safe_poly(surface, (110, 104, 96), poly)
        safe_poly(surface, (60, 56, 50), poly, 2)
        safe_circle(surface, (150, 144, 136), (cx - self.r * 0.2, cy - self.r * 0.25), self.r * 0.22)
        safe_circle(surface, COLOR_FOAM, (cx, cy + self.r * 0.7), self.r * 0.5, 1)


# ----------------------------------------------------------------------------
# 沙滩岛
# ----------------------------------------------------------------------------
@dataclass
class Island:
    x: float
    y: float
    r: float
    palm: List[Tuple[float, float]] = field(default_factory=list)

    @staticmethod
    def make(x, y):
        r = random.uniform(90, 150)
        palm = []
        for _ in range(random.randint(1, 3)):
            a = random.uniform(0, 2 * math.pi)
            d = random.uniform(0, r * 0.5)
            palm.append((math.cos(a) * d, math.sin(a) * d))
        return Island(x, y, r, palm)

    def draw(self, surface, cx, cy, t):
        safe_circle(surface, COLOR_SEA_LIGHT, (cx, cy), self.r * 1.25)
        safe_circle(surface, (238, 214, 160), (cx, cy), self.r)
        safe_circle(surface, (250, 232, 185), (cx, cy), self.r * 0.72)
        safe_circle(surface, (110, 190, 110), (cx, cy - self.r * 0.1), self.r * 0.42)
        for px, py in self.palm:
            tx, ty = int(cx + px), int(cy + py - self.r * 0.1)
            safe_line(surface, (140, 96, 52), (tx, ty), (tx - 6, ty - 26), 4)
            sway = math.sin(t + px) * 4
            for k in range(4):
                a = k * math.pi / 2 + sway * 0.05
                safe_line(surface, (60, 170, 90), (tx - 6, ty - 26),
                          (tx - 6 + math.cos(a) * 18, ty - 26 + math.sin(a) * 14), 3)
            safe_circle(surface, (150, 110, 60), (tx - 4, ty - 24), 3)


# ----------------------------------------------------------------------------
# 灯塔
# ----------------------------------------------------------------------------
@dataclass
class Lighthouse:
    x: float
    y: float

    def draw(self, surface, cx, cy, t):
        safe_line(surface, (120, 116, 108), (cx - 22, cy), (cx + 22, cy), 14)
        for i in range(5):
            col = (235, 80, 70) if i % 2 == 0 else (245, 245, 240)
            safe_line(surface, col, (cx - 12, cy - i * 16 - 8), (cx + 12, cy - i * 16 - 8), 16)
        safe_line(surface, COLOR_DARK, (cx - 14, cy - 84), (cx + 14, cy - 84), 16)
        safe_circle(surface, (255, 255, 200), (cx, cy - 84), 8)
        safe_circle(surface, (255, 255, 160), (cx, cy - 84), 14, 2)
        beam = (t * 1.5) % (2 * math.pi)
        safe_line(surface, (255, 255, 180), (cx, cy - 84),
                  (cx + math.cos(beam) * 90, cy - 84 + math.sin(beam) * 40), 2)


# ----------------------------------------------------------------------------
# 云
# ----------------------------------------------------------------------------
@dataclass
class Cloud:
    x: float
    y: float
    speed: float
    scale: float = 1.0

    @staticmethod
    def make(x, y):
        return Cloud(x, y, random.uniform(6, 14), random.uniform(0.8, 1.4))

    def update(self, dt):
        self.x += self.speed * dt
        if self.x > WORLD_W + 100:
            self.x = -100

    def draw(self, surface, cx, cy):
        s = self.scale
        for dx, dy, r in [(0, 0, 26), (22, -6, 30), (46, 0, 24), (22, 8, 22)]:
            safe_circle(surface, (255, 255, 255), (cx + dx * s, cy + dy * s), r * s)
        safe_circle(surface, (235, 240, 245), (cx + 22 * s, cy + 14 * s), 16 * s)


# ----------------------------------------------------------------------------
# 海鸥
# ----------------------------------------------------------------------------
@dataclass
class Seagull:
    x: float
    y: float
    dir: float
    speed: float
    phase: float = 0.0

    @staticmethod
    def make(x, y):
        return Seagull(x, y, random.choice([-1, 1]) * 1.0,
                       random.uniform(20, 40), random.uniform(0, 2 * math.pi))

    def update(self, dt):
        self.x += self.dir * self.speed * dt
        self.y += math.sin(self.phase) * 6 * dt
        self.phase += dt * 4
        if self.x < -100:
            self.x = WORLD_W + 100
        if self.x > WORLD_W + 100:
            self.x = -100

    def draw(self, surface, cx, cy):
        wing = math.sin(self.phase) * 6
        safe_line(surface, (250, 250, 245), (cx - 10, cy - wing), (cx, cy + 3), 2)
        safe_line(surface, (250, 250, 245), (cx, cy + 3), (cx + 10, cy - wing), 2)


# ----------------------------------------------------------------------------
# 补给
# ----------------------------------------------------------------------------
@dataclass
class Supply:
    x: float
    y: float
    kind: str
    r: float = 14
    phase: float = 0.0

    @staticmethod
    def make(x, y):
        return Supply(x, y, random.choice(["repair", "boost", "coin", "coin", "coin"]),
                      phase=random.uniform(0, 2 * math.pi))

    def color(self):
        return {"repair": COLOR_GREEN, "boost": COLOR_BLUE, "coin": COLOR_GOLD}[self.kind]

    def update(self, dt):
        self.phase += dt * 3

    def draw(self, surface, cx, cy, font):
        bob = math.sin(self.phase) * 4
        c = self.color()
        bright = tuple(min(255, v + 60) for v in c)
        safe_circle(surface, bright, (cx, cy + bob), self.r + 5)
        safe_circle(surface, c, (cx, cy + bob), self.r)
        safe_circle(surface, COLOR_WHITE, (cx, cy + bob), self.r, 2)
        icon = {"repair": "+", "boost": ">>", "coin": "$"}[self.kind]
        safe_text(surface, font, icon, (cx - 5, cy + bob - 7), COLOR_DARK)


# ----------------------------------------------------------------------------
# 浪花粒子
# ----------------------------------------------------------------------------
class Particle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.vx = random.uniform(-60, 60)
        self.vy = random.uniform(-60, 60)
        self.life = random.uniform(0.3, 0.7)
        self.max_life = self.life

    def update(self, dt):
        self.x += self.vx * dt
        self.y += self.vy * dt
        self.life -= dt

    def draw(self, surface, cx, cy):
        alpha = max(0, self.life / self.max_life)
        r = int(2 + 4 * alpha)
        safe_circle(surface, (int(200 + 55 * alpha), int(230 + 25 * alpha), 255), (cx, cy), r)


# ----------------------------------------------------------------------------
# 摄像机
# ----------------------------------------------------------------------------
class Camera:
    def __init__(self):
        self.x = WORLD_W / 2
        self.y = WORLD_H / 2

    def follow(self, target):
        self.x += (target.x - self.x) * 0.1
        self.y += (target.y - self.y) * 0.1

    def to_screen(self, wx, wy):
        return (wx - self.x + SCREEN_W / 2, wy - self.y + SCREEN_H / 2)


class Button:
    def __init__(self, x, y, w, h, label, key):
        self.rect = pygame.Rect(x, y, w, h)
        self.label = label
        self.key = key
        self.down = False

    def hit(self, px, py):
        return self.rect.collidepoint(px, py)


# ----------------------------------------------------------------------------
# 游戏主体
# ----------------------------------------------------------------------------
class Game:
    def __init__(self):
        pygame.init()
        try:
            self.screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
            pygame.display.set_caption("航海模拟器 Sailing Simulator")
        except Exception:
            self.screen = None
        self.clock = pygame.time.Clock()
        self.font_big = make_font(36)
        self.font = make_font(22)
        self.font_small = make_font(16)
        self.font_icon = make_font(18)
        self.keys_down = set()
        self.buttons = [
            Button(20, SCREEN_H - 90, 44, 40, "W", pygame.K_w),
            Button(20, SCREEN_H - 46, 44, 40, "S", pygame.K_s),
            Button(72, SCREEN_H - 90, 44, 40, "A", pygame.K_a),
            Button(124, SCREEN_H - 90, 44, 40, "D", pygame.K_d),
        ]
        self.fatal = None
        self.reset()

    def reset(self):
        self.wind = Wind()
        self.boat = Boat(WORLD_W / 2, WORLD_H / 2)
        self.camera = Camera()
        self.rocks = []
        self.islands = []
        self.lighthouses = []
        self.clouds = []
        self.seagulls = []
        self.supplies = []
        self.particles = []
        self.score = 0
        self.distance = 0.0
        self.game_over = False
        self.paused = False
        self.last_boat_pos = (self.boat.x, self.boat.y)
        self.trail = []
        for _ in range(ROCK_MAX):
            self._spawn_rock()
        for _ in range(ISLAND_MAX):
            self._spawn_island()
        for _ in range(LIGHTHOUSE_MAX):
            self._spawn_lighthouse()
        for _ in range(CLOUD_MAX):
            self.clouds.append(Cloud.make(random.uniform(0, WORLD_W), random.uniform(60, 500)))
        for _ in range(SEAGULL_MAX):
            self.seagulls.append(Seagull.make(random.uniform(0, WORLD_W), random.uniform(80, 400)))
        for _ in range(SUPPLY_MAX):
            self._spawn_supply()

    def _rand_around(self, rx, ry):
        x = self.boat.x + random.uniform(-rx, rx)
        y = self.boat.y + random.uniform(-ry, ry)
        return (max(60, min(WORLD_W - 60, x)), max(60, min(WORLD_H - 60, y)))

    def _spawn_rock(self):
        x, y = self._rand_around(2400, 1700)
        if math.hypot(x - self.boat.x, y - self.boat.y) > 220:
            self.rocks.append(Rock.make(x, y))

    def _spawn_island(self):
        x, y = self._rand_around(2800, 2000)
        if math.hypot(x - self.boat.x, y - self.boat.y) > 500:
            self.islands.append(Island.make(x, y))

    def _spawn_lighthouse(self):
        x, y = self._rand_around(3200, 2200)
        if math.hypot(x - self.boat.x, y - self.boat.y) > 600:
            self.lighthouses.append(Lighthouse(x, y))

    def _spawn_supply(self):
        x, y = self._rand_around(1900, 1400)
        self.supplies.append(Supply.make(x, y))

    # ---------------- 输入 ----------------
    def read_input(self, event):
        if event.type == pygame.KEYDOWN:
            self.keys_down.add(event.key)
        elif event.type == pygame.KEYUP:
            self.keys_down.discard(event.key)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            for b in self.buttons:
                if b.hit(*event.pos):
                    b.down = True
                    self.keys_down.add(b.key)
        elif event.type == pygame.MOUSEBUTTONUP:
            for b in self.buttons:
                if b.down:
                    b.down = False
                    self.keys_down.discard(b.key)

    def input_state(self):
        left = pygame.K_a in self.keys_down
        right = pygame.K_d in self.keys_down
        up = pygame.K_w in self.keys_down
        down = pygame.K_s in self.keys_down
        boost = pygame.K_SPACE in self.keys_down
        if self.screen is not None:
            try:
                p = pygame.key.get_pressed()
                left = left or p[pygame.K_LEFT] or p[pygame.K_a]
                right = right or p[pygame.K_RIGHT] or p[pygame.K_d]
                up = up or p[pygame.K_UP] or p[pygame.K_w]
                down = down or p[pygame.K_DOWN] or p[pygame.K_s]
                boost = boost or p[pygame.K_SPACE]
            except Exception:
                pass
        return left, right, up, down, boost

    # ---------------- 主循环 ----------------
    def run(self):
        running = True
        while running:
            dt = self.clock.tick(FPS) / 1000.0
            if dt <= 0:
                dt = 1.0 / FPS
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                else:
                    self.read_input(event)
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            running = False
                        elif event.key == pygame.K_p and not self.game_over:
                            self.paused = not self.paused
                        elif event.key == pygame.K_r:
                            self.reset()
            try:
                if self.screen is None:
                    self.screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
            except Exception:
                self.screen = None
            if not self.paused and not self.game_over:
                self.update(dt)
            self.draw()
            if self.screen is not None:
                try:
                    pygame.display.flip()
                except Exception:
                    pass
        try:
            pygame.quit()
        except Exception:
            pass

    # ---------------- 逻辑更新 ----------------
    def update(self, dt):
        left, right, up, down, boost = self.input_state()
        self.wind.update(dt)
        result = self.boat.update(dt, self.wind, left, right, up, down, boost)

        moved = math.hypot(self.boat.x - self.last_boat_pos[0], self.boat.y - self.last_boat_pos[1])
        self.distance += moved
        self.score += moved * 0.1
        self.last_boat_pos = (self.boat.x, self.boat.y)

        if abs(self.boat.speed) > 1.5:
            self.trail.append((self.boat.x, self.boat.y))
            if len(self.trail) > 24:
                self.trail.pop(0)
        elif self.trail:
            self.trail.pop(0)

        if result == "honk":
            for _ in range(16):
                self.particles.append(Particle(self.boat.x, self.boat.y))

        self.camera.follow(self.boat)
        for c in self.clouds:
            c.update(dt)
        for g in self.seagulls:
            g.update(dt)

        self.rocks = [r for r in self.rocks if math.hypot(r.x - self.boat.x, r.y - self.boat.y) < 2800]
        while len(self.rocks) < ROCK_MAX:
            self._spawn_rock()
            if len(self.rocks) >= ROCK_MAX:
                break
        self.islands = [i for i in self.islands if math.hypot(i.x - self.boat.x, i.y - self.boat.y) < 3200]
        while len(self.islands) < ISLAND_MAX:
            self._spawn_island()
            if len(self.islands) >= ISLAND_MAX:
                break
        self.lighthouses = [l for l in self.lighthouses if math.hypot(l.x - self.boat.x, l.y - self.boat.y) < 3600]
        while len(self.lighthouses) < LIGHTHOUSE_MAX:
            self._spawn_lighthouse()
            if len(self.lighthouses) >= LIGHTHOUSE_MAX:
                break
        self.supplies = [s for s in self.supplies if math.hypot(s.x - self.boat.x, s.y - self.boat.y) < 2400]
        while len(self.supplies) < SUPPLY_MAX:
            self._spawn_supply()
            if len(self.supplies) >= SUPPLY_MAX:
                break

        for s in self.supplies[:]:
            s.update(dt)
            if math.hypot(s.x - self.boat.x, s.y - self.boat.y) < self.boat.boat_len + s.r:
                self._apply_supply(s)
                self.supplies.remove(s)

        for r in self.rocks:
            d = math.hypot(r.x - self.boat.x, r.y - self.boat.y)
            if d < r.r + self.boat.boat_wid:
                self.boat.damage(abs(self.boat.speed) * 7 + 4)
                self.boat.speed *= -0.3
                for _ in range(10):
                    self.particles.append(Particle(self.boat.x, self.boat.y))
                break

        for il in self.islands:
            d = math.hypot(il.x - self.boat.x, il.y - self.boat.y)
            if d < il.r:
                self.boat.damage(6)
                ang = math.atan2(self.boat.y - il.y, self.boat.x - il.x)
                self.boat.x = il.x + math.cos(ang) * (il.r + 4)
                self.boat.y = il.y + math.sin(ang) * (il.r + 4)
                self.boat.speed *= -0.4
                break

        for p in self.particles[:]:
            p.update(dt)
            if p.life <= 0:
                self.particles.remove(p)

        if self.boat.hp <= 0:
            self.game_over = True

    def _apply_supply(self, s):
        if s.kind == "repair":
            self.boat.hp = min(BOAT_MAX_HP, self.boat.hp + 25)
            self.score += 20
        elif s.kind == "boost":
            self.boat.speed = min(BOAT_MAX_SPEED, self.boat.speed + 2.5)
            self.score += 15
        elif s.kind == "coin":
            self.score += 100

    # ---------------- 绘制 ----------------
    def draw(self):
        surface = self.screen
        if surface is None:
            return
        try:
            self._draw_scene(surface)
        except Exception:
            print("绘制出错:\n" + traceback.format_exc())
            try:
                surface.fill(COLOR_SEA)
                safe_text(surface, self.font, "绘制出错, 详见控制台", (20, 20), COLOR_WHITE)
            except Exception:
                pass

    def _draw_scene(self, surface):
        w, h = surface.get_size()
        surface.fill(COLOR_SEA)
        t = pygame.time.get_ticks() / 1000.0

        for i in range(0, w, 80):
            for j in range(0, h, 80):
                ox = math.sin(t + i * 0.05 + j * 0.03) * 6
                oy = math.cos(t * 0.8 + j * 0.05) * 6
                safe_line(surface, COLOR_SEA_DEEP, (i + ox, j + oy), (i + 20 + ox, j + oy), 1)
                if (i // 80 + j // 80) % 3 == 0:
                    safe_circle(surface, COLOR_FOAM,
                                (i + 40 + math.sin(t * 1.2 + j * 0.1) * 8,
                                 j + 40 + math.cos(t + i * 0.1) * 8), 1)

        def to_screen(wx, wy):
            return (wx - self.camera.x + w / 2, wy - self.camera.y + h / 2)

        for c in self.clouds:
            sx, sy = to_screen(c.x, c.y)
            if -120 < sx < w + 120 and -80 < sy < h + 80:
                c.draw(surface, sx, sy)
        for il in self.islands:
            sx, sy = to_screen(il.x, il.y)
            if -200 < sx < w + 200 and -200 < sy < h + 200:
                il.draw(surface, sx, sy, t)
        for lh in self.lighthouses:
            sx, sy = to_screen(lh.x, lh.y)
            if -120 < sx < w + 120 and -160 < sy < h + 160:
                lh.draw(surface, sx, sy, t)
        for r in self.rocks:
            sx, sy = to_screen(r.x, r.y)
            if -100 < sx < w + 100 and -100 < sy < h + 100:
                r.draw(surface, sx, sy)
        for s in self.supplies:
            sx, sy = to_screen(s.x, s.y)
            if -50 < sx < w + 50 and -50 < sy < h + 50:
                s.draw(surface, sx, sy, self.font_icon)

        for i, (wx, wy) in enumerate(self.trail):
            sx, sy = to_screen(wx, wy)
            a = i / max(1, len(self.trail))
            safe_circle(surface, (200, 230, 250), (sx, sy), int(3 + 6 * a))

        for p in self.particles:
            sx, sy = to_screen(p.x, p.y)
            p.draw(surface, sx, sy)

        bsx, bsy = to_screen(self.boat.x, self.boat.y)
        self.boat.draw(surface, bsx, bsy)

        for g in self.seagulls:
            sx, sy = to_screen(g.x, g.y)
            if -60 < sx < w + 60 and -60 < sy < h + 60:
                g.draw(surface, sx, sy)

        for b in self.buttons:
            b.rect.topleft = (b.rect.x, h - 90) if b.rect.y > h - 60 else b.rect.topleft
            col = (90, 170, 240) if b.down else (50, 110, 170)
            safe_poly(surface, col, [(b.rect.left, b.rect.top), (b.rect.right, b.rect.top),
                                     (b.rect.right, b.rect.bottom), (b.rect.left, b.rect.bottom)])
            safe_poly(surface, COLOR_WHITE, [(b.rect.left, b.rect.top), (b.rect.right, b.rect.top),
                                             (b.rect.right, b.rect.bottom), (b.rect.left, b.rect.bottom)], 2)
            safe_text(surface, self.font_small, b.label, (b.rect.x + 16, b.rect.y + 12), COLOR_WHITE)

        self._draw_hud(surface, w, h)
        self._draw_compass(surface, w)

        if self.paused and not self.game_over:
            self._center_text(surface, w, h, "暂停中  PAUSED", "按 P 继续")
        if self.game_over:
            self._center_text(surface, w, h, "船只沉没！", "最终得分 %d   按 R 重新开始" % int(self.score))

    def _draw_hud(self, surface, w, h):
        panel = safe_aalpha(250, 158)
        if panel is not None:
            panel.fill((10, 30, 50, 150))
            surface.blit(panel, (12, 12))
        else:
            safe_poly(surface, (10, 30, 50), [(12, 12), (262, 12), (262, 170), (12, 170)])
        safe_text(surface, self.font_big, "得分 %d" % int(self.score), (24, 18), COLOR_WHITE)
        safe_text(surface, self.font, "航程 %d m" % int(self.distance), (24, 54), COLOR_BLUE)
        safe_poly(surface, COLOR_DARK, [(24, 82), (204, 82), (204, 96), (24, 96)])
        ratio = self.boat.hp / BOAT_MAX_HP
        col = COLOR_GREEN if ratio > 0.4 else COLOR_RED
        safe_poly(surface, col, [(24, 82), (24 + int(180 * ratio), 82),
                                 (24 + int(180 * ratio), 96), (24, 96)])
        safe_text(surface, self.font_small, "船体", (24, 100), COLOR_WHITE)
        state = "静止"
        if self.boat.speed > 0.2:
            state = "前进"
        elif self.boat.speed < -0.2:
            state = "后退"
        safe_text(surface, self.font_small, "%s  航速 %.1f" % (state, self.boat.speed), (24, 120), COLOR_WHITE)
        keys = []
        if pygame.K_a in self.keys_down:
            keys.append("A")
        if pygame.K_d in self.keys_down:
            keys.append("D")
        if pygame.K_w in self.keys_down:
            keys.append("W")
        if pygame.K_s in self.keys_down:
            keys.append("S")
        safe_text(surface, self.font_small, "按键: " + ("".join(keys) if keys else "无"),
                  (24, 140), (180, 220, 255))
        safe_text(surface, self.font_small, "A/D转向  W前进  S后退  空格冲刺  P暂停  R重开",
                  (12, h - 22), (180, 210, 230))

    def _draw_compass(self, surface, w):
        cx, cy = w - 80, 90
        r = 46
        safe_circle(surface, (10, 30, 50), (cx, cy), r + 6)
        safe_circle(surface, COLOR_DARK, (cx, cy), r)
        safe_circle(surface, COLOR_SEA_LIGHT, (cx, cy), r - 4)
        safe_arrow(surface, COLOR_GOLD, cx, cy, self.wind.angle + math.pi, r - 10, 3, 12)
        safe_arrow(surface, COLOR_GREEN, cx, cy, self.boat.heading, r - 16, 2, 9)
        safe_text(surface, self.font_small, "风向/船头", (cx - 34, cy + r + 8), COLOR_WHITE)
        safe_text(surface, self.font_small, "风力 x%.1f" % self.wind.strength, (cx - 34, cy + r + 24), COLOR_GOLD)

    def _center_text(self, surface, w, h, title, subtitle):
        overlay = safe_aalpha(w, h)
        if overlay is not None:
            overlay.fill((0, 0, 0, 120))
            surface.blit(overlay, (0, 0))
        safe_text(surface, self.font_big, title, (w / 2 - 90, h / 2 - 40), COLOR_GOLD)
        safe_text(surface, self.font, subtitle, (w / 2 - 140, h / 2 + 6), COLOR_WHITE)


# ----------------------------------------------------------------------------
def main():
    game = None
    try:
        game = Game()
        game.run()
    except Exception:
        print("运行出错:\n" + traceback.format_exc())
        if game is not None and game.screen is not None:
            try:
                game.screen.fill(COLOR_SEA)
                safe_text(game.screen, game.font, "运行出错, 详见控制台", (20, 20), COLOR_WHITE)
                pygame.display.flip()
                pygame.time.delay(3000)
            except Exception:
                pass


if __name__ == "__main__":
    main()
