# -*- coding: utf-8 -*-
"""
凸透镜成像规律演示（键盘微调版）
- ← / →  微调物距 ±5
- ↑ / ↓  粗调物距 ±20
- 1/2/3/4 切换典型情况
- R 显示/隐藏光线
- 拖动蜡烛顶部橙色圆点也可改变物距
"""
import turtle
import math

# ==================== 参数 ====================
F = 90.0
LENS_X = 60.0
AXIS_Y = -70.0
OBJ_H = 62.0
LENS_HALF_H = 180.0

U_MIN, U_MAX = 40.0, 330.0
U_GAP = 45.0          # 焦点附近跳过，避免像距过大
STEP_FINE = 5         # 左右键微调步长
STEP_COARSE = 20      # 上下键粗调步长
FONT = "Microsoft YaHei"

# 颜色
C_AXIS       = "#cfd8dc"
C_LENS       = "#1976d2"
C_LENS_FILL  = "#e3f2fd"
C_CANDLE     = "#ffb74d"
C_FLAME      = "#ff7043"
C_RAY        = "#ff7043"
C_RAY_VIRT   = "#90a4ae"
C_IMG_REAL   = "#43a047"
C_IMG_VIRT   = "#81c784"
C_TEXT       = "#37474f"
C_TITLE      = "#0d47a1"

u = 200.0
show_rays = True

# ==================== 屏幕 ====================
screen = turtle.Screen()
screen.title("凸透镜成像规律演示")
screen.setup(1060, 760)
screen.setworldcoordinates(-500, -380, 500, 380)
screen.bgcolor("#f7fbff")
screen.tracer(0)
screen.delay(0)


def new_pen():
    t = turtle.Turtle()
    t.hideturtle()
    t.speed(0)
    t.penup()
    return t


axis_pen    = new_pen()
lens_pen    = new_pen()
ray_pen     = new_pen()
obj_pen     = new_pen()
img_pen     = new_pen()
text_pen    = new_pen()
measure_pen = new_pen()

handle = turtle.Turtle()
handle.shape("circle")
handle.shapesize(1.5, 1.5)
handle.color("#ff5722", "#ffab91")
handle.penup()
handle.speed(0)
handle.hideturtle()


