import pygame
import math

pygame.init()

W, H = 1000, 600
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, 0, 0)
GREEN = (0, 160, 0)
BLUE = (0, 80, 200)
GRAY = (120, 120, 120)

# 光学参数
center_x = W // 2
center_y = H // 2
f = 120          # 焦距
two_f = f * 2

# 物体（蜡烛）
obj_x = center_x - two_f - 30
obj_y = center_y
obj_h = 70
dragging = False

def calc_image(ox, oy):
    # 透镜在 center_x
    u = center_x - ox
    if abs(u) < 1:
        return None
    # 透镜公式 1/f = 1/u + 1/v
    v = (u * f) / (u - f)
    img_x = center_x + v
    scale = v / u
    img_h = obj_h * scale
    img_y = center_y - img_h
    return img_x, img_y, img_h, v

running = True
while running:
    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) < 35 and abs(my - obj_y) < obj_h:
                dragging = True
        elif event.type == pygame.MOUSEBUTTONUP:
            dragging = False
        elif event.type == pygame.MOUSEMOTION and dragging:
            mx, my = event.pos
            obj_x = max(20, min(center_x - 10, mx))
            obj_y = center_y

    screen.fill(WHITE)

    # 主光轴
    pygame.draw.line(screen, GRAY, (0, center_y), (W, center_y), 2)
    # 凸透镜
    pygame.draw.line(screen, BLUE, (center_x, center_y - 180), (center_x, center_y + 180), 4)
    # 焦点、2F
    for sign in (-1, 1):
        fx = center_x + sign * f
        f2x = center_x + sign * two_f
        pygame.draw.circle(screen, GREEN, (fx, center_y), 5)
        pygame.draw.circle(screen, GRAY, (f2x, center_y), 4)

    # 画物体（蜡烛）
    pygame.draw.rect(screen, RED, (obj_x - 12, obj_y - obj_h, 24, obj_h))
    pygame.draw.circle(screen, RED, (obj_x, obj_y - obj_h - 8), 10)

    img_info = calc_image(obj_x, obj_y)
    if img_info is not None:
        img_x, img_y, img_h, v = img_info
        is_real = v > 0

        # 三条特殊光线
        # 1. 平行光 → 过右焦点
        pygame.draw.line(screen, BLACK, (obj_x, obj_y - obj_h), (center_x, obj_y - obj_h), 1)
        pygame.draw.line(screen, BLACK, (center_x, obj_y - obj_h), (center_x + f, center_y), 1)
        # 2. 过光心方向不变
        pygame.draw.line(screen, BLACK, (obj_x, obj_y - obj_h), (center_x, center_y), 1)
        # 3. 过左焦点 → 平行射出
        pygame.draw.line(screen, BLACK, (obj_x, obj_y - obj_h), (center_x - f, center_y), 1)
        pygame.draw.line(screen, BLACK, (center_x - f, center_y), (W, center_y - obj_h), 1)

        # 画像
        if abs(img_h) > 5 and abs(img_h) < 300:
            if is_real:
                pygame.draw.rect(screen, BLUE, (img_x - 12, img_y, 24, -img_h), 2)
            else:
                pygame.draw.rect(screen, (100, 100, 255), (img_x - 12, img_y, 24, -img_h), 2)

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

pygame.quit()
