# -*- coding: utf-8 -*-
"""
水循环演示动画（pygame 单文件，零素材依赖）

画面：太阳 / 海面 / 陆地山坡 / 云 / 树 / 河流 / 地下水层
六个环节循环演示：
  ① 蒸发  ② 凝结（水汽输送）  ③ 降水  ④ 地表径流  ⑤ 下渗与地下径流  ⑥ 蒸腾与循环

交互运行：
    python 水循环动画.py
    空格 暂停/继续    ← → 调速    1~6 跳到指定环节    R 重置    Esc 退出
    鼠标点底部流程条也能切换环节

导出成品：
    python 水循环动画.py --export
    生成 水循环演示.mp4 / 水循环演示.gif / 水循环封面.png
"""

import glob
import math
import os
import random
import subprocess
import sys

EXPORT = "--export" in sys.argv
TEST = "--test" in sys.argv
if EXPORT or TEST:
    os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
    os.environ.setdefault("SDL_AUDIODRIVER", "dummy")

import pygame
from PIL import Image

# ---------------- 画布与配色 ----------------
W, H = 960, 600
PANEL_TOP = 518
SEA_Y = 380
FPS_EXPORT = 12
STAGE_SEC_EXPORT = 2.0

SKY_TOP = (74, 148, 214)
SKY_BOTTOM = (206, 232, 248)
SEA = (44, 126, 190)
SEA_DEEP = (28, 92, 152)
LAND_GREEN = (104, 168, 104)
LAND_DARK = (72, 132, 86)
SOIL = (158, 120, 82)
GROUND_WATER = (74, 108, 140)
CLOUD_WHITE = (250, 252, 255)
CLOUD_GRAY = (128, 138, 156)
SUN = (255, 206, 74)
BLUE = (59, 125, 221)
LIGHT_BLUE = (120, 196, 246)
GREEN = (46, 168, 88)
DARK = (28, 38, 58)
GREY = (108, 120, 142)
WHITE = (255, 255, 255)

# 陆地轮廓（海岸线 x=470，山顶约 x=715）
LAND = [(470, 380), (515, 358), (585, 298), (655, 242), (715, 216),
        (775, 222), (845, 272), (905, 326), (960, 352)]
# 河流：山顶汇流 → 沿坡回海
RIVER = [(718, 219), (688, 240), (642, 278), (596, 316),
         (552, 350), (510, 373), (472, 380)]

STAGES = [
    ("① 蒸发", "太阳加热海面，液态水变成水汽升入空中", (232, 300)),
    ("② 凝结", "水汽上升遇冷，聚集成小水滴，形成云", (610, 78)),
    ("③ 降水", "云滴越聚越大，以雨的形式落回地面", (812, 186)),
    ("④ 地表径流", "雨水沿山坡汇成河流，奔流回大海", (560, 262)),
    ("⑤ 下渗·地下径流", "一部分水渗入土壤，在地下缓慢回流", (752, 452)),
    ("⑥ 蒸腾·循环", "植物蒸腾补充水汽，水循环往复不息", (862, 244)),
]


def ground_y(x):
    if x <= LAND[0][0]:
        return float(SEA_Y)
    if x >= LAND[-1][0]:
        return float(LAND[-1][1])
    for (x1, y1), (x2, y2) in zip(LAND, LAND[1:]):
        if x1 <= x <= x2:
            t = (x - x1) / (x2 - x1)
            return y1 + (y2 - y1) * t
    return float(SEA_Y)


def lerp(a, b, t):
    t = max(0.0, min(1.0, t))
    return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(3))


# ---------------- 字体 ----------------
def find_cn_font():
    cands = [
        "/usr/share/fonts/truetype/alibaba-puhuiti/AlibabaPuHuiTi-2-75-SemiBold.ttf",
        "/usr/share/fonts/truetype/alibaba-puhuiti/AlibabaPuHuiTi-3-55-Regular.ttf",
        "/System/Library/Fonts/PingFang.ttc",
        "C:/Windows/Fonts/msyh.ttc",
        "C:/Windows/Fonts/simhei.ttf",
        "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
    ]
    for p in cands:
        if os.path.exists(p):
            return p
    for pat in ("/usr/share/fonts/**/*CJK*.*", "/usr/share/fonts/**/wqy*.*",
                "/usr/share/fonts/**/*PuHuiTi*.*"):
        hits = [p for p in glob.glob(pat, recursive=True)
                if p.lower().endswith((".ttf", ".otf", ".ttc"))]
        if hits:
            return sorted(hits)[0]
    return None


