# -*- coding: utf-8 -*-
"""
✨ 透镜成像规律 · 清爽严谨版 (无乱线，严格裁剪) ✨
操作：←/→ 移动物体，空格键切换凹凸透镜
"""
import turtle
import math

# ==========================================
# 1. 屏幕初始化
# ==========================================
screen = turtle.Screen()
screen.setup(width=1300, height=800)
screen.title("透镜成像规律 (清爽交互版)")
screen.bgcolor("#0B0E14")
screen.tracer(0)

t_static = turtle.Turtle(); t_static.hideturtle(); t_static.speed(0); t_static.penup()
t_lens = turtle.Turtle(); t_lens.hideturtle(); t_lens.speed(0); t_lens.penup()
t_anim = turtle.Turtle(); t_anim.hideturtle(); t_anim.speed(0); t_anim.penup()

# ==========================================
# 2. 全局状态与视区边界
# ==========================================
lens_type = 'convex'
f_abs = 150
h = 100
u = 320

# 严格视区边界 (防止线条超出屏幕导致视线干扰)
BOUND_X_MAX = 550
BOUND_X_MIN = -550
BOUND_Y_MAX = 300
BOUND_Y_MIN = -300

# ==========================================
# 3. 绘图辅助函数
# ==========================================
def draw_dashed_line(t, x1, y1, x2, y2, color, width=2):
    """绘制规整的虚线"""
    t.penup(); t.goto(x1, y1)
    t.color(color); t.pensize(width)
    dist = math.hypot(x2 - x1, y2 - y1)
    if dist == 0: return
    steps = int(dist / 15)
    dx = (x2 - x1) / steps
    dy = (y2 - y1) / steps
    t.setheading(math.degrees(math.atan2(dy, dx)))
    for _ in range(steps):
        t.pendown(); t.forward(9)
        t.penup(); t.forward(6)

def get_line_intersection(x1, y1, x2, y2):
    """计算线段与视区边界的交点 (严格裁剪)"""
    dx = x2 - x1
    dy = y2 - y1
    t_min, t_max = 0.0, 1.0
    
    # x 边界
    if dx != 0:
        t1 = (BOUND_X_MIN - x1) / dx
        t2 = (BOUND_X_MAX - x1) / dx
        t_min = max(t_min, min(t1, t2))
        t_max = min(t_max, max(t1, t2))
    elif x1 < BOUND_X_MIN or x1 > BOUND_X_MAX:
        return None

    # y 边界
    if dy != 0:
        t1 = (BOUND_Y_MIN - y1) / dy
        t2 = (BOUND_Y_MAX - y1) / dy
        t_min = max(t_min, min(t1, t2))
        t_max = min(t_max, max(t1, t2))
    elif y1 < BOUND_Y_MIN or y1 > BOUND_Y_MAX:
        return None

    if t_min > t_max:
        return None # 完全在边界外
    
    # 返回入点和出点
    return (x1 + t_min * dx, y1 + t_min * dy), (x1 + t_max * dx, y1 + t_max * dy)

def draw_clipped_ray(t, x1, y1, x2, y2, color, is_dashed=False):
    """绘制受边界限制的直线段"""
    pts = get_line_intersection(x1, y1, x2, y2)
    if not pts: return
    p_start, p_end = pts
    
    if is_dashed:
        draw_dashed_line(t, p_start[0], p_start[1], p_end[0], p_end[1], color, 1.5)
    else:
        t.penup(); t.goto(p_start[0], p_start[1])
        t.color(color); t.pensize(2); t.pendown()
        t.goto(p_end[0], p_end[1]); t.penup()

def draw_rounded_rect(t, x, y, w, h, r, border_color, fill_color, text=""):
    t.penup(); t.goto(x + r, y); t.pendown()
    t.color(border_color, fill_color); t.pensize(2)
    t.begin_fill()
    t.goto(x + w - r, y); t.circle(-r, 90)
    t.goto(x + w, y + h - r); t.circle(-r, 90)
    t.goto(x + r, y + h); t.circle(-r, 90)
    t.goto(x, y + r); t.circle(-r, 90)
    t.goto(x + r, y)
    t.end_fill(); t.penup()
    if text:
        t.goto(x + w/2, y + h/2 - 10); t.color("#FFFFFF")
        t.write(text, align="center", font=("Microsoft YaHei", 14, "bold"))

