import pygame
import sys
import random
import math

# ── 初始化 ──
pygame.init()
W, H = 1100, 650
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("🌊 水循环演示动画 · Water Cycle Demo")
clock = pygame.time.Clock()
FPS = 60

# ── 配色 ──
SKY_DAY_TOP    = (70, 150, 230)
SKY_DAY_BOT    = (170, 215, 245)
SKY_EVE_TOP    = (50, 80, 160)
SKY_EVE_BOT    = (255, 180, 100)
OCEAN_DEEP     = (20, 70, 150)
OCEAN_SHALLOW  = (50, 130, 210)
GROUND_BROWN   = (120, 85, 50)
GROUND_LIGHT   = (150, 115, 70)
GREEN_BRT      = (60, 180, 70)
GREEN_DK       = (35, 120, 40)
CLOUD_WHITE    = (250, 250, 255)
SUN_YELLOW     = (255, 225, 70)
SNOW_WHITE     = (230, 240, 255)
TEXT_DARK      = (30, 30, 50)
WHITE          = (255, 255, 255)
BLACK          = (20, 20, 30)
GOLD           = (255, 200, 50)
ORANGE         = (255, 140, 50)

try:
    font_xs = pygame.font.SysFont("simhei,arial", 12)
    font_s  = pygame.font.SysFont("simhei,arial", 16)
    font_m  = pygame.font.SysFont("simhei,arial", 22)
    font_l  = pygame.font.SysFont("simhei,arial", 32, bold=True)
    font_xl = pygame.font.SysFont("simhei,arial", 48, bold=True)
except:
    font_xs = pygame.font.Font(None, 14)
    font_s  = pygame.font.Font(None, 18)
    font_m  = pygame.font.Font(None, 24)
    font_l  = pygame.font.Font(None, 36)
    font_xl = pygame.font.Font(None, 52)


# ═══════════════════════ 粒子系统 ═══════════════════════

class Particle:
    def __init__(self, x, y, vx, vy, color, life, size=3):
        self.x = x
        self.y = y
        self.vx = vx
        self.vy = vy
        self.color = color
        self.life = life
        self.max_life = life
        self.size = size

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

    def draw(self, surf):
        alpha = int(255 * max(0, self.life / self.max_life))
        s = pygame.Surface((self.size * 2 + 2, self.size * 2 + 2), pygame.SRCALPHA)
        pygame.draw.circle(s, (*self.color, alpha),
                          (self.size + 1, self.size + 1), self.size)
        surf.blit(s, (self.x - self.size - 1, self.y - self.size - 1))


# ═══════════════════════ 太阳 ═══════════════════════

class Sun:
    def __init__(self):
        self.x = 900
        self.y = 80
        self.angle = 0
        self.glow = 0

    def update(self, dt):
        self.angle += dt * 0.5
        self.glow += dt * 3

    def draw(self, surf):
        # 光晕
        r = 50 + math.sin(self.glow) * 5
        for i in range(5):
            a = max(0, 80 - i * 15)
            s = pygame.Surface((int(r)*2, int(r)*2), pygame.SRCALPHA)
            pygame.draw.circle(s, (*SUN_YELLOW, a), (int(r), int(r)), int(r) - i * 6)
            surf.blit(s, (self.x - int(r), self.y - int(r)))

        # 光芒
        for i in range(16):
            a = self.angle + i * math.pi / 8
            x1 = self.x + math.cos(a) * 38
            y1 = self.y + math.sin(a) * 25
            x2 = self.x + math.cos(a) * 58
            y2 = self.y + math.sin(a) * 38
            pygame.draw.line(surf, (*SUN_YELLOW, 180), (x1, y1), (x2, y2), 2)

        # 本体
        for r in range(36, 26, -2):
            shade = (36 - r) * 4
            pygame.draw.circle(surf, (255, 255 - shade, 70 - shade), (self.x, self.y), r)

        # 脸
        pygame.draw.circle(surf, BLACK, (self.x - 10, self.y - 5), 3)
        pygame.draw.circle(surf, BLACK, (self.x + 10, self.y - 5), 3)
        pygame.draw.arc(surf, BLACK, (self.x - 14, self.y + 5, 28, 14), 0.1, math.pi - 0.1, 2)


# ═══════════════════════ 云 ═══════════════════════

