import pygame
import sys
import math

# --- 初始化与常量 ---
pygame.init()
WIDTH, HEIGHT = 1200, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("精致版：凸透镜成像交互演示")
clock = pygame.time.Clock()

# 字体
try:
    font_title = pygame.font.SysFont("Microsoft YaHei", 24, bold=True)
    font_main = pygame.font.SysFont("Microsoft YaHei", 18)
    font_small = pygame.font.SysFont("Microsoft YaHei", 14)
except:
    font_title = pygame.font.SysFont("simhei", 24, bold=True)
    font_main = pygame.font.SysFont("simhei", 18)
    font_small = pygame.font.SysFont("simhei", 14)

# 配色方案
C_BG = (245, 248, 252)
C_AXIS = (160, 165, 175)
C_LENS_FILL = (220, 235, 255)
C_LENS_OUT = (60, 120, 220)
C_OBJ = (230, 60, 60)
C_REAL = (40, 130, 230)
C_VIRT = (160, 70, 210)
C_RAY1 = (230, 80, 80)
C_RAY2 = (40, 180, 80)
C_SCREEN = (210, 210, 210)
C_TEXT_INFO = (40, 40, 40)

# 场景几何
AXIS_Y = HEIGHT // 2 + 40
LENS_X = WIDTH // 2
LENS_H = 200
LENS_W = 14

# 物理状态
focal_len = 100.0
obj_x = LENS_X - 280.0
obj_h = 70.0
screen_x = LENS_X + 280.0
show_rays = True
dragging_obj = False
dragging_screen = False

def calculate_image(u, f):
    if abs(u) < 1e-5 or abs(u - f) < 1e-5:
        return None, 0
    v = 1.0 / (1.0 / f - 1.0 / u)
    m = -v / u
    return v, m

def get_image_desc(u, f, v, m):
    if v is None:
        return "不成像 (u = f)", (100, 100, 100)
    if v > 0:
        size = "放大" if abs(m) > 1.05 else "缩小" if abs(m) < 0.95 else "等大"
        return f"倒立、{size}、实像", C_REAL
    else:
        return "正立、放大、虚像", C_VIRT

def draw_flame(surf, x, y_base, h, t):
    """绘制动态火焰"""
    if h < 5: return
    colors = [(255, 200, 0), (255, 100, 0), (255, 50, 50)]
    layers = 3
    for i in range(layers):
        factor = 1.0 - i * 0.25
        color = colors[i]
        flicker = math.sin(t * 0.015 + i) * 3
        w = (12 - i * 3) * factor
        hh = h * factor + flicker
        pts = [
            (x, y_base - hh),
            (x - w, y_base),
            (x + w, y_base)
        ]
        pygame.draw.polygon(surf, color, pts)