# ==========================================
# 4. 静态背景与 UI
# ==========================================
def draw_static_base():
    t_static.clear()
    # 网格
    t_static.color("#10151F"); t_static.pensize(1)
    for x in range(-600, 601, 50):
        t_static.goto(x, -400); t_static.pendown(); t_static.goto(x, 400); t_static.penup()
    for y in range(-400, 401, 50):
        t_static.goto(-650, y); t_static.pendown(); t_static.goto(650, y); t_static.penup()

    # 主光轴
    t_static.color("#30363D"); t_static.pensize(2)
    t_static.goto(-600, 0); t_static.pendown(); t_static.goto(600, 0); t_static.penup()

    # 焦点标记
    t_static.color("#8B949E")
    for x, label in [(-2*f_abs, "2F"), (-f_abs, "F"), (f_abs, "F'"), (2*f_abs, "2F'")]:
        t_static.goto(x, -10); t_static.pendown(); t_static.goto(x, 10); t_static.penup()
        t_static.goto(x, 15); t_static.write(label, align="center", font=("Arial", 12, "bold"))

    # 标题
    t_static.goto(0, 350); t_static.color("#58A6FF")
    t_static.write("透镜成像规律演示", align="center", font=("Microsoft YaHei", 24, "bold"))

    # 底部控制按钮
    draw_rounded_rect(t_static, -400, -360, 160, 50, 8, "#1F6FEB", "#0D1420", "< 靠近")
    draw_rounded_rect(t_static, -100, -360, 200, 50, 8, "#D29922", "#0D1420", "切换透镜 [空格]")
    draw_rounded_rect(t_static, 240, -360, 160, 50, 8, "#1F6FEB", "#0D1420", "远离 >")

# ==========================================
# 5. 绘制透镜
# ==========================================
def draw_lens():
    t_lens.clear()
    t_lens.color("#58A6FF", "#1F6FEB"); t_lens.pensize(2)
    t_lens.penup()
    if lens_type == 'convex':
        t_lens.goto(0, 180); t_lens.pendown(); t_lens.begin_fill()
        for y in range(180, -181, -10):
            x = 20 * (1 - (y/180)**2)
            t_lens.goto(x, y)
        for y in range(-180, 181, 10):
            x = -20 * (1 - (y/180)**2)
            t_lens.goto(x, y)
        t_lens.end_fill()
        t_lens.goto(0, 200); t_lens.color("#58A6FF"); t_lens.write("凸透镜", align="center", font=("Microsoft YaHei", 16, "bold"))
    else:
        t_lens.goto(-20, 180); t_lens.pendown(); t_lens.begin_fill()
        for y in range(180, -181, -10):
            x = 20 * ((y/180)**2)
            t_lens.goto(x, y)
        for y in range(-180, 181, 10):
            x = -20 * ((y/180)**2)
            t_lens.goto(x, y)
        t_lens.end_fill()
        t_lens.goto(0, 200); t_lens.color("#58A6FF"); t_lens.write("凹透镜", align="center", font=("Microsoft YaHei", 16, "bold"))

