import pygame

pygame.init()

W, H = 900, 500
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("凸透镜成像演示")
clock = pygame.time.Clock()

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (200, 30, 30)
ORANGE = (255, 150, 50)
BLUE = (30, 80, 200)
GREEN = (30, 160, 60)
GRAY = (180, 180, 180)

# 统一初始化字体，捕获异常兜底
try:
    font_small = pygame.font.SysFont("simhei", 20)
    font_mid = pygame.font.SysFont("simhei", 24)
    font_btn = pygame.font.SysFont("simhei", 26)
except:
    font_small = pygame.font.Font(None, 20)
    font_mid = pygame.font.Font(None, 24)
    font_btn = pygame.font.Font(None, 26)

lens_x = W // 2
center_y = H // 2

f = 80
u = 200
running_sim = False
anim_speed = 1

class Slider:
    def __init__(self, x, y, w, h, min_val, max_val, init_val, label):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.min_val = min_val
        self.max_val = max_val
        self.val = init_val
        self.label = label
        self.dragging = False

    def draw(self, surf):
        pygame.draw.rect(surf, GRAY, (self.x, self.y, self.w, self.h))
        ratio = (self.val - self.min_val) / (self.max_val - self.min_val)
        cx = self.x + int(ratio * self.w)
        pygame.draw.circle(surf, RED, (cx, self.y + self.h//2), 8)
        t = font_mid.render(f"{self.label}: {self.val}", True, BLACK)
        surf.blit(t, (self.x, self.y - 22))

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            mx, my = event.pos
            if self.x <= mx <= self.x + self.w and self.y <= my <= self.y + self.h:
                self.dragging = True
        elif event.type == pygame.MOUSEBUTTONUP:
            self.dragging = False
        elif event.type == pygame.MOUSEMOTION and self.dragging:
            mx, _ = event.pos
            ratio = max(0, min(1, (mx - self.x) / self.w))
            self.val = int(self.min_val + ratio * (self.max_val - self.min_val))

btn_rect = pygame.Rect(W - 130, 20, 110, 35)

slider_f = Slider(60, H - 70, 200, 14, 30, 150, f, "焦距 f")
slider_u = Slider(300, H - 70, 200, 14, 50, 350, u, "物距 u")

def calc_image(u, f):
    if u == f:
        return None, None
    v = (u * f) / (u - f)
    scale = -v / u
    return v, scale

def draw_candle(surf, x, y, height, color):
    pygame.draw.rect(surf, color, (x - 8, y - height, 16, height))
    pygame.draw.circle(surf, ORANGE, (x, y - height - 6), 7)

while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            exit()
        slider_f.handle_event(e)
        slider_u.handle_event(e)
        if e.type == pygame.MOUSEBUTTONDOWN:
            if btn_rect.collidepoint(e.pos):
                running_sim = not running_sim

    f = slider_f.val
    u = slider_u.val

    if running_sim:
        u += anim_speed
        if u > 350 or u < 50:
            anim_speed *= -1
        slider_u.val = u

    screen.fill(WHITE)

    pygame.draw.line(screen, BLACK, (0, center_y), (W, center_y), 2)
    pygame.draw.line(screen, BLUE, (lens_x, center_y - 160), (lens_x, center_y + 160), 4)

    pygame.draw.circle(screen, GREEN, (lens_x - f, center_y), 4)
    pygame.draw.circle(screen, GREEN, (lens_x + f, center_y), 4)
    screen.blit(font_small.render("F", True, GREEN), (lens_x - f - 12, center_y + 8))
    screen.blit(font_small.render("F", True, GREEN), (lens_x + f + 4, center_y + 8))

    obj_x = lens_x - u
    obj_h = 70
    draw_candle(screen, obj_x, center_y, obj_h, RED)

    v, scale = calc_image(u, f)
    if v is not None:
        img_x = lens_x + v
        img_h = obj_h * scale
        draw_candle(screen, int(img_x), center_y, int(img_h), (120, 30, 160))

        pygame.draw.line(screen, (100,100,100), (obj_x, center_y - obj_h), (lens_x, center_y - obj_h))
        pygame.draw.line(screen, (100,100,100), (lens_x, center_y - obj_h), (lens_x + f, center_y))
        pygame.draw.line(screen, (100,100,100), (lens_x + f, center_y), (img_x, center_y - img_h))
        pygame.draw.line(screen, (100,100,100), (obj_x, center_y - obj_h), (img_x, center_y - img_h))

    slider_f.draw(screen)
    slider_u.draw(screen)

    btn_text = "暂停" if running_sim else "运行"
    pygame.draw.rect(screen, GREEN if running_sim else GRAY, btn_rect)
    t = font_btn.render(btn_text, True, WHITE)
    screen.blit(t, (btn_rect.x + 25, btn_rect.y + 6))

    tip = ""
    if u > 2*f:
        tip = "物距 > 2f：倒立、缩小实像（照相机原理）"
    elif abs(u - 2*f) < 8:
        tip = "物距 = 2f：倒立、等大实像"
    elif f < u < 2*f:
        tip = "f < 物距 < 2f：倒立、放大实像（投影仪）"
    elif abs(u - f) < 6:
        tip = "物距 = f：不成像"
    elif u < f:
        tip = "物距 < f：正立、放大虚像（放大镜）"
    text_tip = font_mid.render(tip, True, BLACK)
    screen.blit(text_tip, (20, 20))

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