def draw_arrow(surf, x, y_base, h, color, label=""):
    if abs(h) < 1: return
    is_inverted = h < 0
    y_tip = y_base - h
    pygame.draw.line(surf, color, (x, y_base), (x, y_tip), 4)
    head_size = 8
    if is_inverted:
        pts = [(x, y_tip), (x - head_size, y_tip + head_size*1.5), (x + head_size, y_tip + head_size*1.5)]
    else:
        pts = [(x, y_tip), (x - head_size, y_tip - head_size*1.5), (x + head_size, y_tip - head_size*1.5)]
    pygame.draw.polygon(surf, color, pts)
    if label:
        txt = font_main.render(label, True, color)
        surf.blit(txt, (x - txt.get_width()//2, y_tip - 25 if not is_inverted else y_tip + 10))

def draw_lens_body(surf):
    pts_l, pts_r = [], []
    for i in range(40):
        y_norm = -1 + 2 * i / 39
        dx = LENS_W * math.sqrt(max(0, 1 - y_norm**2))
        y = AXIS_Y + y_norm * LENS_H
        pts_l.append((LENS_X - dx, y))
        pts_r.append((LENS_X + dx, y))
    poly = pts_l + pts_r[::-1]
    pygame.draw.polygon(surf, C_LENS_FILL, poly)
    pygame.draw.lines(surf, C_LENS_OUT, True, poly, 2)
    pygame.draw.circle(surf, (0,0,0), (LENS_X, AXIS_Y), 3)

def draw_dashed_line(surf, color, start, end, dash=6):
    dx, dy = end[0]-start[0], end[1]-start[1]
    dist = math.hypot(dx, dy)
    if dist < 1: return
    ux, uy = dx/dist, dy/dist
    t = 0
    while t < dist:
        t_end = min(t + dash, dist)
        p1 = (start[0]+ux*t, start[1]+uy*t)
        p2 = (start[0]+ux*t_end, start[1]+uy*t_end)
        pygame.draw.line(surf, color, p1, p2, 2)
        t += dash * 2

def main():
    global focal_len, obj_x, screen_x, show_rays, dragging_obj, dragging_screen
    
    t = 0
    running = True
    while running:
        t += 1
        for event in pygame.event.get():
            if event.type == pygame.QUIT: running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mx, my = event.pos
                if abs(mx - obj_x) < 25 and abs(my - AXIS_Y) < 100: dragging_obj = True
                elif abs(mx - screen_x) < 15 and AXIS_Y < my < AXIS_Y + 150: dragging_screen = True
            elif event.type == pygame.MOUSEBUTTONUP:
                dragging_obj = False
                dragging_screen = False
            elif event.type == pygame.MOUSEMOTION:
                if dragging_obj: obj_x = max(LENS_X - 450, min(LENS_X - 10, event.pos[0]))
                if dragging_screen: screen_x = max(LENS_X + 20, min(WIDTH - 50, event.pos[0]))
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE: show_rays = not show_rays
                if event.key == pygame.K_UP: focal_len = min(200, focal_len + 5)
                if event.key == pygame.K_DOWN: focal_len = max(40, focal_len - 5)

        u = LENS_X - obj_x
        v, m = calculate_image(u, focal_len)
        img_h = obj_h * m if m else 0
        img_x = LENS_X + v if v is not None else 0
        desc, desc_col = get_image_desc(u, focal_len, v, m)

        # --- 绘图 ---
        screen.fill(C_BG)
        
        # 1. 主光轴与刻度
        pygame.draw.line(screen, C_AXIS, (50, AXIS_Y), (WIDTH-50, AXIS_Y), 2)
        for f_sign in [-1, 1]:
            for k, col, txt in [(1, (230, 140, 30), "F"), (2, (140, 80, 200), "2F")]:
                px = LENS_X + f_sign * k * focal_len
                pygame.draw.line(screen, col, (px, AXIS_Y-6), (px, AXIS_Y+6), 2)
                screen.blit(font_small.render(txt, True, col), (px-6, AXIS_Y+10))

        # 2. 透镜
        draw_lens_body(screen)
        screen.blit(font_main.render("凸透镜", True, C_LENS_OUT), (LENS_X-25, AXIS_Y-LENS_H-30))

        # 3. 物体 (蜡烛)
        draw_arrow(screen, obj_x, AXIS_Y, 15, C_OBJ) # 蜡烛身
        draw_flame(screen, obj_x, AXIS_Y - 15, obj_h, t) # 火焰
        screen.blit(font_main.render("物体", True, C_OBJ), (obj_x-20, AXIS_Y+30))

        # 4. 像
        if v is not None and abs(v) > 2:
            is_real = v > 0
            color = C_REAL if is_real else C_VIRT
            draw_arrow(screen, img_x, AXIS_Y, img_h, color)
            label = "实像" if is_real else "虚像"
            screen.blit(font_main.render(label, True, color), (img_x-25, AXIS_Y + (img_h if img_h>0 else -img_h) + 20))

        # 5. 光屏
        pygame.draw.rect(screen, (180,180,180), (screen_x, AXIS_Y, 6, 120))
        pygame.draw.polygon(screen, (140,140,140), [(screen_x, AXIS_Y+120), (screen_x+20, AXIS_Y+130), (screen_x-20, AXIS_Y+130)])
        screen.blit(font_small.render("光屏", True, (80,80,80)), (screen_x-10, AXIS_Y+135))
        
        # 光屏上是否成像
        if v is not None and v > 0:
            dist_to_screen = abs(screen_x - img_x)
            if dist_to_screen < 10:
                # 在光屏上画出模糊的像
                alpha_surf = pygame.Surface((40, abs(img_h)+10), pygame.SRCALPHA)
                c_blur = (*C_REAL, 100)
                pygame.draw.ellipse(alpha_surf, c_blur, alpha_surf.get_rect())
                screen.blit(alpha_surf, (screen_x-20, AXIS_Y - max(0, img_h)))
                screen.blit(font_small.render("清晰成像", True, (0,150,0)), (screen_x-30, AXIS_Y - 40))

        # 6. 光线
        if show_rays and v is not None:
            top_obj = (obj_x, AXIS_Y - obj_h)
            top_img = (img_x, AXIS_Y - img_h)
            
            # Ray 1: 平行 -> 过焦点
            pygame.draw.line(screen, C_RAY1, top_obj, (LENS_X, top_obj[1]), 2)
            if v > 0: pygame.draw.line(screen, C_RAY1, (LENS_X, top_obj[1]), top_img, 2)
            else: # 虚像折射光
                end_r = (LENS_X + 600, top_obj[1] + (top_obj[1] - (AXIS_Y)) * (600/focal_len))
                pygame.draw.line(screen, C_RAY1, (LENS_X, top_obj[1]), end_r, 2)
                draw_dashed_line(screen, C_RAY1, (LENS_X, top_obj[1]), top_img)

            # Ray 2: 过光心
            end_2 = (LENS_X + 600, AXIS_Y + (AXIS_Y - top_obj[1]) * (600/(LENS_X+600-obj_x)))
            pygame.draw.line(screen, C_RAY2, top_obj, end_2, 2)
            if v < 0: draw_dashed_line(screen, C_RAY2, (LENS_X, AXIS_Y), top_img)

        # 7. UI 面板
        panel = pygame.Surface((320, 160), pygame.SRCALPHA)
        panel.fill((255,255,255, 220))
        pygame.draw.rect(panel, (200,200,200), panel.get_rect(), 2)
        screen.blit(panel, (10, 10))
        
        infos = [
            f"焦距 f = {focal_len:.1f}",
            f"物距 u = {u:.1f}",
            f"像距 v = {v if v is not None else '∞':.1f}",
            f"放大率 m = {m:.2f}",
        ]
        y_off = 20
        for txt in infos:
            screen.blit(font_small.render(txt, True, C_TEXT_INFO), (20, y_off))
            y_off += 20
        
        pygame.draw.line(screen, C_AXIS, (20, y_off+5), (310, y_off+5), 1)
        y_off += 15
        screen.blit(font_main.render(f"性质：{desc}", True, desc_col), (20, y_off))
        
        # 底部操作栏
        help_txt = "操作：[拖拽] 移动物体/光屏 | [滚轮/↑↓] 调焦距 | [空格] 显隐光线"
        h_surf = font_small.render(help_txt, True, (100,100,100))
        screen.blit(h_surf, (WIDTH//2 - h_surf.get_width()//2, HEIGHT - 30))

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

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
