#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
水的三态变化 · 动态演示（自绘彩色温度滑条，方向正确）
纯 Python 实现（tkinter），无需安装第三方库。
运行: python water_states.py
"""

import tkinter as tk
import math
import random
import time

# ================= 可调参数 =================
N = 100
R_PART = 0.22
R0 = 0.52
BW, BH = 8.0, 8.0

CANVAS_W, CANVAS_H = 960, 660
PAD_L, PAD_T, PAD_R, PAD_B = 55, 30, 200, 110

S = min((CANVAS_W - PAD_L - PAD_R) / BW,
        (CANVAS_H - PAD_T - PAD_B) / BH)
OFF_X = PAD_L + ((CANVAS_W - PAD_L - PAD_R) - BW * S) / 2
OFF_Y = PAD_T + ((CANVAS_H - PAD_T - PAD_B) - BH * S) / 2

E1, E2, E3, E4, E5 = 20.0, 50.0, 110.0, 170.0, 200.0
PERIOD = 40.0
FIXED_DT = 1.0 / 60.0

# 自绘滑条布局
SLIDER_X = 790
SLIDER_W = 36
SLIDER_Y_TOP = 72
SLIDER_Y_BOTTOM = 462
T_MIN, T_MAX = -20.0, 140.0


def clamp(v, a, b):
    return a if v < a else (b if v > b else v)


def energy_at(t):
    ph = (t % PERIOD) / PERIOD
    if ph < 0.05:
        return 0.0
    if ph < 0.47:
        return E5 * (ph - 0.05) / 0.42
    if ph < 0.51:
        return E5
    if ph < 0.93:
        return E5 * (1.0 - (ph - 0.51) / 0.42)
    return 0.0


def state_from_energy(E):
    if E <= E1:
        return T_MIN + 20.0 * (E / E1), 0.0, 0.0
    if E <= E2:
        return 0.0, (E - E1) / (E2 - E1), 0.0
    if E <= E3:
        return 100.0 * (E - E2) / (E3 - E2), 1.0, 0.0
    if E <= E4:
        return 100.0, 1.0, (E - E3) / (E4 - E3)
    return 100.0 + 40.0 * (E - E4) / (E5 - E4), 1.0, 1.0


def temp_color(T):
    stops = [(-20, (120, 190, 255)), (0, (70, 170, 245)),
             (100, (255, 140, 0)), (140, (240, 60, 50))]
    if T <= stops[0][0]:
        return stops[0][1]
    for i in range(len(stops) - 1):
        t0, c0 = stops[i]
        t1, c1 = stops[i + 1]
        if T <= t1:
            f = (T - t0) / (t1 - t0)
            return tuple(int(c0[j] + (c1[j] - c0[j]) * f) for j in range(3))
    return stops[-1][1]


def hex_color(c):
    return "#%02x%02x%02x" % c


class WaterDemo:
    def __init__(self, root):
        self.root = root
        root.title("水的三态变化 · 温度滑条")
        root.configure(bg="#0a1020")
        self.canvas = tk.Canvas(root, width=CANVAS_W, height=CANVAS_H,
                                bg="#0a1020", highlightthickness=0)
        self.canvas.pack()

        # --- 粒子 ---
        self.px = [0.0] * N
        self.py = [0.0] * N
        self.vx = [0.0] * N
        self.vy = [0.0] * N
        self.lat_x = [0.0] * N
        self.lat_y = [0.0] * N
        self._build_lattice()

        # --- 热力学 ---
        self.sim_time = 0.0
        self.temp = T_MIN
        self.melt = 0.0
        self.vapor = 0.0
        self.prev_T = T_MIN
        self.heating = True
        self.manual_temp = T_MIN
        self.dragging = False

        self.acc = 0.0
        self.last_time = time.perf_counter()

        self._build_static()
        self._build_particles()
        self._bind_events()

        self.tick()

    # ---------- 工具 ----------
    def temp_to_y(self, T):
        frac = (T - T_MIN) / (T_MAX - T_MIN)
        frac = clamp(frac, 0.0, 1.0)
        return SLIDER_Y_BOTTOM - frac * (SLIDER_Y_BOTTOM - SLIDER_Y_TOP)

    def y_to_temp(self, y):
        frac = (SLIDER_Y_BOTTOM - y) / (SLIDER_Y_BOTTOM - SLIDER_Y_TOP)
        frac = clamp(frac, 0.0, 1.0)
        return T_MIN + frac * (T_MAX - T_MIN)

    # ---------- 初始化 ----------
    def _build_lattice(self):
        cols, rows = 10, 10
        x0, x1 = 0.62, BW - 0.62
        y0, y1 = 0.42, 5.4
        idx = 0
        for r in range(rows):
            y = y0 + (y1 - y0) * r / (rows - 1)
            for c in range(cols):
                x = x0 + (x1 - x0) * c / (cols - 1)
                self.lat_x[idx] = x
                self.lat_y[idx] = y
                self.px[idx] = x + (random.random() - 0.5) * 0.05
                self.py[idx] = y + (random.random() - 0.5) * 0.05
                idx += 1

    def _build_static(self):
        c = self.canvas
        c.create_text(CANVAS_W / 2, 26, text="水的三态变化",
                      fill="#dce8ff",
                      font=("Microsoft YaHei", 20, "bold"))

        ix, iy = OFF_X, OFF_Y
        iw, ih = BW * S, BH * S
        c.create_rectangle(ix, iy, ix + iw, iy + ih,
                           fill="#0e1830", outline="")

        # 加热/冷却提示条
        self.heat_bar = c.create_rectangle(
            ix + 40, iy + ih + 14, ix + iw - 40, iy + ih + 30,
            fill="#3a9bff", outline="")
        self.heat_txt = c.create_text(
            ix + iw / 2, iy + ih + 48, text="",
            fill="#3a9bff", font=("Microsoft YaHei", 13, "bold"))

        # ========== 自绘彩色温度滑条 ==========
        c.create_text(SLIDER_X + SLIDER_W / 2, SLIDER_Y_TOP - 26,
                      text="温度", fill="#8fb0dd",
                      font=("Microsoft YaHei", 12, "bold"))

        # 彩色渐变条（60 段，底部蓝 → 顶部红）
        SEG = 60
        for i in range(SEG):
            f0 = i / SEG
            f1 = (i + 1) / SEG
            t_mid = T_MIN + (f0 + f1) / 2 * (T_MAX - T_MIN)
            y_lo = SLIDER_Y_BOTTOM - f0 * (SLIDER_Y_BOTTOM - SLIDER_Y_TOP)
            y_hi = SLIDER_Y_BOTTOM - f1 * (SLIDER_Y_BOTTOM - SLIDER_Y_TOP)
            c.create_rectangle(SLIDER_X, y_hi, SLIDER_X + SLIDER_W, y_lo + 0.5,
                               fill=hex_color(temp_color(t_mid)), outline="")

        # 外框
        c.create_rectangle(SLIDER_X - 2, SLIDER_Y_TOP - 2,
                           SLIDER_X + SLIDER_W + 2, SLIDER_Y_BOTTOM + 2,
                           outline="#3a557a", width=2, fill="")

        # 刻度线 + 刻度值（右侧）
        for v in range(-20, 141, 20):
            y = self.temp_to_y(v)
            c.create_line(SLIDER_X + SLIDER_W + 2, y,
                          SLIDER_X + SLIDER_W + 10, y,
                          fill="#6b8bb5", width=1)
            c.create_text(SLIDER_X + SLIDER_W + 16, y, text=str(v),
                          anchor="w", fill="#9db8dd",
                          font=("Consolas", 9))

        # 温度数字
        self.thermo_text = c.create_text(
            SLIDER_X + SLIDER_W / 2, SLIDER_Y_BOTTOM + 34,
            text="-20.0 °C", fill="#e0eaff",
            font=("Consolas", 17, "bold"))

        # 手柄（初始在底部）
        y0 = self.temp_to_y(T_MIN)
        self.handle = c.create_oval(
            SLIDER_X - 7, y0 - 12, SLIDER_X + SLIDER_W + 7, y0 + 12,
            fill="#ffffff", outline="#5a8bd0", width=2, tags="slider")

        # 自动演示复选框（默认关闭）
        self.auto_var = tk.BooleanVar(value=False)
        self.auto_cb = tk.Checkbutton(
            self.canvas, text="自动演示",
            variable=self.auto_var, command=self._on_auto_toggle,
            bg="#0a1020", fg="#9db8dd", selectcolor="#1b2b4a",
            activebackground="#0a1020", activeforeground="#cfe0ff",
            highlightthickness=0, bd=0,
            font=("Microsoft YaHei", 11),
        )
        self.auto_cb.place(x=SLIDER_X - 6, y=SLIDER_Y_BOTTOM + 62)

        # 状态文字
        self.status_text = c.create_text(
            CANVAS_W / 2, 624, text="",
            fill="#cfe0ff", font=("Microsoft YaHei", 15, "bold"))

        # 图例
        lx = 120
        ly = 650
        for name, col in (("固态（冰）", "#78c8f5"),
                          ("液态（水）", "#2678e8"),
                          ("气态（水蒸气）", "#c8d8f0")):
            c.create_oval(lx - 6, ly - 6, lx + 6, ly + 6,
                          fill=col, outline="")
            c.create_text(lx + 14, ly, text=name, anchor="w",
                          fill="#9db8dd",
                          font=("Microsoft YaHei", 11))
            lx += 165

    def _build_particles(self):
        self.items = []
        for _ in range(N):
            it = self.canvas.create_oval(0, 0, 0, 0, outline="")
            self.items.append(it)
        c = self.canvas
        ix, iy = OFF_X, OFF_Y
        iw, ih = BW * S, BH * S
        c.create_line(ix, iy, ix, iy + ih, ix + iw, iy + ih, ix + iw, iy,
                      fill="#4a6fa5", width=5,
                      capstyle="round", joinstyle="round")
        c.create_line(ix - 10, iy, ix + 10, iy, fill="#6b93c9", width=3)
        c.create_line(ix + iw - 10, iy, ix + iw + 10, iy,
                      fill="#6b93c9", width=3)

    def _bind_events(self):
        self.canvas.bind("<Button-1>", self._on_press)
        self.canvas.bind("<B1-Motion>", self._on_drag)
        self.canvas.bind("<ButtonRelease-1>", self._on_release)

    # ---------- 滑条交互 ----------
    def _in_slider_zone(self, x, y):
        return (SLIDER_X - 18 <= x <= SLIDER_X + SLIDER_W + 18 and
                SLIDER_Y_TOP - 18 <= y <= SLIDER_Y_BOTTOM + 18)

    def _on_press(self, event):
        if self._in_slider_zone(event.x, event.y):
            if self.auto_var.get():
                self.auto_var.set(False)
                self._on_auto_toggle()
            self.dragging = True
            self._set_temp_from_y(event.y)

    def _on_drag(self, event):
        if self.dragging:
            self._set_temp_from_y(event.y)

    def _on_release(self, event):
        self.dragging = False

    def _set_temp_from_y(self, y):
        T = self.y_to_temp(y)
        self.manual_temp = round(T * 2) / 2.0

    def _on_auto_toggle(self):
        if not self.auto_var.get():
            self.manual_temp = self.temp

    # ---------- 目标状态 ----------
    def update_targets(self, dt):
        if self.auto_var.get():
            E = energy_at(self.sim_time)
            T, _, _ = state_from_energy(E)
            self.manual_temp = round(T * 2) / 2.0

        self.temp = self.manual_temp

        if self.temp > 0.01:
            tm = 1.0
        elif self.temp < -0.01:
            tm = 0.0
        else:
            tm = self.melt
        if self.temp > 100.01:
            tv = 1.0
        elif self.temp < 99.99:
            tv = 0.0
        else:
            tv = self.vapor

        rate = 2.2
        self.melt += clamp(tm - self.melt, -rate * dt, rate * dt)
        self.vapor += clamp(tv - self.vapor, -rate * dt, rate * dt)
        self.melt = clamp(self.melt, 0.0, 1.0)
        self.vapor = clamp(self.vapor, 0.0, 1.0)

        if self.temp > self.prev_T + 0.001:
            self.heating = True
        elif self.temp < self.prev_T - 0.001:
            self.heating = False
        self.prev_T = self.temp

    # ---------- 物理 ----------
    def _physics_step(self):
        melt = self.melt
        vapor = self.vapor
        solid = 1.0 - melt
        liquid = melt * (1.0 - vapor)
        gas = vapor

        damp = 0.86 * solid + 0.94 * liquid + 0.99 * gas
        sigma = 0.006 * solid + 0.030 * liquid + 0.100 * gas
        grav = 0.012 * (1.0 - gas)
        k_lat = 0.10 * solid
        stiff = 0.75 * (1.0 - 0.9 * gas)

        px, py, vx, vy = self.px, self.py, self.vx, self.vy
        latx, laty = self.lat_x, self.lat_y
        dt = FIXED_DT

        for i in range(N):
            ax = k_lat * (latx[i] - px[i])
            ay = k_lat * (laty[i] - py[i]) - grav
            vx[i] = (vx[i] + ax) * damp + (random.random() * 2.0 - 1.0) * sigma * 1.7
            vy[i] = (vy[i] + ay) * damp + (random.random() * 2.0 - 1.0) * sigma * 1.7

        predx = [px[i] + vx[i] * dt for i in range(N)]
        predy = [py[i] + vy[i] * dt for i in range(N)]

        rr0 = R0 * R0
        for _ in range(2):
            for i in range(N):
                xi = predx[i]
                yi = predy[i]
                for j in range(i + 1, N):
                    dx = xi - predx[j]
                    dy = yi - predy[j]
                    d2 = dx * dx + dy * dy
                    if 1e-12 < d2 < rr0:
                        d = math.sqrt(d2)
                        w = 0.5 * (R0 - d) * stiff / d
                        ox = w * dx
                        oy = w * dy
                        predx[i] += ox
                        predy[i] += oy
                        predx[j] -= ox
                        predy[j] -= oy
                        xi += ox
                        yi += oy

        lo, hi_x, hi_y = R_PART, BW - R_PART, BH - R_PART
        for i in range(N):
            if predx[i] < lo:
                predx[i] = lo
                vx[i] = abs(vx[i]) * 0.4
            elif predx[i] > hi_x:
                predx[i] = hi_x
                vx[i] = -abs(vx[i]) * 0.4
            if predy[i] < lo:
                predy[i] = lo
                vy[i] = abs(vy[i]) * 0.4
            elif predy[i] > hi_y:
                predy[i] = hi_y
                vy[i] = -abs(vy[i]) * 0.4

        vmax = 0.3 * solid + 0.9 * liquid + 1.8 * gas
        inv_dt = 1.0 / dt
        for i in range(N):
            nvx = (predx[i] - px[i]) * inv_dt
            nvy = (predy[i] - py[i]) * inv_dt
            sp = math.hypot(nvx, nvy)
            if sp > vmax and sp > 1e-9:
                f = vmax / sp
                nvx *= f
                nvy *= f
            vx[i] = nvx
            vy[i] = nvy
            px[i] = predx[i]
            py[i] = predy[i]

    # ---------- 主循环 ----------
    def tick(self):
        now = time.perf_counter()
        real_dt = now - self.last_time
        self.last_time = now
        if real_dt > 0.1:
            real_dt = 0.1
        self.acc += real_dt

        steps = 0
        while self.acc >= FIXED_DT and steps < 4:
            self.sim_time += FIXED_DT
            self.update_targets(FIXED_DT)
            self._physics_step()
            self.acc -= FIXED_DT
            steps += 1

        self.render()
        self.root.after(16, self.tick)

    # ---------- 渲染 ----------
    def render(self):
        melt = self.melt
        vapor = self.vapor
        T = self.temp

        cr = 120 * (1 - melt) + 38 * melt
        cg = 200 * (1 - melt) + 122 * melt
        cb = 245 * (1 - melt) + 232 * melt
        cr = cr * (1 - vapor) + 200 * vapor
        cg = cg * (1 - vapor) + 220 * vapor
        cb = cb * (1 - vapor) + 240 * vapor
        col = "#%02x%02x%02x" % (int(cr), int(cg), int(cb))
        rad = R_PART * S * (1.0 - 0.08 * vapor)
        for i in range(N):
            cx = OFF_X + self.px[i] * S
            cy = OFF_Y + (BH - self.py[i]) * S
            self.canvas.coords(self.items[i],
                               cx - rad, cy - rad, cx + rad, cy + rad)
            self.canvas.itemconfig(self.items[i], fill=col)

        # 手柄跟随温度
        hy = self.temp_to_y(T)
        self.canvas.coords(self.handle,
                           SLIDER_X - 7, hy - 12,
                           SLIDER_X + SLIDER_W + 7, hy + 12)
        self.canvas.tag_raise("slider")

        self.canvas.itemconfig(self.thermo_text, text="%.1f °C" % T)

        hc = "#ff6a33" if self.heating else "#3a9bff"
        self.canvas.itemconfig(self.heat_bar, fill=hc)
        self.canvas.itemconfig(self.heat_txt,
                               text="🔥 加热中（吸热）" if self.heating
                               else "❄ 冷却中（放热）",
                               fill=hc)

        self.canvas.itemconfig(self.status_text, text=self.describe())

    def describe(self):
        melt, vapor = self.melt, self.vapor
        h = self.heating
        if vapor > 0.99:
            return "气态 · 水蒸气    " + ("（吸热升温）" if h else "（放热降温）")
        if vapor > 0.005:
            return "汽化（蒸发 / 沸腾）· 吸热" if h else "液化（凝结）· 放热"
        if melt > 0.99:
            return "液态 · 水    %.1f°C" % self.temp
        if melt > 0.005:
            return "熔化（冰 → 水）· 吸热" if h else "凝固（水 → 冰）· 放热"
        return "固态 · 冰    %.1f°C" % self.temp


def main():
    root = tk.Tk()
    root.resizable(False, False)
    WaterDemo(root)
    root.mainloop()


if __name__ == "__main__":
    main()
    