import pygame
import random
import math
import sys

# =========================
# 基础设置
# =========================
WIDTH, HEIGHT = 1100, 680
FPS = 60

TITLE = "潜水员戴夫 - 开阔海域版"

OCEAN_TOP = pygame.Color(48, 170, 220)
OCEAN_MID = pygame.Color(12, 92, 150)
OCEAN_DEEP = pygame.Color(4, 25, 62)
ABYSS = pygame.Color(2, 8, 28)

WHITE = pygame.Color(238, 250, 255)
LIGHT = pygame.Color(150, 230, 255)
YELLOW = pygame.Color(255, 210, 75)
ORANGE = pygame.Color(255, 125, 55)
RED = pygame.Color(230, 80, 70)
GREEN = pygame.Color(80, 220, 135)
CYAN = pygame.Color(70, 220, 255)
PURPLE = pygame.Color(165, 105, 235)
DARK = pygame.Color(8, 20, 34)
SAND = pygame.Color(215, 188, 125)
SAND_DARK = pygame.Color(172, 140, 82)

pygame.init()
pygame.display.set_caption(TITLE)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

FONT_NAME = "microsoftyahei,pingfangsc,notosanscjk,wenquanyimicrohei,sansserif"
font = pygame.font.SysFont(FONT_NAME, 22)
small_font = pygame.font.SysFont(FONT_NAME, 17)
tiny_font = pygame.font.SysFont(FONT_NAME, 14)
big_font = pygame.font.SysFont(FONT_NAME, 42)
huge_font = pygame.font.SysFont(FONT_NAME, 56)


# =========================
# 工具函数
# =========================
def clamp(v, lo, hi):
    return max(lo, min(hi, v))


def dist(a, b):
    return math.hypot(a.x - b.x, a.y - b.y)


def to_rgb(color):
    """把 RGB / RGBA / pygame.Color 统一转成 RGB 三元组。"""
    try:
        if len(color) == 4:
            return color[0], color[1], color[2]
        return color[0], color[1], color[2]
    except Exception:
        return 255, 255, 255


def with_alpha(color, alpha):
    r, g, b = to_rgb(color)
    return (r, g, b, clamp(alpha, 0, 255))


def draw_rounded_panel(surface, rect, color=(8, 35, 60), alpha=160, border=None):
    s = pygame.Surface(rect.size, pygame.SRCALPHA)
    pygame.draw.rect(
        s,
        with_alpha(color, alpha),
        (0, 0, rect.width, rect.height),
        border_radius=14
    )

    if border:
        pygame.draw.rect(
            s,
            border,
            (0, 0, rect.width, rect.height),
            width=2,
            border_radius=14
        )

    surface.blit(s, rect.topleft)


def draw_text(surface, text, x, y, color=WHITE, f=None, center=False):
    f = f or font
    img = f.render(str(text), True, to_rgb(color))
    r = img.get_rect()

    if center:
        r.center = (x, y)
    else:
        r.topleft = (x, y)

    surface.blit(img, r)
    return r


def draw_bar(surface, rect, value, max_value, color, label):
    pygame.draw.rect(surface, (0, 0, 0, 90), rect, border_radius=8)

    inner = rect.inflate(-8, -8)
    pct = clamp(value / max_value, 0, 1)
    fill = pygame.Rect(inner.left, inner.top, int(inner.width * pct), inner.height)

    pygame.draw.rect(surface, to_rgb(color), fill, border_radius=5)
    pygame.draw.rect(surface, (190, 235, 255), rect, 2, border_radius=8)

    draw_text(surface, label, rect.left + 10, rect.top + 3, WHITE, small_font)


def blend_color(colors, p):
    p = clamp(p, 0, 1)
    n = len(colors) - 1
    x = p * n
    i = int(x)

    if i >= n:
        return colors[-1]

    return colors[i].lerp(colors[i + 1], x - i)


# =========================
# 区域设置
# =========================
REGIONS = [
    {
        "name": "浅蓝珊瑚礁",
        "depth_name": "近海浅滩",
        "theme": OCEAN_TOP,
        "danger": 0.3,
        "unlock": 0,
        "fish_weights": {
            "goby": 50,
            "clown": 23,
            "angel": 15,
            "blow": 8,
            "star": 4
        },
        "pearl_chance": 0.55,
        "oxygen_drain": 0.55
    },
    {
        "name": "沉船沙谷",
        "depth_name": "沉船区",
        "theme": pygame.Color(25, 125, 175),
        "danger": 0.7,
        "unlock": 180,
        "fish_weights": {
            "goby": 28,
            "clown": 20,
            "angel": 20,
            "blow": 16,
            "eel": 7,
            "star": 6,
            "treasure": 3
        },
        "pearl_chance": 0.7,
        "oxygen_drain": 0.75
    },
    {
        "name": "紫光海沟",
        "depth_name": "深海边缘",
        "theme": pygame.Color(18, 55, 115),
        "danger": 1.25,
        "unlock": 450,
        "fish_weights": {
            "angel": 18,
            "blow": 18,
            "eel": 18,
            "ray": 13,
            "star": 13,
            "jelly": 12,
            "treasure": 8
        },
        "pearl_chance": 0.9,
        "oxygen_drain": 1.05
    },
    {
        "name": "幽蓝深渊",
        "depth_name": "深渊入口",
        "theme": pygame.Color(5, 14, 45),
        "danger": 1.8,
        "unlock": 850,
        "fish_weights": {
            "eel": 20,
            "ray": 17,
            "jelly": 18,
            "shark": 10,
            "ghost": 12,
            "star": 10,
            "treasure": 13
        },
        "pearl_chance": 1.15,
        "oxygen_drain": 1.35
    }
]

