import pygame
import math
import random
import sys

# ==================== 初始化 ====================
pygame.init()
WIDTH, HEIGHT = 1200, 750
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("水循环 3D 演示 - 雪山 · 植物 · 海洋 · 蒸发 · 降雨 · 下渗")
clock = pygame.time.Clock()

# ========== 关键修复：安全字体加载 ==========
def load_font(size, bold=False):
    # 依次尝试：中文字体 → 默认字体
    for name in ["microsoftyahei", "simhei", "simsun", "arial", "freesansbold"]:
        try:
            f = pygame.font.SysFont(name, size, bold=bold)
            return f
        except Exception:
            continue
    # 兜底：使用 pygame 内置字体（不受系统字体影响）
    return pygame.font.Font(None, size)

font = load_font(22)
small_font = load_font(16)
# ============================================

# ==================== 渐变背景 ====================
def create_gradient_bg():
    bg = pygame.Surface((WIDTH, HEIGHT))
    for y in range(HEIGHT):
        t = y / HEIGHT
        r = int(10 + t * 150)
        g = int(40 + t * 160)
        b = int(90 + t * 120)
        pygame.draw.line(bg, (min(r, 255), min(g, 255), min(b, 255)), (0, y), (WIDTH, y))
    return bg

bg_surface = create_gradient_bg()

# ==================== 等距 3D 坐标转换 ====================
def iso(wx, wy, wz):
    sx = WIDTH // 2 + (wx - wz) * 0.9
    sy = HEIGHT // 2 + (wx + wz) * 0.35 - wy * 1.1
    return int(sx), int(sy)

# ==================== 静态元素绘制 ====================
def draw_sun(surf, cx, cy, radius, t):
    for i in range(6, 0, -1):
        alpha = 30 - i * 4
        glow_r = radius + i * 8 + int(math.sin(t * 2) * 3)
        glow_surf = pygame.Surface((glow_r * 2, glow_r * 2), pygame.SRCALPHA)
        pygame.draw.circle(glow_surf, (255, 200, 80, max(alpha, 5)),
                           (glow_r, glow_r), glow_r)
        surf.blit(glow_surf, (cx - glow_r, cy - glow_r))
    pygame.draw.circle(surf, (255, 230, 120), (cx, cy), radius)
    pygame.draw.circle(surf, (255, 250, 200), (cx, cy), radius - 6)

def draw_mountain(surf, wx, wz, base_radius, height, body_color):
    base_pts = []
    for i in range(12):
        a = i / 12 * math.pi * 2
        bx = wx + math.cos(a) * base_radius
        bz = wz + math.sin(a) * base_radius
        base_pts.append(iso(bx, 0, bz))
    peak = iso(wx, height, wz)
    for i in range(len(base_pts)):
        p1 = base_pts[i]
        p2 = base_pts[(i + 1) % len(base_pts)]
        shade = 0.6 + 0.4 * ((i % 2) == 0)
        col = tuple(int(c * shade) for c in body_color)
        pygame.draw.polygon(surf, col, [p1, p2, peak])
    # 雪顶
    snow_h = height * 0.72
    snow_pts = []
    for i in range(12):
        a = i / 12 * math.pi * 2
        sx = wx + math.cos(a) * base_radius * 0.4
        sz = wz + math.sin(a) * base_radius * 0.4
        snow_pts.append(iso(sx, snow_h, sz))
    snow_peak = iso(wx, height, wz)
    for i in range(len(snow_pts)):
        p1 = snow_pts[i]
        p2 = snow_pts[(i + 1) % len(snow_pts)]
        pygame.draw.polygon(surf, (240, 248, 255), [p1, p2, snow_peak])

def draw_ocean(surf, cx, cz, rx, rz, t):
    pts = []
    for i in range(36):
        a = i / 36 * math.pi * 2
        wx = cx + math.cos(a) * rx
        wz = cz + math.sin(a) * rz
        pts.append(iso(wx, 0, wz))
    pygame.draw.polygon(surf, (30, 90, 150), pts)
    pygame.draw.polygon(surf, (40, 120, 180), pts, 3)
    for i in range(40):
        a = random.random() * math.pi * 2
        r = random.random()
        wx = cx + math.cos(a) * rx * r
        wz = cz + math.sin(a) * rz * r
        sx, sy = iso(wx, 0, wz)
        if math.sin(t * 3 + i) > 0.3:
            pygame.draw.circle(surf, (200, 230, 255), (sx, sy), 2)