# ==========================================
# 6. 核心物理光线追踪
# ==========================================
def draw_dynamic():
    global u
    t_anim.clear()
    
    # 计算透镜参数
    f = f_abs if lens_type == 'convex' else -f_abs
    # 若接近焦点，为了视觉稳定，强制跳过死区
    if abs(u - f_abs) < 20 and lens_type == 'convex':
        u = f_abs - 25 if u < f_abs else f_abs + 25
        
    v = (u * f) / (u - f)
    m = v / u
    h_img = h * m
    
    # 光线颜色
    C_IN = "#F9E2AF"   # 入射光线
    C_OUT = "#F9E2AF"  # 出射光线
    C_VIRTUAL = "#79C0FF" # 反向延长线

    # 1. 画物体 (红色)
    t_anim.penup(); t_anim.goto(-u, 0)
    t_anim.color("#FF7B72"); t_anim.pensize(3); t_anim.pendown()
    t_anim.goto(-u, h); t_anim.penup()
    t_anim.goto(-u, h); t_anim.begin_fill()
    t_anim.goto(-u - 6, h - 12); t_anim.goto(-u + 6, h - 12)
    t_anim.goto(-u, h); t_anim.end_fill(); t_anim.penup()

    # 2. 画像 (实像黄，虚像绿虚线)
    if v > 0 and u > f_abs:
        t_anim.penup(); t_anim.goto(v, 0)
        t_anim.color(C_OUT); t_anim.pensize(3); t_anim.pendown()
        t_anim.goto(v, h_img); t_anim.penup()
        t_anim.goto(v, h_img); t_anim.begin_fill()
        t_anim.goto(v - 6, h_img + 12); t_anim.goto(v + 6, h_img + 12)
        t_anim.goto(v, h_img); t_anim.end_fill(); t_anim.penup()
        t_anim.goto(v, h_img - 20); t_anim.write("实像", align="center", font=("Microsoft YaHei", 12, "bold"))
    elif v < 0:
        draw_dashed_line(t_anim, v, 0, v, h_img, "#3FB950", 3)
        t_anim.penup(); t_anim.goto(v, h_img); t_anim.begin_fill()
        t_anim.goto(v - 5, h_img - 10); t_anim.goto(v + 5, h_img - 10)
        t_anim.goto(v, h_img); t_anim.end_fill(); t_anim.penup()
        t_anim.goto(v, h_img + 15); t_anim.write("虚像", align="center", font=("Microsoft YaHei", 12, "bold"))

    # 3. 特征光线追踪
    # 光线1：平行主轴入射，折射后过焦点
    # 入射段
    draw_clipped_ray(t_anim, -u, h, 0, h, C_IN)
    # 出射段 (直线方程：过(0,h)和(f,0))
    # 若 v > 0 且为实像，出射光线在 x=v 处汇聚，之后继续发散
    draw_clipped_ray(t_anim, 0, h, f, 0, C_OUT) 
    # 反向延长 (虚像时向左)
    if v < 0:
        draw_clipped_ray(t_anim, 0, h, -f, 2*h, C_VIRTUAL, is_dashed=True)

    # 光线2：过光心，方向不改变
    # 入射段
    draw_clipped_ray(t_anim, -u, h, 0, 0, C_IN)
    # 出射段 (直线方程：过(0,0)和(-u,h))
    draw_clipped_ray(t_anim, 0, 0, u, -h, C_OUT)
    # 反向延长 (虚像时向左)
    if v < 0:
        draw_clipped_ray(t_anim, 0, 0, -u, h, C_VIRTUAL, is_dashed=True)

    # 4. 左侧半透明数据面板 (覆盖在光线之上，防止线条干扰文字)
    panel_w, panel_h = 220, 150
    panel_x, panel_y = -600, 100
    draw_rounded_rect(t_anim, panel_x, panel_y, panel_w, panel_h, 10, "#1F6FEB", "#0A1222")
    
    t_anim.goto(panel_x + 15, panel_y + panel_h - 30)
    t_anim.color("#C9D1D9")
    t_anim.write(f"物距 u = {u:.0f}", font=("Courier New", 14, "bold"))
    t_anim.goto(panel_x + 15, panel_y + panel_h - 55)
    t_anim.write(f"像距 v = {v:.0f}" if abs(v) < 1000 else "像距 v = ∞", font=("Courier New", 14, "bold"))
    
    # 性质结论
    if v > 0:
        prop = "倒立" + ("放大" if abs(m) > 1 else "缩小" if abs(m) < 1 else "等大") + "实像"
    else:
        prop = "正立" + ("放大" if abs(m) > 1 else "缩小" if abs(m) < 1 else "等大") + "虚像"
    
    t_anim.goto(panel_x + 15, panel_y + panel_h - 85)
    t_anim.color("#F9E2AF")
    t_anim.write(prop, font=("Microsoft YaHei", 13, "bold"))

    screen.update()

# ==========================================
# 7. 交互与事件
# ==========================================
def update():
    draw_lens()
    draw_dynamic()

def move_left():
    global u
    u = max(30, u - 15)
    update()

def move_right():
    global u
    u = min(500, u + 15)
    update()

def toggle_lens():
    global lens_type, u
    lens_type = 'concave' if lens_type == 'convex' else 'convex'
    u = 320
    update()

def on_click(x, y):
    if -400 <= x <= -240 and -360 <= y <= -310: move_left()
    elif 240 <= x <= 400 and -360 <= y <= -310: move_right()
    elif -100 <= x <= 100 and -360 <= y <= -310: toggle_lens()

screen.listen()
screen.onkey(move_left, "Left")
screen.onkey(move_right, "Right")
screen.onkey(toggle_lens, "space")
screen.onscreenclick(on_click)

draw_static_base()
update()
turtle.done()