# =========================
# 鱼类资料
# =========================
FISH_DATA = {
    "goby": {
        "name": "小蓝鱼",
        "value": 10,
        "radius": 17,
        "escape": 1.0,
        "speed_min": 28,
        "speed_max": 55,
        "color": (55, 150, 230)
    },
    "clown": {
        "name": "橙纹小丑鱼",
        "value": 18,
        "radius": 17,
        "escape": 1.1,
        "speed_min": 25,
        "speed_max": 48,
        "color": (245, 120, 55)
    },
    "angel": {
        "name": "黄金神仙鱼",
        "value": 30,
        "radius": 23,
        "escape": 1.35,
        "speed_min": 22,
        "speed_max": 42,
        "color": (255, 205, 70)
    },
    "blow": {
        "name": "斑点河豚",
        "value": 24,
        "radius": 20,
        "escape": 1.2,
        "speed_min": 18,
        "speed_max": 35,
        "color": (230, 155, 65)
    },
    "eel": {
        "name": "蓝纹海鳗",
        "value": 42,
        "radius": 24,
        "escape": 1.7,
        "speed_min": 35,
        "speed_max": 62,
        "color": (70, 225, 185)
    },
    "ray": {
        "name": "蓝斑鳐鱼",
        "value": 65,
        "radius": 31,
        "escape": 1.9,
        "speed_min": 25,
        "speed_max": 48,
        "color": (80, 120, 225)
    },
    "jelly": {
        "name": "紫光水母",
        "value": 38,
        "radius": 22,
        "escape": 1.25,
        "speed_min": 12,
        "speed_max": 26,
        "color": (175, 100, 235)
    },
    "shark": {
        "name": "灰礁鲨",
        "value": 120,
        "radius": 38,
        "escape": 2.6,
        "speed_min": 42,
        "speed_max": 78,
        "color": (100, 125, 145)
    },
    "ghost": {
        "name": "幽灵帆鳍鱼",
        "value": 95,
        "radius": 30,
        "escape": 2.25,
        "speed_min": 30,
        "speed_max": 58,
        "color": (145, 230, 220)
    },
    "star": {
        "name": "星光鮨",
        "value": 80,
        "radius": 22,
        "escape": 1.65,
        "speed_min": 35,
        "speed_max": 65,
        "color": (115, 235, 255)
    },
    "treasure": {
        "name": "稀有宝箱鱼",
        "value": 160,
        "radius": 28,
        "escape": 2.4,
        "speed_min": 18,
        "speed_max": 36,
        "color": (255, 175, 90)
    }
}


# =========================
# 背景
# =========================
class Background:
    def __init__(self):
        self.bubbles = []

        for _ in range(90):
            self.bubbles.append(self.make_bubble(True))

        self.t = 0

    def make_bubble(self, anywhere=False):
        return {
            "x": random.randrange(0, WIDTH),
            "y": random.randrange(0, HEIGHT) if anywhere else HEIGHT + random.randint(10, 80),
            "r": random.randint(2, 7),
            "speed": random.uniform(18, 60),
            "drift": random.uniform(-14, 14),
            "phase": random.uniform(0, math.pi * 2)
        }

    def update(self, dt):
        self.t += dt

        for b in self.bubbles:
            b["y"] -= b["speed"] * dt
            b["x"] += (b["drift"] + math.sin(self.t * 2 + b["phase"]) * 8) * dt

            if b["y"] < -30 or b["x"] < -40 or b["x"] > WIDTH + 40:
                b.update(self.make_bubble(False))

    def draw_ocean(self, surface, region_index, camera_y, player_y):
        region = REGIONS[region_index]
        p = clamp((player_y - 90) / 470, 0, 1)

        colors = [OCEAN_TOP, region["theme"], OCEAN_MID, OCEAN_DEEP]

        if region_index >= 2:
            colors.append(ABYSS)

        grad = pygame.Surface((1, HEIGHT))

        for y in range(HEIGHT):
            k = clamp((y / HEIGHT) * 0.75 + p * 0.35, 0, 1)
            grad.set_at((0, y), blend_color(colors, k))

        surface.blit(pygame.transform.scale(grad, (WIDTH, HEIGHT)), (0, 0))

        # 水层线
        layer_surf = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)

        for i in range(11):
            y = 55 + i * 58 + math.sin(self.t * 0.65 + i) * 5 - camera_y * 0.035
            alpha = 12 if region_index < 2 else 8
            pygame.draw.line(
                layer_surf,
                (150, 230, 255, alpha),
                (0, y),
                (WIDTH, y),
                2
            )

        surface.blit(layer_surf, (0, 0))

        # 海面
        if region_index <= 1:
            wave_surf = pygame.Surface((WIDTH, 160), pygame.SRCALPHA)

            for x in range(0, WIDTH, 34):
                h = 15 + 9 * math.sin(self.t * 1.5 + x * 0.035)
                pygame.draw.arc(
                    wave_surf,
                    (220, 250, 255, 45),
                    (x, 12, 38, 60),
                    math.pi,
                    math.pi * 2,
                    2
                )
                pygame.draw.line(
                    wave_surf,
                    (190, 240, 255, 25),
                    (x, 52 + h * 0.2),
                    (x + 30, 52 + h * 0.2),
                    2
                )

            surface.blit(wave_surf, (0, 5 - camera_y * 0.04))

        # 光束
        beam_surf = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        beam_alpha = 20 - region_index * 4

        for i in range(8):
            x = 60 + i * 145 + math.sin(self.t * 0.5 + i) * 20
            points = [
                (x, 0),
                (x + 36, 0),
                (x + 230 + i * 10, HEIGHT),
                (x - 95 - i * 7, HEIGHT)
            ]
            pygame.draw.polygon(
                beam_surf,
                (135, 225, 255, max(6, beam_alpha)),
                points
            )

        surface.blit(beam_surf, (0, 0))

        # 区域装饰
        if region_index == 1:
            self.draw_wreck(surface, camera_y)
        elif region_index == 2:
            self.draw_trench(surface, camera_y)
        elif region_index == 3:
            self.draw_abyss(surface, camera_y)

        # 气泡
        bubble_surf = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)

        for b in self.bubbles:
            pygame.draw.circle(
                bubble_surf,
                (145, 230, 255, 55),
                (int(b["x"]), int(b["y"])),
                b["r"],
                1
            )
            pygame.draw.circle(
                bubble_surf,
                (255, 255, 255, 35),
                (int(b["x"] - b["r"] * 0.3), int(b["y"] - b["r"] * 0.3)),
                max(1, b["r"] // 3)
            )

        surface.blit(bubble_surf, (0, 0))

        # 海床
        floor_y = HEIGHT - 72
        sand = pygame.Surface((WIDTH, 100), pygame.SRCALPHA)
        points = [(0, 45)]

        for x in range(0, WIDTH + 30, 30):
            yy = 38 + 12 * math.sin(x * 0.018) + 5 * math.sin(x * 0.063)
            points.append((x, yy))

        points += [(WIDTH, 100), (0, 100)]
        pygame.draw.polygon(sand, SAND, points)

        for x in range(0, WIDTH, 18):
            pygame.draw.line(sand, SAND_DARK, (x, 62), (x + 8, 91), 2)

        surface.blit(sand, (0, floor_y - 22))

    def draw_wreck(self, surface, camera_y):
        y = HEIGHT - 165 - camera_y * 0.04
        s = pygame.Surface((360, 120), pygame.SRCALPHA)

        pygame.draw.polygon(
            s,
            (65, 65, 58, 160),
            [(20, 75), (260, 75), (315, 98), (5, 98)]
        )
        pygame.draw.rect(s, (55, 55, 50, 150), (70, 25, 150, 55), border_radius=8)
        pygame.draw.rect(s, (25, 35, 42, 150), (92, 37, 25, 25), border_radius=4)
        pygame.draw.rect(s, (25, 35, 42, 150), (132, 37, 25, 25), border_radius=4)
        pygame.draw.rect(s, (25, 35, 42, 150), (172, 37, 25, 25), border_radius=4)
        pygame.draw.line(s, (35, 45, 48, 160), (260, 72), (330, 20), 6)

        surface.blit(s, (120, y))

    def draw_trench(self, surface, camera_y):
        s = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)

        for i in range(6):
            x = 70 + i * 185
            points = [(x, HEIGHT), (x + 55, 210), (x + 105, HEIGHT)]
            pygame.draw.polygon(s, (3, 12, 35, 70), points)
            pygame.draw.polygon(s, (55, 65, 100, 20), points)

        surface.blit(s, (0, -camera_y * 0.04))

    def draw_abyss(self, surface, camera_y):
        s = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)

        for i in range(24):
            x = (i * 83 + math.sin(self.t + i) * 10) % WIDTH
            y = (i * 47 - camera_y * 0.04) % HEIGHT
            pygame.draw.circle(
                s,
                (80, 160, 190, 16),
                (x, y),
                35 + 12 * math.sin(self.t + i)
            )

        surface.blit(s, (0, 0))


