import turtle
import random
import math

# ============ 基础设置 ============
W, H = 900, 620
screen = turtle.Screen()
screen.setup(W, H)
screen.title("水循环演示 · 蒸发/液化/降水/下渗/径流")
screen.bgcolor("#87CEEB")
screen.tracer(0)          # 关闭自动刷新，手动 update，避免闪烁
screen.delay(0)

# 画笔（用于快速绘制静态背景）
pen = turtle.Turtle(visible=False)
pen.speed(0)
pen.penup()

# 动画对象画笔池（每个对象一个 turtle，避免重影）
class Pen:
    def __init__(self, shape="circle"):
        self.t = turtle.Turtle(visible=False)
        self.t.speed(0)
        self.t.penup()
        self.t.shape(shape)

# ============ 静态背景 ============
def draw_background():
    pen.clear()
    pen.hideturtle()
    # 天空渐变（用横线模拟）
    for i in range(300):
        y = 120 + i
        c = i / 300
        r = int(120 + 135 * c)
        g = int(180 + 60 * c)
        b = int(230 + 20 * c)
        pen.goto(-W/2, y)
        pen.color((r/255, g/255, b/255))
        pen.pendown()
        pen.goto(W/2, y)
        pen.penup()
    # 远山
    pen.color("#6B8E9E")
    pen.goto(-450, 120)
    pen.begin_fill()
    for x, y in [(-450,120),(-300,260),(-150,150),(0,280),(150,160),(300,240),(450,120)]:
        pen.goto(x, y)
    pen.goto(450, 120)
    pen.goto(-450, 120)
    pen.end_fill()
    # 草地
    pen.color("#4CAF50")
    pen.goto(-450, -200)
    pen.begin_fill()
    pen.goto(-450, 120); pen.goto(450, 120); pen.goto(450, -200)
    pen.goto(-450, -200)
    pen.end_fill()
    # 地表线
    pen.color("#2E7D32")
    pen.pensize(2)
    pen.goto(-450, 120); pen.pendown(); pen.goto(450, 120); pen.penup()
    pen.pensize(1)
    # 湖泊
    pen.color("#2196F3")
    pen.goto(-200, 120)
    pen.begin_fill()
    pen.setheading(-90)
    pen.circle(40, 180)
    pen.end_fill()
    # 河流（曲线）
    pen.color("#1976D2")
    pen.pensize(8)
    pen.goto(-160, 120)
    pen.pendown()
    pts = [(-160,120),(-80,80),(0,90),(100,60),(200,40),(320,20),(450,10)]
    for x, y in pts[1:]:
        pen.goto(x, y)
    pen.penup()
    pen.pensize(1)
    # 大海
    pen.color("#0D47A1")
    pen.goto(200, -200)
    pen.begin_fill()
    pen.goto(200, 20); pen.goto(450, 10); pen.goto(450, -200)
    pen.goto(200, -200)
    pen.end_fill()
    # 地下土层（用于下渗示意）
    pen.color("#8D6E63")
    pen.goto(-450, -200)
    pen.begin_fill()
    pen.goto(-450, 120); pen.goto(450, 120); pen.goto(450, -200)
    pen.goto(-450, -200)
    pen.end_fill()
    # 地下水层
    pen.color("#5D4037")
    pen.goto(-450, -200)
    pen.begin_fill()
    pen.goto(-450, -120); pen.goto(450, -120); pen.goto(450, -200)
    pen.goto(-450, -200)
    pen.end_fill()
    # 标签
    pen.color("black")
    pen.goto(-430, 130); pen.write("蒸发 ↑", font=("Arial", 12, "bold"))
    pen.goto(-430, -170); pen.write("下渗 ↓ / 地下水", font=("Arial", 12, "bold"))
    pen.goto(300, 30); pen.write("地表径流 →", font=("Arial", 12, "bold"))
    pen.goto(300, -190); pen.write("大海", font=("Arial", 12, "bold"))
    pen.goto(-220, 60); pen.write("湖泊", font=("Arial", 12, "bold"))
    pen.goto(-20, 260); pen.write("云（液化）", font=("Arial", 12, "bold"))

# ============ 动画元素 ============
class Vapor:
    """蒸发的水汽"""
    def __init__(self):
        self.p = Pen()
        self.p.t.color("#B3E5FC")
        self.p.t.shapesize(0.35)
        self.reset()
    def reset(self):
        # 从湖面/海面/河流随机蒸发
        src = random.choice(["lake", "sea", "river"])
        if src == "lake":
            self.x = random.uniform(-240, -160)
            self.y = 120
        elif src == "sea":
            self.x = random.uniform(210, 440)
            self.y = random.uniform(10, 20)
        else:
            self.x = random.uniform(-150, 300)
            self.y = random.uniform(20, 110)
        self.vy = random.uniform(0.6, 1.2)
        self.phase = random.uniform(0, math.tau)
        self.alive = True
    def update(self):
        if not self.alive:
            return
        self.y += self.vy
        self.phase += 0.12
        self.x += math.sin(self.phase) * 0.6
        if self.y > 260:
            self.alive = False
        self.p.t.goto(self.x, self.y)
        self.p.t.showturtle()
    def hide(self):
        self.p.t.hideturtle()