def draw_river(surf, t):
    river_pts = [(150, -200), (60, -120), (-20, -60), (-80, 20), (-150, 80)]
    screen_pts = [iso(x, 0.5, z) for (x, z) in river_pts]
    smooth_pts = []
    for i in range(len(screen_pts) - 1):
        p1 = screen_pts[i]
        p2 = screen_pts[i + 1]
        for s in range(10):
            u = s / 10
            x = p1[0] + (p2[0] - p1[0]) * u
            y = p1[1] + (p2[1] - p1[1]) * u
            smooth_pts.append((int(x), int(y)))
    for i, p in enumerate(smooth_pts):
        width = max(2, 10 - i // 30)
        pygame.draw.circle(surf, (70, 170, 240), p, width // 2)
    for i in range(8):
        idx = int((t * 30 + i * 40) % len(smooth_pts))
        pygame.draw.circle(surf, (220, 240, 255), smooth_pts[idx], 3)

def draw_tree(surf, wx, wz, size=1.0):
    base = iso(wx, 0, wz)
    top = iso(wx, size * 40, wz)
    pygame.draw.line(surf, (90, 60, 30), base, top, 4)
    cx, cy = top
    pygame.draw.circle(surf, (30, 130, 50), (cx, cy - 8), int(18 * size))
    pygame.draw.circle(surf, (40, 160, 70), (cx - 12, cy + 4), int(14 * size))
    pygame.draw.circle(surf, (50, 180, 80), (cx + 12, cy + 4), int(14 * size))

def draw_bush(surf, wx, wz):
    cx, cy = iso(wx, 0, wz)
    pygame.draw.circle(surf, (40, 140, 60), (cx, cy - 5), 10)
    pygame.draw.circle(surf, (60, 170, 80), (cx - 8, cy), 8)
    pygame.draw.circle(surf, (50, 160, 70), (cx + 8, cy), 8)

# ==================== 动态粒子 ====================
class RainDrop:
    def __init__(self):
        self.reset()
    def reset(self):
        self.wx = random.uniform(-300, 400)
        self.wz = random.uniform(-400, 200)
        self.wy = random.uniform(220, 320)
        self.speed = random.uniform(4, 8)
    def update(self):
        self.wy -= self.speed
        if self.wy <= 0:
            self.reset()
    def draw(self, surf):
        sx, sy = iso(self.wx, self.wy, self.wz)
        pygame.draw.line(surf, (170, 210, 255), (sx, sy), (sx, sy + 10), 2)

class Vapor:
    def __init__(self):
        self.reset()
    def reset(self):
        self.wx = random.uniform(-400, 50)
        self.wz = random.uniform(-250, 250)
        self.wy = 10
        self.speed = random.uniform(0.8, 2.0)
        self.phase = random.random() * math.pi * 2
    def update(self, t):
        self.wy += self.speed
        self.wx += math.sin(t + self.phase) * 0.6
        if self.wy > 260:
            self.reset()
    def draw(self, surf):
        sx, sy = iso(self.wx, self.wy, self.wz)
        pygame.draw.circle(surf, (210, 235, 255), (sx, sy), 4)

class Infiltration:
    def __init__(self):
        self.reset()
    def reset(self):
        self.wx = random.uniform(-350, 400)
        self.wz = random.uniform(-350, 250)
        self.wy = random.uniform(0, 30)
        self.speed = random.uniform(0.3, 0.8)
    def update(self):
        self.wy -= self.speed
        if self.wy < -20:
            self.reset()
    def draw(self, surf):
        sx, sy = iso(self.wx, self.wy, self.wz)
        pygame.draw.circle(surf, (140, 200, 255), (sx, sy), 3)

class Cloud:
    def __init__(self):
        self.reset()
    def reset(self):
        self.wx = random.uniform(-400, 400)
        self.wz = random.uniform(-400, 100)
        self.wy = random.uniform(240, 320)
        self.speed = random.uniform(0.3, 1.0)
        self.scale = random.uniform(0.8, 1.6)
    def update(self):
        self.wx += self.speed
        if self.wx > 500:
            self.wx = -500
    def draw(self, surf):
        sx, sy = iso(self.wx, self.wy, self.wz)
        s = self.scale
        pygame.draw.ellipse(surf, (255, 255, 255),
                            (sx - 60 * s, sy - 20 * s, 120 * s, 50 * s))
        pygame.draw.ellipse(surf, (250, 250, 255),
                            (sx - 40 * s, sy - 35 * s, 80 * s, 50 * s))
        pygame.draw.ellipse(surf, (245, 245, 255),
                            (sx - 80 * s, sy - 10 * s, 70 * s, 40 * s))
        pygame.draw.ellipse(surf, (220, 225, 235),
                            (sx - 55 * s, sy + 5 * s, 110 * s, 20 * s))

# ==================== 场景数据 ====================
mountains = [
    dict(wx=-80, wz=-400, r=110, h=280, col=(100, 80, 60)),
    dict(wx=90, wz=-420, r=90, h=230, col=(90, 70, 55)),
    dict(wx=-200, wz=-360, r=70, h=180, col=(110, 90, 70)),
    dict(wx=200, wz=-380, r=80, h=200, col=(95, 75, 60)),
]

plants = [
    (-250, -100), (280, -80), (-320, -180), (350, -150),
    (-150, -20), (180, 0), (-400, -50), (400, -30),
    (100, 50), (-50, 60), (250, 100), (-300, 120),
    (0, 200), (-200, 180), (300, 220), (-380, 200),
    (150, 300), (-150, 320),
]
bushes = [
    (-280, 40), (220, 60), (-120, 100), (320, 140),
    (-400, 100), (400, 80), (50, 250), (-250, 260),
]

raindrops = [RainDrop() for _ in range(180)]
vapors = [Vapor() for _ in range(120)]
infiltrations = [Infiltration() for _ in range(150)]
clouds = [Cloud() for _ in range(8)]

# ==================== 主循环 ====================
start_time = pygame.time.get_ticks()
running = True
while running:
    t = (pygame.time.get_ticks() - start_time) / 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:
                running = False

    screen.blit(bg_surface, (0, 0))
    draw_sun(screen, 150, 100, 45, t)

    for c in clouds:
        c.update()
        c.draw(screen)

    sorted_mountains = sorted(mountains, key=lambda m: m['wz'])
    for m in sorted_mountains:
        draw_mountain(screen, m['wx'], m['wz'], m['r'], m['h'], m['col'])

    draw_ocean(screen, -200, 200, 280, 160, t)
    draw_river(screen, t)

    all_plants = [(x, z, 'tree') for (x, z) in plants] + \
                 [(x, z, 'bush') for (x, z) in bushes]
    all_plants.sort(key=lambda p: p[1])
    for (x, z, kind) in all_plants:
        if kind == 'tree':
            draw_tree(screen, x, z)
        else:
            draw_bush(screen, x, z)

    for v in vapors:
        v.update(t)
        v.draw(screen)

    for r in raindrops:
        r.update()
        r.draw(screen)

    for inf in infiltrations:
        inf.update()
        inf.draw(screen)

    # 顶部信息（用内置字体，中文可能显示方块；建议用英文或已加载成功的中文字体）
    title = font.render("Water Cycle 3D Demo", True, (255, 255, 255))
    screen.blit(title, (20, 20))
    subtitle = small_font.render(
        "Sun -> Evaporation -> Clouds -> Rain -> Infiltration / River -> Ocean",
        True, (230, 240, 255))
    screen.blit(subtitle, (20, 55))

    legend_items = [
        ("Sun", (255, 230, 120)),
        ("Vapor", (200, 235, 255)),
        ("Cloud & Rain", (255, 255, 255)),
        ("River", (70, 170, 240)),
        ("Infiltration", (140, 200, 255)),
    ]
    for i, (txt, col) in enumerate(legend_items):
        s = small_font.render(txt, True, col)
        screen.blit(s, (WIDTH - 200, 20 + i * 25))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()