class Cloud:
    def __init__(self, x, y, scale=1.0):
        self.x = x
        self.y = y
        self.scale = scale
        self.speed = random.uniform(15, 35)
        self.bubbles = []
        for _ in range(random.randint(5, 9)):
            self.bubbles.append({
                'ox': random.uniform(-40, 40) * scale,
                'oy': random.uniform(-15, 10) * scale,
                'r': random.uniform(20, 40) * scale,
            })
        self.mood = "normal"
        self.rain_drops = []

    def update(self, dt, raining, phase):
        self.x += self.speed * dt

        # 循环
        if self.x > W + 60:
            self.x = -80
        elif self.x < -80:
            self.x = W + 60

        # 情绪
        if raining:
            self.mood = "sad"
        elif phase == 2:  # 凝结
            self.mood = "happy"
        else:
            self.mood = "normal"

        # 下雨
        if raining and random.random() < 0.15 * dt * 60:
            for _ in range(2):
                rx = self.x + random.uniform(-30, 30)
                ry = self.y + 20
                self.rain_drops.append(
                    Particle(rx, ry, random.uniform(-10, 10), random.uniform(200, 350),
                            (60, 140, 230), random.uniform(1.5, 2.5), random.randint(2, 4))
                )

        # 更新雨滴
        self.rain_drops = [d for d in self.rain_drops if d.update(dt)]

    def draw(self, surf):
        # 云体
        for b in self.bubbles:
            cx = int(self.x + b['ox'])
            cy = int(self.y + b['oy'])
            r = int(b['r'])
            for rr in range(r, max(0, r - 12), -3):
                t = (r - rr) / 12
                cr = int(250 - t * 15)
                cg = int(250 - t * 15)
                cb = int(255 - t * 5)
                pygame.draw.circle(surf, (cr, cg, cb), (cx, cy + int(t * 4)), rr)

        # 脸
        pygame.draw.circle(surf, BLACK, (self.x - 12, self.y + 2), 3)
        pygame.draw.circle(surf, BLACK, (self.x + 12, self.y + 2), 3)

        if self.mood == "sad":
            pygame.draw.arc(surf, BLACK, (self.x - 14, self.y + 10, 28, 12),
                           math.pi, 2 * math.pi, 2)
        elif self.mood == "happy":
            pygame.draw.arc(surf, BLACK, (self.x - 14, self.y + 6, 28, 12), 0.1, math.pi - 0.1, 2)
        else:
            pygame.draw.line(surf, BLACK, (self.x - 10, self.y + 10), (self.x + 10, self.y + 10), 2)

        # 雨滴
        for d in self.rain_drops:
            d.draw(surf)


# ═══════════════════════ 海洋 ═══════════════════════