# =========================
# 玩家
# =========================
class Player:
    def __init__(self, x=WIDTH // 2, y=HEIGHT // 2):
        self.x = x
        self.y = y
        self.vx = 0
        self.vy = 0
        self.radius = 24

        self.max_oxygen = 100
        self.oxygen = self.max_oxygen
        self.health = 100
        self.stamina = 100

        self.coins = 0
        self.inventory = []

        self.facing = 1
        self.anim = 0
        self.dash_cd = 0

        self.speed_level = 0
        self.tank_level = 0
        self.catch_level = 0
        self.fins_level = 0

    @property
    def move_speed(self):
        return 215 + self.speed_level * 28

    @property
    def vertical_speed(self):
        return 185 + self.fins_level * 24

    @property
    def dash_speed(self):
        return self.move_speed * (1.72 + self.fins_level * 0.07)

    @property
    def catch_power(self):
        return 1 + self.catch_level * 0.18

    def update(self, keys, dt, region):
        self.anim += dt
        self.vx = 0
        self.vy = 0

        if self.dash_cd > 0:
            self.dash_cd -= dt

        move_speed = self.move_speed
        v_speed = self.vertical_speed

        if keys[pygame.K_SPACE] and self.stamina >= 22 and self.dash_cd <= 0:
            move_speed = self.dash_speed
            v_speed = self.vertical_speed * 1.35
            self.stamina -= 30 * dt
            self.dash_cd = 0.34
        else:
            self.stamina = min(100, self.stamina + 15 * dt)

        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.vx -= move_speed
            self.facing = -1

        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.vx += move_speed
            self.facing = 1

        if keys[pygame.K_UP] or keys[pygame.K_w]:
            self.vy -= v_speed

        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            self.vy += v_speed

        self.x += self.vx * dt
        self.y += self.vy * dt

        self.x = clamp(self.x, 42, WIDTH - 42)
        self.y = clamp(self.y, 68, HEIGHT - 95)

        drain = region["oxygen_drain"]
        self.oxygen -= drain * dt

        # 越深越耗氧
        depth_pressure = clamp((self.y - 220) / 360, 0, 1.7)
        self.oxygen -= depth_pressure * 0.8 * dt

        if self.oxygen <= 0:
            self.oxygen = 0
            self.health -= 6 * dt

    def draw(self, surface):
        x, y = int(self.x), int(self.y)
        bob = math.sin(self.anim * 5) * 3
        flip = self.facing

        # 尾迹气泡
        for i in range(3):
            bx = x - flip * (19 + i * 6) + math.sin(self.anim * 7 + i) * 4
            by = y - 35 + i * 11 + bob
            pygame.draw.circle(surface, (155, 235, 255, 65), (int(bx), int(by)), 3 + i)

        # 脚蹼
        leg_swing = math.sin(self.anim * 6) * 5
        pygame.draw.line(
            surface,
            (25, 45, 65),
            (x - 8, y + 14),
            (x - 10, y + 31 + leg_swing),
            6
        )
        pygame.draw.line(
            surface,
            (25, 45, 65),
            (x + 8, y + 14),
            (x + 10, y + 31 - leg_swing),
            6
        )

        fin_color = (20, 170, 195) if self.fins_level == 0 else (40, 220, 210)
        pygame.draw.ellipse(
            surface,
            fin_color,
            (x - flip * 24, y + 29 + leg_swing, 19 * flip, 8)
        )
        pygame.draw.ellipse(
            surface,
            fin_color,
            (x + 5 - flip * 24, y + 27 - leg_swing, 19 * flip, 8)
        )

        # 身体
        body = pygame.Surface((46, 48), pygame.SRCALPHA)
        suit_color = ORANGE if self.speed_level < 2 else (255, 95, 75)

        pygame.draw.ellipse(body, to_rgb(suit_color), (2, 3, 41, 39))
        pygame.draw.ellipse(body, (225, 85, 35), (7, 8, 31, 28))
        pygame.draw.arc(body, to_rgb(YELLOW), (8, 12, 26, 18), 0.2, 2.7, 3)
        pygame.draw.rect(body, (45, 70, 85), (18, 38, 10, 10), border_radius=3)

        if flip == 1:
            surface.blit(body, (x - 23, y - 12 + bob))
        else:
            surface.blit(pygame.transform.flip(body, True, False), (x - 23, y - 12 + bob))

        # 手臂
        arm_y = y + 5 + bob
        pygame.draw.line(
            surface,
            to_rgb(suit_color),
            (x - 18 * flip, arm_y),
            (x - 30 * flip, arm_y + 14),
            7
        )
        pygame.draw.line(
            surface,
            to_rgb(suit_color),
            (x + 18 * flip, arm_y),
            (x + 29 * flip, arm_y - 10),
            7
        )

        # 头
        head_x = x + flip * 4
        head_y = y - 27 + bob
        pygame.draw.circle(surface, (230, 168, 120), (head_x, head_y), 15)
        pygame.draw.circle(surface, (28, 55, 70), (head_x + flip * 3, head_y - 2), 12)
        pygame.draw.circle(surface, (120, 225, 255), (head_x + flip * 5, head_y - 2), 8)
        pygame.draw.circle(surface, (240, 255, 255), (head_x + flip * 7, head_y - 4), 2)
        pygame.draw.circle(surface, (40, 75, 90), (head_x - flip * 10, head_y + 4), 5)
        pygame.draw.arc(
            surface,
            (80, 50, 35),
            (head_x - 4, head_y + 3, 12, 8),
            0.15,
            2.8,
            2
        )

        # 氧气瓶
        tank_color = (115, 130, 140) if self.tank_level == 0 else (125, 205, 220)
        tank_x = x - flip * 21
        pygame.draw.rect(
            surface,
            tank_color,
            (tank_x - 5, y - 23 + bob, 10, 32),
            border_radius=5
        )
        pygame.draw.rect(
            surface,
            (80, 95, 105),
            (tank_x - 3, y - 18 + bob, 6, 24),
            border_radius=3
        )
        pygame.draw.line(
            surface,
            (60, 75, 85),
            (tank_x + flip * 5, y - 13 + bob),
            (x - flip * 10, y - 15 + bob),
            2
        )


# =========================
# 鱼、珍珠、气泡补给
# =========================
class Fish:
    def __init__(self, x, y, kind):
        data = FISH_DATA[kind]

        self.kind = kind
        self.name = data["name"]
        self.value = data["value"]
        self.radius = data["radius"]
        self.escape = data["escape"]
        self.x = x
        self.y = y
        self.dir = random.choice([-1, 1])
        self.speed = random.uniform(data["speed_min"], data["speed_max"])
        self.phase = random.uniform(0, math.pi * 2)
        self.color = data["color"]

    def update(self, dt, t):
        self.x += self.dir * self.speed * dt
        self.y += math.sin(t * 1.6 + self.phase) * (8 + self.radius * 0.25) * dt

        if self.kind == "jelly":
            self.y += math.sin(t * 2.3 + self.phase) * 10 * dt

        if self.kind == "shark":
            self.y += math.sin(t * 0.8 + self.phase) * 5 * dt

        if self.x < 55:
            self.dir = 1

        if self.x > WIDTH - 55:
            self.dir = -1

        self.y = clamp(self.y, 95, HEIGHT - 102)

    def draw(self, surface, t):
        x, y = int(self.x), int(self.y)
        d = self.dir
        tail = math.sin(t * 7 + self.phase) * 5

        if self.kind == "ray":
            self.draw_ray(surface, x, y, d, tail)
            return

        if self.kind == "jelly":
            self.draw_jelly(surface, x, y, t)
            return

        if self.kind == "shark":
            self.draw_shark(surface, x, y, d, tail)
            return

        if self.kind == "eel":
            self.draw_eel(surface, x, y, d, t)
            return

        if self.kind == "treasure":
            self.draw_treasure_fish(surface, x, y, d, tail)
            return

        s = pygame.Surface((68, 48), pygame.SRCALPHA)

        pygame.draw.polygon(
            s,
            self.color,
            [(14, 24), (1, 11 + tail), (2, 35 - tail)]
        )
        pygame.draw.ellipse(s, self.color, (10, 8, 42, 30))
        pygame.draw.ellipse(s, (255, 255, 255, 55), (18, 12, 20, 9))
        pygame.draw.circle(s, to_rgb(DARK), (44, 18), 3)
        pygame.draw.polygon(s, self.color, [(26, 8), (34, 0), (41, 8)])
        pygame.draw.polygon(s, self.color, [(26, 36), (34, 44), (41, 36)])

        if self.kind == "clown":
            pygame.draw.rect(s, (255, 255, 255), (17, 12, 7, 25), border_radius=2)
            pygame.draw.rect(s, (255, 255, 255), (37, 12, 5, 25), border_radius=2)
            pygame.draw.rect(s, (255, 255, 255), (27, 9, 6, 5), border_radius=2)

        if self.kind == "angel":
            pygame.draw.rect(s, (210, 120, 30), (17, 13, 27, 3), border_radius=2)
            pygame.draw.rect(s, (210, 120, 30), (19, 28, 22, 3), border_radius=2)

        if self.kind == "blow":
            for px, py in [(21, 18), (31, 15), (36, 23), (23, 29), (33, 30)]:
                pygame.draw.circle(s, (80, 75, 60), (px, py), 2)

        if self.kind == "star":
            for px, py in [(22, 16), (31, 14), (40, 18), (36, 29), (25, 29)]:
                pygame.draw.circle(s, (255, 255, 255), (px, py), 2)

        if self.kind == "ghost":
            s.set_alpha(190)

        img = s if d == 1 else pygame.transform.flip(s, True, False)
        surface.blit(img, (x - 34, y - 24))

    def draw_ray(self, surface, x, y, d, tail):
        s = pygame.Surface((78, 58), pygame.SRCALPHA)

        pygame.draw.ellipse(s, self.color, (15, 18, 45, 20))
        pygame.draw.polygon(s, self.color, [(37, 18), (10, 5), (18, 31)])
        pygame.draw.polygon(s, self.color, [(37, 18), (64, 5), (56, 31)])
        pygame.draw.polygon(s, self.color, [(59, 25), (75, 13 + tail), (74, 36 - tail)])
        pygame.draw.circle(s, to_rgb(DARK), (51, 23), 3)

        for px in [28, 36, 44]:
            pygame.draw.circle(s, (140, 230, 255), (px, 25), 3)

        img = s if d == 1 else pygame.transform.flip(s, True, False)
        surface.blit(img, (x - 39, y - 29))

    def draw_jelly(self, surface, x, y, t):
        pulse = math.sin(t * 4 + self.phase) * 4

        pygame.draw.ellipse(
            surface,
            (175, 100, 235, 155),
            (x - 23, y - 18 + pulse, 46, 31)
        )
        pygame.draw.ellipse(
            surface,
            (225, 190, 255, 100),
            (x - 13, y - 11 + pulse, 26, 15)
        )

        for i in range(5):
            bx = x - 15 + i * 8
            pygame.draw.line(
                surface,
                (190, 130, 255, 130),
                (bx, y + 10 + pulse),
                (bx + math.sin(t * 5 + i) * 5, y + 31 + pulse),
                2
            )

    def draw_shark(self, surface, x, y, d, tail):
        s = pygame.Surface((92, 58), pygame.SRCALPHA)

        pygame.draw.ellipse(s, (105, 130, 150), (14, 14, 57, 28))
        pygame.draw.polygon(s, (80, 100, 120), [(68, 27), (88, 10 + tail), (86, 42 - tail)])
        pygame.draw.polygon(s, (75, 95, 115), [(28, 16), (38, 0), (49, 16)])
        pygame.draw.polygon(s, (85, 105, 125), [(24, 38), (33, 51), (44, 39)])
        pygame.draw.circle(s, to_rgb(DARK), (58, 22), 3)
        pygame.draw.line(s, (130, 160, 180), (20, 27), (63, 27), 2)
        pygame.draw.arc(s, (255, 255, 255), (42, 30, 13, 8), 0, 3.0, 2)

        img = s if d == 1 else pygame.transform.flip(s, True, False)
        surface.blit(img, (x - 46, y - 29))

    def draw_eel(self, surface, x, y, d, t):
        s = pygame.Surface((82, 38), pygame.SRCALPHA)

        for i in range(5):
            px = 12 + i * 12
            py = 19 + math.sin(t * 5 + i + self.phase) * 5
            pygame.draw.circle(
                s,
                self.color,
                (px, py),
                10 if i in [1, 2, 3] else 8
            )

        pygame.draw.circle(s, to_rgb(DARK), (62, 15), 3)
        pygame.draw.line(s, (30, 95, 125), (15, 19), (68, 18), 3)

        img = s if d == 1 else pygame.transform.flip(s, True, False)
        surface.blit(img, (x - 41, y - 19))

    def draw_treasure_fish(self, surface, x, y, d, tail):
        s = pygame.Surface((72, 50), pygame.SRCALPHA)

        pygame.draw.rect(s, (120, 75, 35), (18, 14, 32, 23), border_radius=4)
        pygame.draw.rect(s, (210, 160, 60), (18, 20, 32, 5))
        pygame.draw.circle(s, to_rgb(YELLOW), (34, 23), 4)
        pygame.draw.polygon(s, (210, 160, 60), [(16, 19), (7, 10 + tail), (8, 31 - tail)])
        pygame.draw.polygon(s, (210, 160, 60), [(49, 18), (63, 8 - tail), (62, 30 + tail)])

        img = s if d == 1 else pygame.transform.flip(s, True, False)
        surface.blit(img, (x - 36, y - 25))


class Pearl:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.radius = 14
        self.name = "闪光珍珠"
        self.value = 55
        self.phase = random.uniform(0, math.pi * 2)

    def update(self, dt, t):
        self.y += math.sin(t * 2 + self.phase) * 3 * dt

    def draw(self, surface, t):
        pulse = 1 + math.sin(t * 4 + self.phase) * 0.12
        r = int(self.radius * pulse)
        x, y = int(self.x), int(self.y)

        glow = pygame.Surface((74, 74), pygame.SRCALPHA)
        pygame.draw.circle(glow, (180, 240, 255, 35), (37, 37), 34)
        surface.blit(glow, (x - 37, y - 37))

        pygame.draw.circle(surface, (235, 245, 255), (x, y), r)
        pygame.draw.circle(surface, (160, 210, 230), (x - 4, y - 4), r - 5)
        pygame.draw.circle(surface, (255, 255, 255), (x - 6, y - 7), 3)


class AirPocket:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.radius = 43
        self.phase = random.uniform(0, math.pi * 2)
        self.name = "换气气泡"

    def update(self, dt, t):
        self.y += math.sin(t * 1.6 + self.phase) * 6 * dt

    def draw(self, surface, t):
        x, y = int(self.x), int(self.y)
        pulse = math.sin(t * 3 + self.phase) * 3

        glow = pygame.Surface((112, 112), pygame.SRCALPHA)
        pygame.draw.circle(glow, (100, 230, 255, 25), (56, 56), 52 + pulse)
        surface.blit(glow, (x - 56, y - 56))

        pygame.draw.circle(
            surface,
            (145, 235, 255, 90),
            (x, y),
            int(self.radius + pulse),
            3
        )
        pygame.draw.circle(
            surface,
            (90, 210, 240, 45),
            (x, y),
            int(self.radius - 8 + pulse),
            2
        )

        for i in range(7):
            bx = x + math.cos(t * 2 + i) * 19
            by = y + math.sin(t * 2.4 + i * 1.7) * 15
            pygame.draw.circle(surface, (210, 250, 255), (int(bx), int(by)), 4)

        draw_text(surface, "空气", x - 20, y - 10, (220, 255, 255), small_font)


# =========================
# 粒子和漂浮文字
# =========================
class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.vx = random.uniform(-55, 55)
        self.vy = random.uniform(-75, -20)
        self.life = random.uniform(0.35, 0.8)
        self.max_life = self.life
        self.color = color
        self.r = random.randint(2, 5)

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

    def draw(self, surface):
        a = clamp(self.life / self.max_life, 0, 1)

        # 修复重点：统一转为 RGB，再单独添加 alpha
        r, g, b = to_rgb(self.color)
        alpha = int(220 * a)
        alpha = clamp(alpha, 0, 255)

        s = pygame.Surface((self.r * 2 + 4, self.r * 2 + 4), pygame.SRCALPHA)

        pygame.draw.circle(
            s,
            (r, g, b, alpha),
            (self.r + 2, self.r + 2),
            self.r
        )

        surface.blit(
            s,
            (int(self.x) - self.r - 2, int(self.y) - self.r - 2)
        )


class FloatText:
    def __init__(self, text, x, y, color=WHITE):
        self.text = text
        self.x = x
        self.y = y
        self.vy = -36
        self.life = 1.25
        self.color = color

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

    def draw(self, surface):
        alpha = clamp(self.life / 1.25, 0, 1)
        img = small_font.render(str(self.text), True, to_rgb(self.color))
        img.set_alpha(int(255 * alpha))
        surface.blit(img, (int(self.x), int(self.y)))


# =========================
# 游戏主体
# =========================
class Game:
    def __init__(self, keep_progress=False):
        self.bg = Background()
        self.player = Player()

        if keep_progress:
            old = self.player
            self.player = Player()
            self.player.coins = old.coins
            self.player.speed_level = old.speed_level
            self.player.tank_level = old.tank_level
            self.player.catch_level = old.catch_level
            self.player.fins_level = old.fins_level
            self.player.max_oxygen = 100 + old.tank_level * 25
            self.player.oxygen = self.player.max_oxygen

        self.region_index = 0
        self.fishes = []
        self.pearls = []
        self.air_pockets = []
        self.particles = []
        self.texts = []

        self.mode = "dive"
        self.prev_mode = "dive"

        self.t = 0
        self.spawn_timer = 0
        self.capture_time = 0

        self.message = "方向键移动，空格冲刺，靠近鱼按住E捕获；Z回岛，U升级。"
        self.message_time = 5.5

        self.populate(force=True)

    @property
    def region(self):
        return REGIONS[self.region_index]

    def populate(self, force=False):
        if force:
            self.fishes.clear()
            self.pearls.clear()
            self.air_pockets.clear()

        for _ in range(14):
            self.spawn_fish()

        for _ in range(4):
            self.spawn_pearl()

        self.spawn_air_pockets()

    def spawn_fish(self):
        weights = self.region["fish_weights"]
        kinds = list(weights.keys())
        ws = list(weights.values())
        kind = random.choices(kinds, weights=ws)[0]

        side = random.choice(["left", "right"])
        x = random.randint(60, 180) if side == "left" else random.randint(WIDTH - 180, WIDTH - 60)
        y = random.randint(120, HEIGHT - 125)

        self.fishes.append(Fish(x, y, kind))

    def spawn_pearl(self):
        self.pearls.append(
            Pearl(
                random.randint(80, WIDTH - 80),
                random.randint(HEIGHT - 170, HEIGHT - 100)
            )
        )

    def spawn_air_pockets(self):
        for _ in range(3 + self.region_index):
            self.air_pockets.append(
                AirPocket(
                    random.randint(110, WIDTH - 110),
                    random.randint(130, HEIGHT - 145)
                )
            )

    def add_particles(self, x, y, color, count=14):
        # 修复重点：防止传入 RGBA 后 Particle.draw 再拼 alpha 导致 5 个颜色值
        rgb = to_rgb(color)

        for _ in range(count):
            self.particles.append(Particle(x, y, rgb))

    def show_msg(self, msg):
        self.message = msg
        self.message_time = 4.2

    def nearest_target(self):
        best = None
        best_d = 86

        for f in self.fishes:
            d = math.hypot(f.x - self.player.x, f.y - self.player.y)
            if d < best_d:
                best_d = d
                best = f

        if best:
            return best

        for p in self.pearls:
            d = math.hypot(p.x - self.player.x, p.y - self.player.y)
            if d < best_d:
                best_d = d
                best = p

        if best:
            return best

        for a in self.air_pockets:
            d = math.hypot(a.x - self.player.x, a.y - self.player.y)
            if d < best_d:
                best_d = d
                best = a

        return best

    def current_region_by_depth(self):
        wanted = 0

        if self.player.y > 340:
            wanted = 1
        if self.player.y > 465:
            wanted = 2
        if self.player.y > 555:
            wanted = 3

        if wanted <= self.region_index:
            self.region_index = wanted
            return

        if wanted > self.region_index:
            need = REGIONS[wanted]["unlock"]
            self.show_msg(f"需要总收益 {need} 才能进入 {REGIONS[wanted]['name']}")

    def refund_and_reset_run(self):
        self.player.health = 100
        self.player.max_oxygen = 100 + self.player.tank_level * 25
        self.player.oxygen = self.player.max_oxygen
        self.player.stamina = 100
        self.player.x = WIDTH // 2
        self.player.y = HEIGHT // 2
        self.region_index = 0
        self.mode = "island"
        self.show_msg("回到岛屿。可以升级潜水装备后再下海。")

    def buy_upgrade(self, kind):
        costs = {
            "speed": 90 + self.player.speed_level * 70,
            "tank": 80 + self.player.tank_level * 65,
            "catch": 110 + self.player.catch_level * 85,
            "fins": 75 + self.player.fins_level * 60
        }

        names = {
            "speed": "推进服",
            "tank": "氧气瓶",
            "catch": "捕获手套",
            "fins": "脚蹼"
        }

        max_level = 4
        level = getattr(self.player, kind + "_level")

        if level >= max_level:
            self.show_msg(f"{names[kind]}已经满级。")
            return

        cost = costs[kind]

        if self.player.coins >= cost:
            self.player.coins -= cost
            setattr(self.player, kind + "_level", level + 1)

            if kind == "tank":
                self.player.max_oxygen = 100 + self.player.tank_level * 25
                self.player.oxygen = self.player.max_oxygen

            self.show_msg(f"升级成功：{names[kind]} Lv.{level + 1}")
        else:
            self.show_msg(f"金币不足，需要 {cost}。")

    def update_dive(self, dt):
        keys = pygame.key.get_pressed()

        self.player.update(keys, dt, self.region)
        self.current_region_by_depth()

        for f in self.fishes[:]:
            f.update(dt, self.t)

        for p in self.pearls:
            p.update(dt, self.t)

        for a in self.air_pockets:
            a.update(dt, self.t)

        # 换气气泡
        for a in self.air_pockets:
            if math.hypot(a.x - self.player.x, a.y - self.player.y) < a.radius + self.player.radius:
                self.player.oxygen = min(
                    self.player.max_oxygen,
                    self.player.oxygen + 28 * dt
                )

                if random.random() < 0.18:
                    self.add_particles(self.player.x, self.player.y - 25, CYAN, 2)

        self.spawn_timer -= dt

        if self.spawn_timer <= 0:
            if len(self.fishes) < 22:
                self.spawn_fish()

            if len(self.pearls) < 7 and random.random() < self.region["pearl_chance"]:
                self.spawn_pearl()

            if random.random() < 0.2:
                self.spawn_air_pockets()

            self.spawn_timer = random.uniform(1.1, 2.7)

        # 捕获
        target = self.nearest_target()

        if keys[pygame.K_e]:
            self.capture_time += dt

            if target:
                if isinstance(target, Fish):
                    need = 0.72 * target.escape / self.player.catch_power
                elif isinstance(target, Pearl):
                    need = 0.55 / self.player.catch_power
                else:
                    need = 0.2

                if self.capture_time >= need:
                    if isinstance(target, AirPocket):
                        self.player.oxygen = self.player.max_oxygen
                        self.show_msg("补充满氧气！")
                        self.add_particles(target.x, target.y, CYAN, 16)
                        self.air_pockets.remove(target)
                    else:
                        self.player.inventory.append(target.name)
                        self.player.coins += target.value
                        self.add_particles(target.x, target.y, (140, 235, 255), 18)
                        self.texts.append(
                            FloatText(
                                f"+{target.value}  {target.name}",
                                target.x - 50,
                                target.y - 35,
                                YELLOW
                            )
                        )

                        if isinstance(target, Fish):
                            self.fishes.remove(target)
                        else:
                            self.pearls.remove(target)

                        self.show_msg("捕获成功！")

                    self.capture_time = 0
        else:
            self.capture_time = 0

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

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

        if self.player.health <= 0:
            self.mode = "gameover"

    def draw_dive(self):
        self.bg.draw_ocean(
            screen,
            self.region_index,
            self.player.y - HEIGHT // 2,
            self.player.y
        )

        camera_y = self.player.y - HEIGHT // 2

        # 远景鱼群剪影
        for i in range(7):
            x = (i * 165 - self.t * (18 + i * 5)) % (WIDTH + 190) - 80
            y = 110 + 42 * math.sin(i * 1.6) - camera_y * 0.03

            pygame.draw.ellipse(screen, (15, 80, 115, 55), (x, y, 45, 16))
            pygame.draw.polygon(
                screen,
                (15, 80, 115, 45),
                [(x, y + 8), (x - 13, y), (x - 13, y + 16)]
            )

        for p in self.pearls:
            p.draw(screen, self.t)

        for a in self.air_pockets:
            a.draw(screen, self.t)

        for f in self.fishes:
            f.draw(screen, self.t)

        self.player.draw(screen)

        for pt in self.particles:
            pt.draw(screen)

        for tx in self.texts:
            tx.draw(screen)

        # 暗角
        vignette = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        pygame.draw.rect(vignette, (0, 8, 20, 62), (0, 0, WIDTH, HEIGHT))
        screen.blit(vignette, (0, 0))

        self.draw_hud()

    def draw_hud(self):
        draw_rounded_panel(screen, pygame.Rect(15, 12, 305, 112), (4, 23, 42), 155)
        draw_bar(
            screen,
            pygame.Rect(30, 25, 250, 17),
            self.player.oxygen,
            self.player.max_oxygen,
            (70, 190, 255),
            "氧气"
        )
        draw_bar(
            screen,
            pygame.Rect(30, 49, 250, 17),
            self.player.health,
            100,
            (80, 220, 120),
            "生命"
        )
        draw_bar(
            screen,
            pygame.Rect(30, 73, 250, 17),
            self.player.stamina,
            100,
            (255, 185, 75),
            "冲刺"
        )

        draw_rounded_panel(screen, pygame.Rect(WIDTH - 245, 12, 220, 92), (4, 23, 42), 155)
        draw_text(screen, f"金币  {self.player.coins}", WIDTH - 223, 25, YELLOW)
        draw_text(screen, f"区域  {self.region['name']}", WIDTH - 223, 50, LIGHT, small_font)
        draw_text(screen, f"深度  {self.region['depth_name']}", WIDTH - 223, 72, WHITE, small_font)

        panel_y = 135

        for i, r in enumerate(REGIONS):
            unlocked = self.player.coins >= r["unlock"]
            color = GREEN if unlocked else (100, 115, 130)
            txt = f"{r['name']}  收益{r['unlock']}+" if not unlocked else r["name"]

            draw_rounded_panel(screen, pygame.Rect(15, panel_y, 190, 25), (4, 20, 35), 110)
            pygame.draw.circle(screen, to_rgb(color), (30, panel_y + 13), 5)
            draw_text(screen, txt, 43, panel_y + 5, WHITE, tiny_font)

            panel_y += 30

        draw_rounded_panel(screen, pygame.Rect(330, HEIGHT - 40, 430, 28), (2, 18, 32), 125)
        draw_text(
            screen,
            "移动 WASD/方向键｜空格冲刺｜E捕获｜Z回岛｜U升级｜B背包",
            WIDTH // 2,
            HEIGHT - 27,
            WHITE,
            tiny_font,
            True
        )

        target = self.nearest_target()

        if target:
            msg = "按住 E 捕获"

            if self.capture_time > 0:
                if isinstance(target, Fish):
                    need = 0.72 * target.escape / self.player.catch_power
                elif isinstance(target, Pearl):
                    need = 0.55 / self.player.catch_power
                else:
                    need = 0.2

                pct = int(clamp(self.capture_time / need, 0, 1) * 100)
                msg = f"捕获中 {pct}%"

            if isinstance(target, AirPocket):
                msg = "按 E 换气"

            draw_text(
                screen,
                msg,
                int(target.x) - 45,
                int(target.y) - 42,
                YELLOW,
                small_font
            )

            pygame.draw.circle(
                screen,
                (255, 230, 110),
                (int(target.x), int(target.y)),
                int(target.radius + 11),
                2
            )

        if self.message_time > 0:
            draw_rounded_panel(screen, pygame.Rect(210, HEIGHT - 78, 680, 31), (2, 18, 32), 135)
            draw_text(
                screen,
                self.message,
                WIDTH // 2,
                HEIGHT - 69,
                WHITE,
                small_font,
                True
            )

    def draw_island(self):
        sky = pygame.Surface((WIDTH, HEIGHT))

        for y in range(HEIGHT):
            p = y / HEIGHT
            sky.set_at(
                (0, y),
                pygame.Color(105, 210, 245).lerp(
                    pygame.Color(225, 245, 230),
                    min(1, p * 1.5)
                )
            )

        screen.blit(pygame.transform.scale(sky, (WIDTH, HEIGHT)), (0, 0))

        pygame.draw.circle(screen, (255, 235, 150), (900, 100), 48)
        pygame.draw.circle(screen, (255, 220, 110), (900, 100), 78, 3)

        pygame.draw.rect(screen, (35, 160, 205), (0, 330, WIDTH, 115))

        for x in range(0, WIDTH, 42):
            pygame.draw.arc(
                screen,
                (230, 255, 255),
                (x, 348, 46, 25),
                math.pi,
                math.pi * 2,
                2
            )
            pygame.draw.arc(
                screen,
                (230, 255, 255),
                (x + 20, 380, 42, 22),
                math.pi,
                math.pi * 2,
                2
            )

        pygame.draw.ellipse(screen, (220, 190, 115), (260, 365, 580, 105))
        pygame.draw.ellipse(screen, (90, 180, 95), (345, 300, 410, 110))
        pygame.draw.ellipse(screen, (65, 150, 80), (390, 275, 320, 95))

        for base_x in [370, 735]:
            pygame.draw.rect(screen, (100, 65, 38), (base_x, 245, 15, 75), border_radius=6)

            for dx, dy in [(-48, -18), (45, -22), (-18, -48), (20, -40)]:
                pygame.draw.ellipse(
                    screen,
                    (35, 145, 75),
                    (base_x + dx, 235 + dy, 58, 18)
                )

        pygame.draw.rect(screen, (170, 110, 65), (505, 290, 90, 60), border_radius=6)
        pygame.draw.polygon(screen, (190, 75, 55), [(490, 292), (550, 245), (612, 292)])
        pygame.draw.rect(screen, (80, 150, 190), (530, 310, 22, 22), border_radius=4)
        pygame.draw.rect(screen, (80, 150, 190), (565, 310, 20, 22), border_radius=4)

        draw_rounded_panel(screen, pygame.Rect(250, 445, 600, 155), (5, 30, 48), 190, CYAN)
        draw_text(screen, "潜水岛基地", WIDTH // 2, 475, WHITE, big_font, True)
        draw_text(
            screen,
            f"总金币：{self.player.coins}    当前捕获背包：{len(self.player.inventory)} 件",
            WIDTH // 2,
            522,
            YELLOW,
            font,
            True
        )
        draw_text(
            screen,
            "按 D 下潜｜按 U 打开升级商店｜按 B 查看背包",
            WIDTH // 2,
            555,
            LIGHT,
            font,
            True
        )
        draw_text(
            screen,
            "提示：携带金币达到指定收益后可进入更深区域。",
            WIDTH // 2,
            580,
            WHITE,
            small_font,
            True
        )

    def draw_shop(self):
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 10, 20, 150))
        screen.blit(overlay, (0, 0))

        panel = pygame.Rect(165, 65, 770, 555)
        draw_rounded_panel(screen, panel, (4, 26, 45), 230, CYAN)

        draw_text(screen, "岛屿升级商店", WIDTH // 2, 108, WHITE, big_font, True)
        draw_text(
            screen,
            f"金币：{self.player.coins}    按 U / ESC 返回",
            WIDTH // 2,
            152,
            YELLOW,
            font,
            True
        )

        items = [
            ("speed", "推进服", "提升横向移动和冲刺速度", self.player.speed_level),
            ("tank", "氧气瓶", "提升最大氧气上限", self.player.tank_level),
            ("catch", "捕获手套", "缩短捕获稀有鱼所需时间", self.player.catch_level),
            ("fins", "脚蹼", "提升上下潜速度和冲刺表现", self.player.fins_level)
        ]

        costs = {
            "speed": 90 + self.player.speed_level * 70,
            "tank": 80 + self.player.tank_level * 65,
            "catch": 110 + self.player.catch_level * 85,
            "fins": 75 + self.player.fins_level * 60
        }

        y = 205

        for key, name, desc, level in items:
            draw_rounded_panel(screen, pygame.Rect(220, y, 660, 72), (8, 45, 68), 180)
            draw_text(screen, f"{name}  Lv.{level}/4", 245, y + 11, WHITE)
            draw_text(screen, desc, 245, y + 40, LIGHT, small_font)

            index = ["speed", "tank", "catch", "fins"].index(key)

            if level >= 4:
                draw_text(screen, "已满级", 715, y + 27, GREEN, font)
            else:
                draw_text(screen, f"花费 {costs[key]}", 700, y + 13, YELLOW, small_font)
                draw_text(screen, f"按 {index + 1} 升级", 700, y + 39, WHITE, tiny_font)

            y += 86

        draw_text(
            screen,
            "快捷键：1 推进服 ｜ 2 氧气瓶 ｜ 3 捕获手套 ｜ 4 脚蹼",
            WIDTH // 2,
            590,
            WHITE,
            small_font,
            True
        )

    def draw_inventory(self):
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 10, 20, 135))
        screen.blit(overlay, (0, 0))

        panel = pygame.Rect(220, 90, 660, 500)
        draw_rounded_panel(screen, panel, (5, 28, 50), 225, (110, 215, 255))

        draw_text(screen, "潜水背包", WIDTH // 2, 130, WHITE, big_font, True)
        draw_text(
            screen,
            f"总价值：{self.player.coins}    按 B / ESC 关闭",
            WIDTH // 2,
            178,
            YELLOW,
            font,
            True
        )

        if not self.player.inventory:
            draw_text(screen, "还没有收获，去抓几条鱼吧。", WIDTH // 2, 310, WHITE, font, True)
        else:
            counts = {}

            for item in self.player.inventory:
                counts[item] = counts.get(item, 0) + 1

            y = 225

            for name, cnt in counts.items():
                pygame.draw.circle(screen, (80, 190, 230), (285, y + 10), 8)
                draw_text(screen, f"{name}  x{cnt}", 310, y, WHITE)
                y += 35

            if y > 500:
                draw_text(screen, "……", 285, 520, WHITE)

    def draw_game_over(self):
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 5, 12, 175))
        screen.blit(overlay, (0, 0))

        draw_text(screen, "潜水结束", WIDTH // 2, HEIGHT // 2 - 65, WHITE, huge_font, True)
        draw_text(
            screen,
            f"本轮累计收益：{self.player.coins}",
            WIDTH // 2,
            HEIGHT // 2 - 5,
            YELLOW,
            font,
            True
        )
        draw_text(
            screen,
            "按 R 重新开始｜按 Z 返回岛屿保留金币和升级",
            WIDTH // 2,
            HEIGHT // 2 + 48,
            CYAN,
            font,
            True
        )

    def draw(self):
        if self.mode == "island":
            self.draw_island()
        elif self.mode == "shop":
            self.draw_island()
            self.draw_shop()
        elif self.mode == "inventory":
            self.draw_dive()
            self.draw_inventory()
        elif self.mode == "gameover":
            self.draw_dive()
            self.draw_game_over()
        else:
            self.draw_dive()

        pygame.display.flip()


# =========================
# 主循环
# =========================
def main():
    game = Game()
    running = True

    while running:
        dt = clock.tick(FPS) / 1000.0

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    if game.mode in ["shop", "inventory"]:
                        game.mode = game.prev_mode
                    elif game.mode == "island":
                        running = False
                    else:
                        game.mode = "island"

                elif event.key == pygame.K_z:
                    if game.mode in ["dive", "gameover"]:
                        game.refund_and_reset_run()

                elif event.key == pygame.K_d:
                    if game.mode == "island":
                        game.mode = "dive"
                        game.show_msg("下潜开始！深潜可解锁新海域。")

                elif event.key == pygame.K_u:
                    if game.mode == "island":
                        game.prev_mode = "island"
                        game.mode = "shop"
                    elif game.mode == "dive":
                        game.prev_mode = "dive"
                        game.mode = "shop"

                elif event.key == pygame.K_b:
                    if game.mode == "dive":
                        game.prev_mode = "dive"
                        game.mode = "inventory"
                    elif game.mode == "inventory":
                        game.mode = game.prev_mode

                elif event.key == pygame.K_r:
                    if game.mode == "gameover":
                        game = Game(keep_progress=True)

                if game.mode == "shop":
                    if event.key == pygame.K_1:
                        game.buy_upgrade("speed")
                    elif event.key == pygame.K_2:
                        game.buy_upgrade("tank")
                    elif event.key == pygame.K_3:
                        game.buy_upgrade("catch")
                    elif event.key == pygame.K_4:
                        game.buy_upgrade("fins")

        if game.mode == "dive":
            game.bg.update(dt)
            game.t += dt
            game.update_dive(dt)

        elif game.mode == "island":
            game.bg.update(dt)
            game.t += dt

        elif game.mode in ["shop", "inventory", "gameover"]:
            game.bg.update(dt)
            game.t += dt

        if game.message_time > 0:
            game.message_time -= dt

        game.draw()

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()