# ==================== 绘图工具 ====================
def seg(t, x1, y1, x2, y2, color, width=2, dash=None):
    t.penup()
    t.pencolor(color)
    t.pensize(width)
    if dash is None:
        t.goto(x1, y1)
        t.pendown()
        t.goto(x2, y2)
        t.penup()
        return
    dx, dy = x2 - x1, y2 - y1
    L = math.hypot(dx, dy)
    if L < 0.5:
        return
    n = max(1, int(L // dash))
    for i in range(n + 1):
        s = i * dash
        e = min(s + dash * 0.55, L)
        if s >= L:
            break
        t.goto(x1 + dx * s / L, y1 + dy * s / L)
        t.pendown()
        t.goto(x1 + dx * e / L, y1 + dy * e / L)
        t.penup()


def draw_candle(t, x, h, flip, body, flame, outline=None, dashed=False):
    y0 = AXIS_Y
    s  = -1 if flip else 1
    w  = max(h * 0.30, 6)
    bh = h * 0.72
    fh = h * 0.28

    t.penup()
    if dashed:
        col = outline or body
        rect = [(x - w/2, y0), (x + w/2, y0),
                (x + w/2, y0 + s*bh), (x - w/2, y0 + s*bh), (x - w/2, y0)]
        for i in range(len(rect) - 1):
            seg(t, *rect[i], *rect[i+1], col, 1.5, dash=6)
        fl = [(x - w*0.3, y0 + s*bh), (x, y0 + s*(bh+fh)),
              (x + w*0.3, y0 + s*bh), (x - w*0.3, y0 + s*bh)]
        for i in range(len(fl) - 1):
            seg(t, *fl[i], *fl[i+1], col, 1.5, dash=6)
        return

    t.pensize(2)
    t.pencolor(body)
    t.fillcolor(body)
    t.goto(x - w/2, y0)
    t.pendown()
    t.begin_fill()
    t.goto(x + w/2, y0)
    t.goto(x + w/2, y0 + s*bh)
    t.goto(x - w/2, y0 + s*bh)
    t.goto(x - w/2, y0)
    t.end_fill()
    t.penup()

    t.pencolor(flame)
    t.fillcolor(flame)
    t.goto(x - w*0.3, y0 + s*bh)
    t.pendown()
    t.begin_fill()
    t.goto(x, y0 + s*(bh + fh))
    t.goto(x + w*0.3, y0 + s*bh)
    t.goto(x - w*0.3, y0 + s*bh)
    t.end_fill()
    t.penup()


def draw_measure(t, x0, x1, y, label, color):
    a, b = min(x0, x1), max(x0, x1)
    t.penup()
    t.pencolor(color)
    t.pensize(1)
    t.goto(a, y); t.pendown(); t.goto(b, y); t.penup()
    for xx in (a, b):
        t.goto(xx, y - 7); t.pendown(); t.goto(xx, y + 7); t.penup()
    t.goto((a + b) / 2, y - 20)
    t.color(color)
    t.write(label, align="center", font=(FONT, 11, "normal"))


# ==================== 静态元素 ====================
def draw_static():
    axis_pen.clear()
    seg(axis_pen, -480, AXIS_Y, 480, AXIS_Y, C_AXIS, 2)
    axis_pen.goto(455, AXIS_Y - 26)
    axis_pen.color("#90a4ae")
    axis_pen.write("主光轴", align="center", font=(FONT, 10, "normal"))

    for fx, name in ((LENS_X - F, "F"), (LENS_X + F, "F'"),
                     (LENS_X - 2*F, "2F"), (LENS_X + 2*F, "2F'")):
        axis_pen.penup()
        axis_pen.goto(fx, AXIS_Y)
        axis_pen.dot(9, "#ef5350")
        axis_pen.goto(fx, AXIS_Y - 34)
        axis_pen.color("#e53935")
        axis_pen.write(name, align="center", font=(FONT, 11, "bold"))

    lens_pen.clear()
    b, a, n = LENS_HALF_H, 18.0, 44
    pts = []
    for i in range(n + 1):
        yy = -b + 2 * b * i / n
        pts.append((LENS_X + a * (1 - (yy / b) ** 2), AXIS_Y + yy))
    for i in range(n, -1, -1):
        yy = -b + 2 * b * i / n
        pts.append((LENS_X - a * (1 - (yy / b) ** 2), AXIS_Y + yy))

    lens_pen.penup()
    lens_pen.pencolor(C_LENS)
    lens_pen.pensize(3)
    lens_pen.fillcolor(C_LENS_FILL)
    lens_pen.goto(pts[0])
    lens_pen.pendown()
    lens_pen.begin_fill()
    for p in pts[1:]:
        lens_pen.goto(p)
    lens_pen.goto(pts[0])
    lens_pen.end_fill()
    lens_pen.penup()

    lens_pen.goto(LENS_X, AXIS_Y)
    lens_pen.dot(8, C_LENS)
    lens_pen.goto(LENS_X, AXIS_Y + b + 22)
    lens_pen.color(C_LENS)
    lens_pen.write("凸透镜", align="center", font=(FONT, 12, "bold"))


# ==================== 物距限制 ====================
def clamp_u(val):
    val = max(U_MIN, min(U_MAX, val))
    if abs(val - F) < U_GAP:
        val = (F - U_GAP) if val < F else (F + U_GAP)
    if abs(val - 2 * F) < 8:
        val = 2 * F
    return val


# ==================== 三条特殊光线 ====================
def draw_rays(u_val, v, img_x):
    ray_pen.clear()
    if not show_rays:
        return

    obj_x = LENS_X - u_val
    yp = AXIS_Y + OBJ_H
    P = (obj_x, yp)
    A = (LENS_X, yp)
    O = (LENS_X, AXIS_Y)
    yB = AXIS_Y - OBJ_H * F / (u_val - F)
    B = (LENS_X, yB)

    stop_x = img_x if v > 0 else LENS_X + 120

    seg(ray_pen, *P, *A, C_RAY, 2.2)
    seg(ray_pen, *P, *O, C_RAY, 2.2)
    seg(ray_pen, *P, *B, C_RAY, 2.2)

    s1 = (stop_x - LENS_X) / F
    seg(ray_pen, *A, stop_x, yp - s1 * OBJ_H, C_RAY, 2.2)

    s2 = (stop_x - LENS_X) / u_val
    seg(ray_pen, *O, stop_x, AXIS_Y - s2 * OBJ_H, C_RAY, 2.2)

    seg(ray_pen, *B, stop_x, yB, C_RAY, 2.2)

    for pt in (A, O, B):
        ray_pen.goto(pt)
        ray_pen.dot(5, C_RAY)

    if v < 0:
        back_x = img_x - 18
        s1b = (LENS_X - back_x) / F
        seg(ray_pen, *A, back_x, yp + s1b * OBJ_H, C_RAY_VIRT, 1.5, dash=9)

        s2b = (LENS_X - back_x) / u_val
        seg(ray_pen, *O, back_x, AXIS_Y + s2b * OBJ_H, C_RAY_VIRT, 1.5, dash=9)

        seg(ray_pen, *B, back_x, yB, C_RAY_VIRT, 1.5, dash=9)


# ==================== 光屏 ====================
def draw_screen(t, x, active, label):
    color = "#90a4ae" if active else "#cfd8dc"
    t.penup()
    t.pencolor(color)
    t.pensize(6)
    t.goto(x, AXIS_Y - 220)
    t.pendown()
    t.goto(x, AXIS_Y + 60)
    t.penup()
    t.pensize(3)
    t.goto(x - 12, AXIS_Y - 220)
    t.pendown()
    t.goto(x + 12, AXIS_Y - 220)
    t.penup()
    t.goto(x, AXIS_Y + 78)
    t.color(color)
    t.write(label, align="center", font=(FONT, 10, "bold"))


# ==================== 文字说明 ====================
def draw_texts(v, m, real):
    text_pen.clear()

    text_pen.goto(0, 352)
    text_pen.color(C_TITLE)
    text_pen.write("凸透镜成像规律演示", align="center", font=(FONT, 20, "bold"))

    text_pen.goto(0, 322)
    text_pen.color("#607d8b")
    text_pen.write("← → 微调(±5)    ↑ ↓ 粗调(±20)    1/2/3/4 典型情况    R 光线开关    也可拖动橙色圆点",
                   align="center", font=(FONT, 11, "normal"))

    if real:
        vtxt = "像距 v = %.0f  ( %.2f f )" % (v, v / F)
    else:
        vtxt = "像距 v = -%.0f  ( %.2f f ，虚像 )" % (abs(v), abs(v) / F)

    text_pen.goto(-460, 290)
    text_pen.color(C_TEXT)
    text_pen.write("物距 u = %.0f  ( %.2f f )      %s      放大率 = %.2f 倍"
                   % (u, u / F, vtxt, m),
                   align="left", font=(FONT, 12, "normal"))

    if u > 2 * F + 0.5:
        t1, t2, c1 = ("①  u > 2f ：成【倒立、缩小】的【实像】",
                      "像在透镜另一侧的 f 与 2f 之间，光屏上能接收到清晰倒立的像",
                      "#c62828")
    elif u >= 2 * F - 0.5:
        t1, t2, c1 = ("特殊情况  u = 2f ：成【倒立、等大】的【实像】",
                      "像距 v = 2f，像与物一样大，光屏上能接收到清晰的像",
                      "#6a1b9a")
    elif u > F:
        t1, t2, c1 = ("②  f < u < 2f ：成【倒立、放大】的【实像】",
                      "像在透镜另一侧的 2f 以外，光屏上能接收到清晰倒立放大的像",
                      "#1565c0")
    else:
        t1, t2, c1 = ("③  u < f ：成【正立、放大】的【虚像】",
                      "像与物在透镜同侧，是折射光线反向延长线的交点，光屏接收不到",
                      "#2e7d32")

    text_pen.goto(-460, 258)
    text_pen.color(c1)
    text_pen.write(t1, align="left", font=(FONT, 14, "bold"))

    text_pen.goto(-460, 232)
    text_pen.color("#455a64")
    text_pen.write(t2, align="left", font=(FONT, 11, "normal"))

    # 焦点附近提示
    if abs(u - (F - U_GAP)) < 0.5 or abs(u - (F + U_GAP)) < 0.5:
        text_pen.goto(-460, 206)
        text_pen.color("#8d6e63")
        text_pen.write("提示：此处已靠近 u ≈ f，像距趋于无穷大，程序自动跳过该区间",
                       align="left", font=(FONT, 10, "italic"))

    # 右下角：实像 / 虚像对照
    bx = 160
    text_pen.goto(bx, 258)
    text_pen.color("#1565c0")
    text_pen.write("实像", align="left", font=(FONT, 11, "bold"))
    text_pen.goto(bx + 40, 258)
    text_pen.color("#455a64")
    text_pen.write("光线真实会聚 · 倒立 · 光屏能接收", align="left", font=(FONT, 10, "normal"))

    text_pen.goto(bx, 232)
    text_pen.color("#2e7d32")
    text_pen.write("虚像", align="left", font=(FONT, 11, "bold"))
    text_pen.goto(bx + 40, 232)
    text_pen.color("#455a64")
    text_pen.write("反向延长线相交 · 正立 · 光屏接不到", align="left", font=(FONT, 10, "normal"))


# ==================== 核心刷新 ====================
def update():
    v = u * F / (u - F)
    m = abs(v) / u
    real = v > 0

    obj_x = LENS_X - u
    img_x = LENS_X + v
    img_h = OBJ_H * m

    draw_rays(u, v, img_x)

    img_pen.clear()
    if real:
        draw_screen(img_pen, img_x, True, "光屏")
    else:
        draw_screen(img_pen, LENS_X + 120, False, "光屏（接不到像）")

    obj_pen.clear()
    draw_candle(obj_pen, obj_x, OBJ_H, False, C_CANDLE, C_FLAME)
    obj_pen.goto(obj_x, AXIS_Y - 14)
    obj_pen.color("#ef6c00")
    obj_pen.write("物", align="center", font=(FONT, 10, "bold"))

    if real:
        draw_candle(img_pen, img_x, img_h, True, C_IMG_REAL, "#66bb6a")
        img_pen.goto(img_x, AXIS_Y + 10)
        img_pen.color(C_IMG_REAL)
        img_pen.write("实像", align="center", font=(FONT, 10, "bold"))
        img_pen.goto(img_x, AXIS_Y - img_h)
        img_pen.dot(8, C_IMG_REAL)
    else:
        draw_candle(img_pen, img_x, img_h, False, "#c8e6c9", "#a5d6a7",
                    outline=C_IMG_VIRT, dashed=True)
        img_pen.goto(img_x, AXIS_Y - 14)
        img_pen.color(C_IMG_VIRT)
        img_pen.write("虚像", align="center", font=(FONT, 10, "bold"))
        img_pen.goto(img_x, AXIS_Y + img_h)
        img_pen.dot(10, "white")
        img_pen.dot(6, C_IMG_VIRT)

    measure_pen.clear()
    draw_measure(measure_pen, obj_x, LENS_X, -262, "物距 u = %.0f" % u, "#ef6c00")
    draw_measure(measure_pen, LENS_X, img_x, -302,
                 "像距 v = %.0f" % abs(v), "#2e7d32" if real else "#7cb342")

    draw_texts(v, m, real)

    handle.goto(obj_x, AXIS_Y + OBJ_H + 24)

    screen.update()


# ==================== 交互 ====================
def on_drag(x, y):
    global u
    nu = clamp_u(LENS_X - x)
    if abs(nu - u) > 0.5:
        u = nu
        update()


handle.ondrag(on_drag)


def set_u(val):
    global u
    u = clamp_u(val)
    update()


def nudge(delta):
    """按步长调整物距；若跨越 u≈f 的无像区，则直接跳到另一侧"""
    global u
    new_u = u + delta
    if abs(new_u - F) < U_GAP and abs(u - F) >= U_GAP:
        new_u = (F + U_GAP) if u < F else (F - U_GAP)
    set_u(new_u)


def toggle_rays():
    global show_rays
    show_rays = not show_rays
    update()


# 典型情况
screen.onkey(lambda: set_u(270), "1")   # u > 2f
screen.onkey(lambda: set_u(150), "2")   # f < u < 2f
screen.onkey(lambda: set_u(40),  "3")   # u < f
screen.onkey(lambda: set_u(180), "4")   # u = 2f

# 方向键微调 / 粗调
screen.onkey(lambda: nudge(+STEP_FINE),   "Left")
screen.onkey(lambda: nudge(-STEP_FINE),   "Right")
screen.onkey(lambda: nudge(+STEP_COARSE), "Up")
screen.onkey(lambda: nudge(-STEP_COARSE), "Down")

# 光线开关
screen.onkey(toggle_rays, "r")
screen.onkey(toggle_rays, "R")

screen.listen()

# ==================== 启动 ====================
draw_static()
handle.showturtle()
update()
turtle.done()