class Ocean:
    def __init__(self):
        self.waves = []
        self.particles = []
        for i in range(20):
            self.waves.append({
                'x': i * 60,
                'offset': random.uniform(0, 2 * math.pi),
                'speed': random.uniform(1.5, 2.5),
                'height': random.uniform(8, 15),
            })

    def update(self, dt, evaporating):
        for w in self.waves:
            w['offset'] += w['speed'] * dt

        # 蒸发气泡
        if evaporating and random.random() < 0.2 * dt * 60:
            x = random.randint(50, 400)
            y = H - 120 + random.randint(-5, 5)
            self.particles.append(
                Particle(x, y, random.uniform(-20, 20), random.uniform(-60, -30),
                        (180, 210, 240), random.uniform(2, 4), random.randint(2, 5))
            )

        self.particles = [p for p in self.particles if p.update(dt)]

    def draw(self, surf):
        ocean_y = H - 120

        # 海洋主体
        pygame.draw.rect(surf, OCEAN_DEEP, (0, ocean_y, W, 120))

        # 波浪层
        for layer in range(3):
            alpha = 200 - layer * 40
            offset_y = layer * 15
            points = [(0, ocean_y + offset_y)]
            for x in range(0, W + 10, 5):
                y = ocean_y + offset_y + math.sin(x * 0.02 + self.waves[x // 60 % len(self.waves)]['offset']) * 5
                points.append((x, y))
            points.append((W, ocean_y + 60))
            points.append((0, ocean_y + 60))

            s = pygame.Surface((W, 60), pygame.SRCALPHA)
            pygame.draw.polygon(s, (*OCEAN_SHALLOW, alpha), points)
            surf.blit(s, (0, offset_y))

        # 蒸发粒子
        for p in self.particles:
            p.draw(surf)


# ═══════════════════════ 地面 ═══════════════════════

class Ground:
    def __init__(self):
        self.mountains = []
        for i in range(5):
            self.mountains.append({
                'x': 400 + i * 160,
                'h': random.randint(60, 100),
                'w': random.randint(80, 120),
            })

        self.plants = []
        for _ in range(12):
            self.plants.append({
                'x': random.randint(450, W - 50),
                'y': H - 120,
                'max_h': random.randint(20, 45),
                'growth': random.uniform(0.2, 0.9),
            })

    def update(self, dt, raining):
        for p in self.plants:
            if raining and p['growth'] < 1.0:
                p['growth'] += dt * 0.04
            elif not raining and p['growth'] > 0.1:
                p['growth'] -= dt * 0.015

    def draw(self, surf):
        ground_y = H - 120

        # 泥土
        pygame.draw.rect(surf, GROUND_BROWN, (400, ground_y, W - 400, 120))

        # 山脉
        for m in self.mountains:
            points = [
                (m['x'] - m['w'], ground_y),
                (m['x'], ground_y - m['h']),
                (m['x'] + m['w'], ground_y),
            ]
            pygame.draw.polygon(surf, GROUND_LIGHT, points)

            # 雪顶
            snow_h = m['h'] * 0.3
            snow_points = [
                (m['x'] - m['w'] * snow_h / m['h'] * 0.8, ground_y - m['h'] + snow_h),
                (m['x'], ground_y - m['h']),
                (m['x'] + m['w'] * snow_h / m['h'] * 0.8, ground_y - m['h'] + snow_h),
            ]
            pygame.draw.polygon(surf, SNOW_WHITE, snow_points)

        # 草地
        for x in range(400, W, 6):
            gh = random.randint(3, 10)
            pygame.draw.line(surf, GREEN_DK, (x, ground_y), (x + random.randint(-2, 2), ground_y - gh), 2)

        # 植物
        for p in self.plants:
            h = p['max_h'] * p['growth']
            if h < 3:
                continue

            # 茎
            pygame.draw.line(surf, GREEN_DK, (p['x'], ground_y), (p['x'], ground_y - h), 3)

            # 叶子
            pygame.draw.polygon(surf, GREEN_BRT, [
                (p['x'], ground_y - h * 0.6),
                (p['x'] - 8, ground_y - h * 0.5),
                (p['x'] + 2, ground_y - h * 0.4),
            ])
            pygame.draw.polygon(surf, GREEN_BRT, [
                (p['x'], ground_y - h * 0.8),
                (p['x'] + 8, ground_y - h * 0.7),
                (p['x'] - 2, ground_y - h * 0.6),
            ])

            # 花
            if h > 20:
                pygame.draw.circle(surf, (255, 200, 50), (p['x'], ground_y - h), 5)


# ═══════════════════════ 蒸发粒子（从地面） ═══════════════════════

class EvaporateSystem:
    def __init__(self):
        self.particles = []

    def spawn(self, x, y):
        self.particles.append(
            Particle(x, y, random.uniform(-15, 15), random.uniform(-80, -40),
                    (200, 220, 255), random.uniform(2.5, 4.5), random.randint(2, 5))
        )

    def update(self, dt):
        self.particles = [p for p in self.particles if p.update(dt)]

    def draw(self, surf):
        for p in self.particles:
            p.draw(surf)


# ═══════════════════════ 流程图标签 ═══════════════════════

class PhaseLabel:
    def __init__(self, text, x, y, color):
        self.text = text
        self.x = x
        self.y = y
        self.color = color
        self.alpha = 0
        self.target_alpha = 255

    def update(self, dt, active):
        self.target_alpha = 255 if active else 100
        speed = 300 * dt
        if self.alpha < self.target_alpha:
            self.alpha = min(self.target_alpha, self.alpha + speed)
        else:
            self.alpha = max(self.target_alpha, self.alpha - speed)

    def draw(self, surf):
        s = pygame.Surface((180, 50), pygame.SRCALPHA)
        pygame.draw.rect(s, (*self.color, int(self.alpha * 0.2)),
                        (0, 0, 180, 50), border_radius=10)
        pygame.draw.rect(s, (*self.color, int(self.alpha * 0.6)),
                        (0, 0, 180, 50), 2, border_radius=10)

        t = font_m.render(self.text, True, (*self.color, int(self.alpha)))
        s.blit(t, (90 - t.get_width() // 2, 25 - t.get_height() // 2))
        surf.blit(s, (self.x - 90, self.y - 25))


# ═══════════════════════ 主模拟 ═══════════════════════════

class WaterCycleDemo:
    def __init__(self):
        self.sun = Sun()
        self.clouds = [Cloud(random.randint(0, W), random.randint(60, 150),
                             random.uniform(0.7, 1.1)) for _ in range(5)]
        self.ocean = Ocean()
        self.ground = Ground()
        self.evaporates = EvaporateSystem()

        # 阶段
        self.phase = 0  # 0=降水 1=蒸发 2=凝结
        self.timer = 0
        self.phase_duration = [8, 10, 8]  # 各阶段时长(秒)
        self.raining = True
        self.evaporating = False

        # 阶段标签
        self.labels = [
            PhaseLabel("① 降水 Precipitation", 150, 320, (50, 150, 255)),
            PhaseLabel("② 蒸发 Evaporation", 420, 200, (255, 180, 50)),
            PhaseLabel("③ 凝结 Condensation", 700, 200, (150, 150, 255)),
        ]

        # 解说文本
        self.descriptions = [
            "雨水从云层降落到地面和海洋",
            "太阳热量使地表水变成水蒸气上升",
            "水蒸气在高空遇冷凝结成云",
        ]

        # 背景装饰
        self.stars = [(random.randint(0, W), random.randint(0, H//2), random.uniform(0.5, 2))
                      for _ in range(40)]

        self.paused = False

    def update(self, dt):
        if self.paused:
            dt = 0

        self.timer += dt

        # 阶段切换
        dur = self.phase_duration[self.phase]
        if self.timer >= dur:
            self.phase = (self.phase + 1) % 3
            self.timer = 0

            if self.phase == 0:
                self.raining = True
                self.evaporating = False
            elif self.phase == 1:
                self.raining = False
                self.evaporating = True
            else:  # phase 2
                self.raining = False
                self.evaporating = False

        # 更新各元素
        self.sun.update(dt)

        for c in self.clouds:
            c.update(dt, self.raining, self.phase)

        self.ocean.update(dt, self.evaporating)

        if self.evaporating and random.random() < 0.3 * dt * 60:
            x = random.randint(50, 350)
            y = H - 120 + random.randint(-10, 10)
            self.evaporates.spawn(x, y)

        self.evaporates.update(dt)

        self.ground.update(dt, self.raining)

        # 更新标签
        for i, lbl in enumerate(self.labels):
            lbl.update(dt, i == self.phase)

    def draw_sky(self, surf):
        """天空渐变"""
        if self.phase == 0:
            top, bot = SKY_DAY_TOP, SKY_DAY_BOT
        elif self.phase == 1:
            top, bot = (50, 170, 240), (180, 230, 250)
        else:  # 凝结
            top, bot = SKY_EVE_TOP, SKY_EVE_BOT

        for y in range(H):
            t = y / H
            r = int(top[0] + (bot[0] - top[0]) * t)
            g = int(top[1] + (bot[1] - top[1]) * t)
            b = int(top[2] + (bot[2] - top[2]) * t)
            pygame.draw.line(surf, (r, g, b), (0, y), (W, y))

        # 星星（凝结阶段）
        if self.phase == 2:
            tw = pygame.time.get_ticks() * 0.002
            for sx, sy, sr in self.stars:
                a = int(80 + 60 * math.sin(tw + sx * 0.01))
                s = pygame.Surface((6, 6), pygame.SRCALPHA)
                pygame.draw.circle(s, (255, 255, 255, a), (3, 3), int(sr))
                surf.blit(s, (sx - 3, sy - 3))

    def draw_flow_arrows(self, surf):
        """流程箭头"""
        arrows = [
            # (起点, 终点, 颜色, 标签)
            ((200, H - 60), (200, 100), (50, 150, 255), "↓ 降水"),
            ((200, 100), (500, 100), (255, 180, 50), "→ 蒸发"),
            ((500, 100), (750, 100), (150, 150, 255), "→ 凝结"),
            ((750, 100), (750, H - 60), (50, 150, 255), "↓ 降水"),
        ]

        for (x1, y1), (x2, y2), col, label in arrows:
            # 箭头线
            pygame.draw.line(surf, col, (x1, y1), (x2, y2), 3)

            # 箭头头部
            if x1 == x2:  # 垂直
                direction = 1 if y2 > y1 else -1
                ax, ay = x2, y2
                pygame.draw.polygon(surf, col, [
                    (ax - 6, ay - direction * 10),
                    (ax + 6, ay - direction * 10),
                    (ax, ay),
                ])
            else:  # 水平
                direction = 1 if x2 > x1 else -1
                ax, ay = x2, y2
                pygame.draw.polygon(surf, col, [
                    (ax - direction * 10, ay - 6),
                    (ax - direction * 10, ay + 6),
                    (ax, ay),
                ])

            # 标签
            mx = (x1 + x2) / 2
            my = (y1 + y2) / 2
            t = font_s.render(label, True, col)
            if x1 == x2:
                surf.blit(t, (mx + 10, my - t.get_height() // 2))
            else:
                surf.blit(t, (mx - t.get_width() // 2, my - 20))

    def draw(self, surf):
        self.draw_sky(surf)

        # 太阳
        self.sun.draw(surf)

        # 云
        for c in self.clouds:
            c.draw(surf)

        # 蒸发粒子
        self.evaporates.draw(surf)

        # 海洋
        self.ocean.draw(surf)

        # 地面
        self.ground.draw(surf)

        # 流程箭头
        self.draw_flow_arrows(surf)

        # 阶段标签
        for lbl in self.labels:
            lbl.draw(surf)

        # UI
        self.draw_ui(surf)

    def draw_ui(self, surf):
        # 顶部栏
        panel = pygame.Surface((W, 70), pygame.SRCALPHA)
        panel.fill((0, 0, 0, 130))
        surf.blit(panel, (0, 0))

        # 标题
        title = font_xl.render("🌊 水循环演示", True, (255, 255, 100))
        surf.blit(title, (15, 8))

        # 阶段名
        phase_colors = [(50, 180, 255), (255, 200, 50), (150, 150, 255)]
        col = phase_colors[self.phase]
        pn = font_l.render(f"阶段 {self.phase + 1}: {self.descriptions[self.phase]}",
                          True, col)
        surf.blit(pn, (320, 18))

        # 暂停指示
        if self.paused:
            pause_t = font_m.render("⏸ 暂停", True, (255, 100, 100))
            surf.blit(pause_t, (W - 80, 25))

        # 底部进度条
        bar_y = H - 25
        bar_h = 20
        total_dur = sum(self.phase_duration)
        elapsed = sum(self.phase_duration[:self.phase]) + self.timer
        progress = elapsed / total_dur

        # 背景
        pygame.draw.rect(surf, (50, 50, 70), (0, bar_y, W, bar_h))

        # 三阶段色块
        seg_w = W / 3
        for i, col in enumerate(phase_colors):
            seg_progress = max(0, min(1, (progress - i / 3) * 3))
            if seg_progress > 0:
                pw = int(seg_w * seg_progress)
                pygame.draw.rect(surf, col, (i * seg_w, bar_y, pw, bar_h))

        # 分隔线
        for i in range(1, 3):
            pygame.draw.line(surf, BLACK, (i * seg_w, bar_y), (i * seg_w, bar_y + bar_h), 2)

        # 提示
        hint = font_s.render(
            "SPACE=暂停 | →=下一阶段 | R=切换下雨 | ESC=退出",
            True, (180, 180, 180)
        )
        surf.blit(hint, (W // 2 - hint.get_width() // 2, bar_y + 3))


# ═══════════════════════ 主循环 ═══════════════════════════

def main():
    demo = WaterCycleDemo()
    prev_time = pygame.time.get_ticks()

    while True:
        current_time = pygame.time.get_ticks()
        dt = (current_time - prev_time) / 1000.0
        prev_time = current_time

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == pygame.K_SPACE:
                    demo.paused = not demo.paused
                if event.key == pygame.K_RIGHT:
                    demo.phase = (demo.phase + 1) % 3
                    demo.timer = 0
                    demo.raining = (demo.phase == 0)
                    demo.evaporating = (demo.phase == 1)
                if event.key == pygame.K_r:
                    demo.raining = not demo.raining
                    if demo.raining:
                        demo.phase = 0
                    else:
                        demo.phase = 1
                    demo.timer = 0

        demo.update(dt)
        demo.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)


if __name__ == "__main__":
    main()