FONT_PATH = find_cn_font()
_fcache = {}


def font(size, bold=False):
    key = (size, bold)
    if key not in _fcache:
        try:
            f = pygame.font.Font(FONT_PATH, size) if FONT_PATH else pygame.font.Font(None, size)
        except Exception:
            f = pygame.font.Font(None, size)
        f.set_bold(bold)
        _fcache[key] = f
    return _fcache[key]


def text(s, size, color, bold=False):
    return font(size, bold).render(s, True, color)


# ---------------- 动画主体 ----------------
class WaterCycle:
    def __init__(self, screen, stage_sec=5.0, seed=2026):
        self.screen = screen
        self.stage_sec = stage_sec
        random.seed(seed)
        self.speed = 1.0
        self.paused = False
        self.stage_rects = []
        self.bg = None
        self.reset()

    def reset(self):
        self.t = 0.0
        self.stage = 0
        self.condense = 0.0
        self.vapor, self.rain, self.ripples = [], [], []
        self.runoff, self.ground, self.transp = [], [], []
        self.acc = {"v": 0.0, "r": 0.0, "u": 0.0, "g": 0.0, "p": 0.0}
        self.bg = self._build_bg()

    # ---------- 静态背景（只渲染一次） ----------
    def _build_bg(self):
        s = pygame.Surface((W, H))
        # 天空渐变
        for y in range(SEA_Y + 1):
            s.fill(lerp(SKY_TOP, SKY_BOTTOM, y / SEA_Y), (0, y, W, 1))
        # 远山剪影（淡）
        pygame.draw.polygon(s, (176, 205, 226), [(330, 380), (430, 300), (500, 360), (560, 320), (640, 380)])
        # 海
        s.fill(SEA, (0, SEA_Y, LAND[0][0], PANEL_TOP - SEA_Y))
        s.fill(SEA_DEEP, (0, SEA_Y + 78, LAND[0][0], PANEL_TOP - SEA_Y - 78))
        # 陆地
        poly = LAND + [(W, PANEL_TOP), (LAND[0][0], PANEL_TOP)]
        pygame.draw.polygon(s, LAND_GREEN, poly)
        # 山体阴影（右侧）
        pygame.draw.polygon(s, LAND_DARK, [(715, 216), (775, 222), (845, 272),
                                           (905, 326), (960, 352), (960, PANEL_TOP),
                                           (760, PANEL_TOP)])
        # 土层
        soil_top = [(x, ground_y(x) + 46) for x, _ in LAND]
        pygame.draw.polygon(s, SOIL, soil_top + [(W, PANEL_TOP), (LAND[0][0], PANEL_TOP)])
        # 地下水层（随地形起伏的带）
        gw_a = [(x, ground_y(x) + 72) for x, _ in LAND]
        gw_b = [(x, ground_y(x) + 112) for x, _ in LAND]
        pygame.draw.polygon(s, GROUND_WATER, gw_a + list(reversed(gw_b)))
        # 地下水层纹理
        for i in range(0, 9):
            x = 500 + i * 52
            yy = ground_y(x) + 92
            pygame.draw.line(s, (108, 146, 176), (x, yy), (x + 26, yy - 4), 1)
        # 河流（静态底）
        pygame.draw.lines(s, (40, 108, 172), False, RIVER, 10)
        pygame.draw.lines(s, (96, 178, 232), False, RIVER, 5)
        # 树
        self.trees = [(548, ground_y(548)), (632, ground_y(632)), (872, ground_y(872))]
        for tx, ty in self.trees:
            pygame.draw.rect(s, (116, 82, 52), (tx - 4, ty - 26, 8, 28))
            for dx, dy, r in ((-11, -34, 15), (11, -34, 15), (0, -48, 17)):
                pygame.draw.circle(s, (58, 132, 76), (tx + dx, ty + dy), r)
                pygame.draw.circle(s, (82, 158, 96), (tx + dx - 3, ty + dy - 4), r - 4)
        # 海岸沙滩
        pygame.draw.line(s, (226, 208, 158), (470, 380), (515, 358), 5)
        # 底部面板
        s.fill((246, 249, 253), (0, PANEL_TOP, W, H - PANEL_TOP))
        pygame.draw.line(s, (218, 228, 240), (0, PANEL_TOP), (W, PANEL_TOP), 2)
        return s

    # ---------- 小组件 ----------
    def pill(self, surf, label, x, y, active, scale=1.0):
        f = font(int(15 * scale), True)
        img = f.render(label, True, WHITE if active else GREY)
        w, h = img.get_width() + 22, img.get_height() + 12
        r = pygame.Rect(int(x - w / 2), int(y - h / 2), w, h)
        pygame.draw.rect(surf, BLUE if active else (232, 238, 246), r, border_radius=h // 2)
        if active:
            pygame.draw.rect(surf, (255, 255, 255), r, width=2, border_radius=h // 2)
        surf.blit(img, (r.centerx - img.get_width() // 2, r.centery - img.get_height() // 2))
        return r

    def arrow(self, surf, x1, y1, x2, y2, color, width=2):
        pygame.draw.line(surf, color, (x1, y1), (x2, y2), width)
        ang = math.atan2(y2 - y1, x2 - x1)
        for a in (ang + 2.6, ang - 2.6):
            pygame.draw.line(surf, color, (x2, y2),
                             (x2 + math.cos(a) * 9, y2 + math.sin(a) * 9), width)

    # ---------- 粒子生成 ----------
    def _spawn_vapor(self):
        self.vapor.append({
            "x": random.uniform(24, 440), "y": SEA_Y - 3,
            "vy": random.uniform(24, 44), "ph": random.uniform(0, 6.28),
            "r": random.uniform(2.0, 3.8), "life": 0.0,
        })

    def _spawn_rain(self):
        x = random.uniform(480, 790)
        self.rain.append({"x": x, "y": random.uniform(168, 182),
                          "vy": random.uniform(230, 330), "len": random.uniform(9, 16)})

    def _spawn_runoff(self):
        self.runoff.append({"t": 0.0, "v": random.uniform(0.22, 0.36)})

    def _spawn_ground(self):
        self.ground.append({"t": 0.0, "v": random.uniform(0.055, 0.09)})

    def _spawn_transp(self):
        tx, ty = random.choice(self.trees)
        self.transp.append({"x": tx + random.uniform(-14, 14),
                            "y": ty + random.uniform(-58, -36),
                            "vy": random.uniform(18, 30),
                            "ph": random.uniform(0, 6.28), "r": random.uniform(1.6, 3.0)})

    def _river_point(self, t):
        seg = min(int(t * (len(RIVER) - 1)), len(RIVER) - 2)
        u = t * (len(RIVER) - 1) - seg
        (x1, y1), (x2, y2) = RIVER[seg], RIVER[seg + 1]
        return x1 + (x2 - x1) * u, y1 + (y2 - y1) * u

    def _gw_point(self, t):
        x = 905 - (905 - 480) * t
        return x, ground_y(x) + 94 + math.sin(t * 9) * 4

    # ---------- 更新 ----------
    def set_stage(self, i):
        self.stage = i % len(STAGES)
        self.t = self.stage * self.stage_sec

    def update(self, dt):
        if self.paused:
            return
        self.t += dt
        st = int(self.t // self.stage_sec) % len(STAGES)
        self.stage = st

        rates = {
            "v": [15, 9, 4, 3, 3, 7][st],       # 蒸发
            "r": [2, 8, 46, 12, 3, 4][st],      # 降水
            "u": [1.2, 1.2, 2, 7, 2, 1][st],   # 径流
            "g": [0.5, 0.5, 1, 2, 6, 1][st],   # 地下径流
            "p": [0.6, 0.6, 0.4, 0.6, 1.5, 12][st],  # 蒸腾
        }
        for k, rate in rates.items():
            self.acc[k] += rate * dt
            while self.acc[k] >= 1:
                self.acc[k] -= 1
                {"v": self._spawn_vapor, "r": self._spawn_rain,
                 "u": self._spawn_runoff, "g": self._spawn_ground,
                 "p": self._spawn_transp}[k]()

        # 云的凝结程度：凝结阶段聚积，降水阶段消耗
        target = [0.18, 0.92, 0.95, 0.5, 0.3, 0.25][st]
        self.condense += (target - self.condense) * min(1.0, dt * 1.1)

        # 水汽上升
        alive = []
        for p in self.vapor:
            p["y"] -= p["vy"] * dt
            p["life"] += dt
            if p["y"] > 172:
                alive.append(p)
            else:
                self.condense = min(1.0, self.condense + 0.004)
        self.vapor = alive[-260:]

        # 降雨
        alive = []
        for p in self.rain:
            p["y"] += p["vy"] * dt
            floor = ground_y(p["x"]) if p["x"] >= 470 else SEA_Y
            if p["y"] < floor:
                alive.append(p)
            elif len(self.ripples) < 60:
                self.ripples.append({"x": p["x"], "y": floor, "r": 2.0, "life": 0.0})
        self.rain = alive[-300:]

        for p in self.ripples:
            p["life"] += dt
            p["r"] += 24 * dt
        self.ripples = [p for p in self.ripples if p["life"] < 0.8]

        # 径流 / 地下径流 / 蒸腾
        for key, lst in (("runoff", self.runoff), ("ground", self.ground)):
            keep = []
            for p in lst:
                p["t"] += p["v"] * dt * ([1, 1, 1, 2.1, 1, 1][st] if key == "runoff" else
                                         [1, 1, 1, 1, 2.4, 1][st])
                if p["t"] < 1:
                    keep.append(p)
            if key == "runoff":
                self.runoff = keep[-26:]
            else:
                self.ground = keep[-22:]
        keep = []
        for p in self.transp:
            p["y"] -= p["vy"] * dt
            if p["y"] > 150:
                keep.append(p)
        self.transp = keep[-60:]

    # ---------- 绘制 ----------
    def draw(self):
        s = self.screen
        s.blit(self.bg, (0, 0))
        st = self.stage
        t = self.t

        # 太阳（光晕 + 旋转光线）
        sx, sy = 118, 96
        for i in range(5, 0, -1):
            a = pygame.Surface((i * 30 * 2, i * 30 * 2), pygame.SRCALPHA)
            pygame.draw.circle(a, (255, 214, 110, 12), (i * 30, i * 30), i * 30)
            s.blit(a, (sx - i * 30, sy - i * 30))
        for i in range(12):
            ang = i * math.pi / 6 + t * 0.12
            r1, r2 = 50, 62 + (4 if st == 0 else 0)
            pygame.draw.line(s, (255, 214, 110),
                             (sx + math.cos(ang) * r1, sy + math.sin(ang) * r1),
                             (sx + math.cos(ang) * r2, sy + math.sin(ang) * r2), 3)
        pygame.draw.circle(s, SUN, (sx, sy), 40)
        pygame.draw.circle(s, (255, 232, 150), (sx - 10, sy - 12), 26)

        # 海浪（3 层正弦线）
        for k, (amp, col, yy) in enumerate(((3.5, (150, 210, 244), SEA_Y + 4),
                                           (5.0, (110, 186, 232), SEA_Y + 26),
                                           (6.5, (86, 166, 220), SEA_Y + 56))):
            pts = [(x, yy + math.sin(x * 0.035 + t * (1.1 + k * 0.3) + k) * amp)
                   for x in range(0, 471, 6)]
            pygame.draw.lines(s, col, False, pts, 2)

        # 云（随凝结变灰 + 缓慢漂移）
        cx = 612 + math.sin(t * 0.22) * 16
        cy = 138 + math.sin(t * 0.5) * 3
        cc = lerp(CLOUD_WHITE, CLOUD_GRAY, self.condense)
        shade = lerp((214, 226, 240), (96, 106, 124), self.condense)
        blobs = [(-86, 10, 34), (-52, -8, 42), (-12, -20, 48), (30, -10, 40),
                 (68, 8, 32), (0, 16, 48)]
        for dx, dy, r in blobs:
            pygame.draw.circle(s, shade, (int(cx + dx), int(cy + dy + 6)), r)
        for dx, dy, r in blobs:
            pygame.draw.circle(s, cc, (int(cx + dx), int(cy + dy)), r)

        # 水汽输送虚线箭头（凝结阶段强调）
        if st in (0, 1):
            for i in range(4):
                x = 300 + i * 82
                self.arrow(s, x, 232 - i * 8, x + 52, 206 - i * 8,
                           (255, 255, 255) if st == 0 else LIGHT_BLUE, 2)

        # 水汽粒子
        for p in self.vapor:
            wob = math.sin(t * 2.2 + p["ph"]) * 11
            a = int(150 * min(1.0, p["life"] * 2.5) *
                    min(1.0, (p["y"] - 170) / 90 + 0.15))
            a = max(30, min(210, a))
            col = (255, 255, 255) if a > 120 else (206, 232, 250)
            pygame.draw.circle(s, col, (int(p["x"] + wob), int(p["y"])), int(p["r"]))
            if a > 160:
                pygame.draw.circle(s, (255, 255, 255),
                                   (int(p["x"] + wob), int(p["y"])), int(p["r"] + 2), 1)

        # 蒸腾粒子
        for p in self.transp:
            pygame.draw.circle(s, (196, 236, 210),
                               (int(p["x"] + math.sin(t * 2 + p["ph"]) * 6),
                                int(p["y"])), int(p["r"]))

        # 雨滴
        for p in self.rain:
            pygame.draw.line(s, (150, 206, 246), (p["x"], p["y"]),
                             (p["x"] + 1.5, p["y"] + p["len"]), 2)
        # 落地涟漪
        for p in self.ripples:
            a = max(0, int(200 * (1 - p["life"] / 0.8)))
            pygame.draw.ellipse(s, (170, 216, 246),
                                (p["x"] - p["r"], p["y"] - p["r"] * 0.28,
                                 p["r"] * 2, p["r"] * 0.56), 1)

        # 河流径流点
        for p in self.runoff:
            x, y = self._river_point(p["t"])
            pygame.draw.line(s, (196, 232, 255), (x - 6, y), (x, y), 2)
            pygame.draw.circle(s, (220, 244, 255), (int(x), int(y)), 3)
        # 河流阶段高亮
        if st == 3:
            pygame.draw.lines(s, (190, 232, 255), False, RIVER, 2)

        # 下渗箭头（下渗阶段）
        if st == 4:
            for x in (560, 640, 720, 800, 880):
                gy = ground_y(x)
                self.arrow(s, x, gy + 6, x, gy + 68, (190, 226, 255), 2)
        # 地下径流点
        for p in self.ground:
            x, y = self._gw_point(p["t"])
            pygame.draw.circle(s, (150, 206, 240), (int(x), int(y)), 3)
        # 地下水方向箭头
        self.arrow(s, 840, ground_y(840) + 94, 540, ground_y(540) + 94,
                   (178, 216, 242), 2)

        # 环节标签（当前环节高亮）
        for i, (name, desc, pos) in enumerate(STAGES):
            self.pill(s, name, pos[0], pos[1], i == st, 1.12 if i == st else 1.0)

        # 标题
        s.blit(text("水循环 · The Water Cycle", 25, DARK, True), (26, 18))
        s.blit(text("蒸发 → 凝结 → 降水 → 径流 → 下渗 → 循环往复", 13, GREY), (28, 50))
        # 状态
        status = f"{self.speed:.2f}x  " + ("⏸ 已暂停" if self.paused else "▶ 播放中")
        img = text(status, 14, BLUE, True)
        s.blit(img, (W - img.get_width() - 24, 24))

        # 底部流程条
        self.stage_rects = []
        bw, gap, x0 = 146, 8, 30
        for i, (name, desc, _) in enumerate(STAGES):
            r = pygame.Rect(x0 + i * (bw + gap), 530, bw, 30)
            self.stage_rects.append(r)
            active = i == st
            pygame.draw.rect(s, BLUE if active else (226, 233, 243),
                             r, border_radius=15)
            img = text(name, 13, WHITE if active else GREY, True)
            s.blit(img, (r.centerx - img.get_width() // 2,
                         r.centery - img.get_height() // 2))
        desc = STAGES[st][1]
        img = text(desc, 15, DARK)
        s.blit(img, (W // 2 - img.get_width() // 2, 570))
        # 阶段进度细线
        frac = (self.t % self.stage_sec) / self.stage_sec
        pygame.draw.rect(s, (210, 222, 238), (30, 566, W - 60, 2))
        pygame.draw.rect(s, BLUE, (30, 566, int((W - 60) * frac), 2))

    # ---------- 交互 ----------
    def handle_event(self, e):
        if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
            for i, r in enumerate(self.stage_rects):
                if r.collidepoint(e.pos):
                    self.set_stage(i)
                    return
        elif e.type == pygame.KEYDOWN:
            if e.key == pygame.K_ESCAPE:
                return "quit"
            if e.key == pygame.K_SPACE:
                self.paused = not self.paused
            elif e.key == pygame.K_LEFT:
                speeds = (0.5, 0.75, 1.0, 1.5, 2.0)
                self.speed = speeds[max(0, speeds.index(self.speed) - 1)] if self.speed in speeds else 0.5
            elif e.key == pygame.K_RIGHT:
                speeds = (0.5, 0.75, 1.0, 1.5, 2.0)
                self.speed = speeds[min(4, speeds.index(self.speed) + 1)] if self.speed in speeds else 2.0
            elif e.key == pygame.K_r:
                self.reset()
            elif pygame.K_1 <= e.key <= pygame.K_6:
                self.set_stage(e.key - pygame.K_1)
        return None


# ---------------- 主程序 ----------------
def main():
    pygame.init()
    pygame.display.set_caption("水循环演示动画")
    screen = pygame.display.set_mode((W, H))
    game = WaterCycle(screen, stage_sec=5.0)
    clock = pygame.time.Clock()
    while True:
        dt = clock.tick(60) / 1000.0
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                return
            if game.handle_event(e) == "quit":
                pygame.quit()
                return
        game.update(dt * game.speed)
        game.draw()
        pygame.display.flip()


# ---------------- 导出 ----------------
def export():
    pygame.init()
    screen = pygame.display.set_mode((W, H))
    game = WaterCycle(screen, stage_sec=STAGE_SEC_EXPORT)
    total = int(len(STAGES) * STAGE_SEC_EXPORT * FPS_EXPORT)   # 144 帧 / 12 秒
    out = os.path.dirname(os.path.abspath(__file__))
    frames = os.path.join(out, "_frames")
    os.makedirs(frames, exist_ok=True)
    for i in range(total):
        game.update(1.0 / FPS_EXPORT)
        game.draw()
        pygame.image.save(screen, os.path.join(frames, "f%04d.png" % i))

    mp4 = os.path.join(out, "水循环演示.mp4")
    cmd = ["ffmpeg", "-y", "-loglevel", "error", "-framerate", str(FPS_EXPORT),
           "-i", os.path.join(frames, "f%04d.png"),
           "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20",
           "-movflags", "+faststart", mp4]
    if subprocess.call(cmd) != 0:
        cmd = ["ffmpeg", "-y", "-loglevel", "error", "-framerate", str(FPS_EXPORT),
               "-i", os.path.join(frames, "f%04d.png"),
               "-c:v", "mpeg4", "-q:v", "4", mp4]
        subprocess.call(cmd)

    # GIF（缩小 + 调色板量化）
    gif = os.path.join(out, "水循环演示.gif")
    imgs = []
    for i in range(total):
        im = Image.open(os.path.join(frames, "f%04d.png" % i)).convert("RGB")
        im = im.resize((720, 450), Image.LANCZOS)
        imgs.append(im.quantize(colors=96, method=Image.MEDIANCUT))
    imgs[0].save(gif, save_all=True, append_images=imgs[1:],
                 duration=int(1000 / FPS_EXPORT), loop=0, optimize=True,
                 disposal=2)

    # 封面：降水阶段的关键帧
    cover = os.path.join(out, "水循环封面.png")
    Image.open(os.path.join(frames, "f%04d.png" % int(total * 0.42))).save(cover)

    print("导出完成：")
    for p in (mp4, gif, cover):
        print("  %s  %.2f MB" % (os.path.basename(p), os.path.getsize(p) / 1024 / 1024))
    for f in glob.glob(os.path.join(frames, "*.png")):
        os.remove(f)
    os.rmdir(frames)
    pygame.quit()


def test():
    pygame.init()
    screen = pygame.display.set_mode((W, H))
    g = WaterCycle(screen, stage_sec=2.0)
    stages_seen = set()
    for i in range(720):          # 60 秒模拟
        g.update(1.0 / 30)
        g.draw()
        stages_seen.add(g.stage)
        assert 0 <= g.condense <= 1.0, g.condense
        assert len(g.vapor) <= 260 and len(g.rain) <= 300
        for p in g.rain:
            assert 0 <= p["x"] <= W and p["y"] <= H, p
        for p in g.vapor:
            assert 0 <= p["x"] <= W and 0 <= p["y"] <= H, p
    assert stages_seen == set(range(6)), stages_seen
    for x in (0, 100, 469, 470, 600, 715, 960, 1200):
        assert 200 <= ground_y(x) <= 380, (x, ground_y(x))
    g.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_SPACE))
    assert g.paused
    g.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_SPACE))
    assert not g.paused
    for k in range(6):
        g.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_1 + k))
        assert g.stage == k
    print("逻辑自测通过：6 阶段完整轮转、粒子边界/数量、暂停与跳阶段、地形函数")
    pygame.quit()


if __name__ == "__main__":
    if TEST:
        test()
    elif EXPORT:
        export()
    else:
        main()