class RainDrop:
    """降水"""
    def __init__(self):
        self.p = Pen()
        self.p.t.color("#1976D2")
        self.p.t.shapesize(0.3, 0.6)
        self.reset()
    def reset(self):
        self.x = random.uniform(-350, 400)
        self.y = random.uniform(230, 280)
        self.vy = random.uniform(3.5, 5.5)
        self.alive = True
    def update(self):
        if not self.alive:
            return
        self.y -= self.vy
        if self.y < 120:
            self.alive = False
        self.p.t.goto(self.x, self.y)
        self.p.t.showturtle()
    def hide(self):
        self.p.t.hideturtle()

class Seep:
    """下渗"""
    def __init__(self):
        self.p = Pen()
        self.p.t.color("#5D4037")
        self.p.t.shapesize(0.3)
        self.reset()
    def reset(self):
        self.x = random.uniform(-400, 400)
        self.y = 120
        self.vy = random.uniform(0.8, 1.5)
        self.alive = True
    def update(self):
        if not self.alive:
            return
        self.y -= self.vy
        if self.y < -120:
            self.alive = False
        self.p.t.goto(self.x, self.y)
        self.p.t.showturtle()
    def hide(self):
        self.p.t.hideturtle()

class Runoff:
    """地表径流（沿河流/斜坡流向大海）"""
    def __init__(self):
        self.p = Pen()
        self.p.t.color("#0D47A1")
        self.p.t.shapesize(0.35)
        self.reset()
    def reset(self):
        # 起点在草地/河流上游
        self.x = random.uniform(-380, -100)
        self.y = random.uniform(40, 110)
        self.vx = random.uniform(1.5, 2.8)
        self.vy = random.uniform(-0.8, -0.2)
        self.alive = True
    def update(self):
        if not self.alive:
            return
        self.x += self.vx
        self.y += self.vy
        # 接近海平面时趋近海面
        if self.x > 200:
            self.y += (10 - self.y) * 0.08
        if self.x > 440:
            self.alive = False
        self.p.t.goto(self.x, self.y)
        self.p.t.showturtle()
    def hide(self):
        self.p.t.hideturtle()

class Cloud:
    """云（液化聚集）"""
    def __init__(self, x, y, scale=1.0):
        self.p = Pen()
        self.p.t.color("#FFFFFF")
        self.x, self.y = x, y
        self.scale = scale
        self.water = 0
        self.dx = random.choice([-1, 1]) * random.uniform(0.1, 0.3)
    def draw(self):
        self.p.t.clear()
        self.p.t.penup()
        # 用几个圆画云
        offsets = [(-18,0,1.0),(0,6,1.2),(18,0,1.0),(8,-6,0.8),(-8,-6,0.8)]
        for ox, oy, s in offsets:
            r = 14 * s * self.scale
            self.p.t.goto(self.x + ox*self.scale, self.y + oy*self.scale - r)
            self.p.t.color("#FFFFFF" if self.water < 6 else "#9E9E9E")
            self.p.t.begin_fill()
            self.p.t.circle(r)
            self.p.t.end_fill()
    def update(self):
        self.x += self.dx
        if self.x > 420 or self.x < -420:
            self.dx *= -1
        if self.water >= 10:
            self.water = 0
        self.draw()

# ============ 主循环 ============
def main():
    draw_background()

    vapors = [Vapor() for _ in range(18)]
    rains = [RainDrop() for _ in range(20)]
    seeps = [Seep() for _ in range(12)]
    runoffs = [Runoff() for _ in range(10)]
    clouds = [Cloud(-250, 250, 1.1), Cloud(0, 280, 1.0), Cloud(250, 255, 1.2)]

    # 初始全部隐藏
    for v in vapors: v.hide()
    for r in rains: r.hide()
    for s in seeps: s.hide()
    for r in runoffs: r.hide()

    frame = 0
    while True:
        frame += 1
        # 云吸收水汽，水汽到顶后"液化"进云
        for c in clouds:
            c.update()

        for v in vapors:
            if v.alive:
                v.update()
                # 到达云层高度，被云吸收
                if v.y > 220:
                    for c in clouds:
                        if abs(v.x - c.x) < 60:
                            c.water += 1
                            break
            else:
                v.reset()
                v.hide()

        # 云够水就下雨
        for c in clouds:
            if c.water >= 8 and random.random() < 0.15:
                for r in rains:
                    if not r.alive:
                        r.reset()
                        r.x = c.x + random.uniform(-40, 40)
                        r.y = c.y - 10
                        c.water -= 1
                        break

        for r in rains:
            if r.alive:
                r.update()
                # 落地后：一部分下渗，一部分形成径流
                if not r.alive:
                    if random.random() < 0.5:
                        for s in seeps:
                            if not s.alive:
                                s.reset()
                                s.x = r.x
                                break
                    else:
                        for ro in runoffs:
                            if not ro.alive:
                                ro.reset()
                                ro.x = r.x
                                ro.y = 110
                                break
            else:
                r.hide()

        for s in seeps:
            if s.alive:
                s.update()
            else:
                s.hide()

        for ro in runoffs:
            if ro.alive:
                ro.update()
            else:
                ro.hide()

        screen.update()   # 一次性刷新，避免闪烁
        turtle.delay(15)

if __name__ == "__main__":
    main()