import pygame
import math
import sys

pygame.init()

WIDTH, HEIGHT = 1000, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("七巧板")

BG_COLOR = (245, 245, 235)
PANEL_COLOR = (220, 220, 210)
TEXT_COLOR = (50, 50, 50)
HIGHLIGHT = (255, 200, 0)
SNAP_COLOR = (0, 200, 100)
SUCCESS_COLOR = (40, 200, 80)
GHOST_ALPHA = 100

COLORS = [
    (231, 76, 60), (46, 204, 113), (52, 152, 219),
    (241, 196, 15), (155, 89, 182), (230, 126, 34), (26, 188, 156),
]

S = 200
SNAP_DIST = 18
MATCH_TOL = 20
TARGET_ORIGIN = (720, 240)


def get_chinese_font(size):
    for path in ["C:/Windows/Fonts/msyh.ttc", "C:/Windows/Fonts/simhei.ttf",
                 "C:/Windows/Fonts/simsun.ttc", "C:/Windows/Fonts/simkai.ttf"]:
        try:
            return pygame.font.Font(path, size)
        except (FileNotFoundError, OSError):
            continue
    return pygame.font.Font(None, size)


# ============================================================
# 标准七巧板拼正方形（顶点坐标，正方形边长归一化为 1）
# 这套坐标是公开的经典摆法，面积总和 = 1，能严丝合缝拼成正方形
# ============================================================
NORM_TARGET = {
    # 大三角形1：左上，直角在左上角
    "大三角形1": [(0.0, 0.0), (0.5, 0.0), (0.0, 0.5)],

    # 大三角形2：右上，直角在右上角
    "大三角形2": [(1.0, 0.0), (0.5, 0.0), (1.0, 0.5)],

    # 中三角形：左下，直角在左下
    "中三角形": [(0.0, 0.5), (0.0, 1.0), (0.5, 1.0)],

    # 小三角形1：中上偏左
    "小三角形1": [(0.5, 0.5), (0.5, 0.25), (0.75, 0.5)],

    # 小三角形2：中上偏右
    "小三角形2": [(0.5, 0.5), (0.75, 0.5), (0.5, 0.75)],

    # 正方形：中心偏右下（菱形）
    "正方形": [(0.5, 0.5), (0.5, 0.75), (0.75, 1.0), (0.75, 0.75)],

    # 平行四边形：底部
    "平行四边形": [(0.5, 0.75), (0.75, 1.0), (1.0, 1.0), (0.75, 0.75)],
}


def build_local_shapes():
    """归一化顶点 → 以质心为原点的局部形状"""
    shapes = {}
    for name, pts in NORM_TARGET.items():
        world = [(x * S, y * S) for x, y in pts]
        cx = sum(p[0] for p in world) / len(world)
        cy = sum(p[1] for p in world) / len(world)
        shapes[name] = [(x - cx, y - cy) for x, y in world]
    return shapes


SHAPES = build_local_shapes()


def build_target_polygons(ox, oy):
    return {name: [(ox + x * S, oy + y * S) for x, y in pts]
            for name, pts in NORM_TARGET.items()}


class Piece:
    def __init__(self, name, points, color, pos):
        self.name = name
        self.base_points = points
        self.color = color
        self.pos = list(pos)
        self.angle = 0
        self.dragging = False
        self.drag_offset = (0, 0)
        self.selected = False
        self.matched = False

    def get_points(self):
        rad = math.radians(self.angle)
        ca, sa = math.cos(rad), math.sin(rad)
        return [(x * ca - y * sa + self.pos[0],
                 x * sa + y * ca + self.pos[1])
                for x, y in self.base_points]

    def contains_point(self, point):
        pts = self.get_points()
        x, y = point
        n = len(pts)
        inside = False
        j = n - 1
        for i in range(n):
            xi, yi = pts[i]
            xj, yj = pts[j]
            if ((yi > y) != (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi):
                inside = not inside
            j = i
        return inside

    def draw(self, surface):
        pts = self.get_points()
        pygame.draw.polygon(surface, self.color, pts)
        bc = HIGHLIGHT if self.selected else (60, 60, 60)
        bw = 3 if self.selected else 2
        pygame.draw.polygon(surface, bc, pts, bw)


def collect_snap_targets(pieces, exclude, target_polys):
    targets = []
    for p in pieces:
        if p is exclude:
            continue
        targets.extend(p.get_points())
    for pts in target_polys.values():
        targets.extend(pts)
    return targets


def try_snap(piece, pieces, target_polys):
    targets = collect_snap_targets(pieces, piece, target_polys)
    if not targets:
        return list(piece.pos), False
    sa = round(piece.angle / 15) * 15
    changed = abs(sa - piece.angle) > 0.01
    rad = math.radians(sa)
    ca, sn = math.cos(rad), math.sin(rad)
    bdx = bdy = None
    bd = SNAP_DIST
    for sx, sy in piece.base_points:
        wx = sx * ca - sy * sn + piece.pos[0]
        wy = sx * sn + sy * ca + piece.pos[1]
        for tx, ty in targets:
            d = math.hypot(wx - tx, wy - ty)
            if d < bd:
                bd = d
                bdx, bdy = tx - wx, ty - wy
    if bdx is not None:
        piece.angle = sa
        return [piece.pos[0] + bdx, piece.pos[1] + bdy], True
    if changed:
        piece.angle = sa
        return list(piece.pos), True
    return list(piece.pos), False


def update_match_flags(pieces, target_polys):
    matched = 0
    names = set()
    for piece in pieces:
        piece.matched = False
        target = target_polys.get(piece.name)
        if target is None or len(piece.base_points) != len(target):
            continue
        p_pts = piece.get_points()
        used = [False] * len(target)
        ok = True
        for px, py in p_pts:
            bd = 1e9
            bj = -1
            for j, (tx, ty) in enumerate(target):
                if used[j]:
                    continue
                d = math.hypot(px - tx, py - ty)
                if d < bd:
                    bd, bj = d, j
            if bj < 0 or bd > MATCH_TOL:
                ok = False
                break
            used[bj] = True
        if ok:
            piece.matched = True
            names.add(piece.name)
            matched += 1
    return matched, names


def make_ghost_surfaces(target_polys):
    ghosts = {}
    for name, pts in target_polys.items():
        min_x = min(p[0] for p in pts)
        max_x = max(p[0] for p in pts)
        min_y = min(p[1] for p in pts)
        max_y = max(p[1] for p in pts)
        w = int(max_x - min_x) + 4
        h = int(max_y - min_y) + 4
        surf = pygame.Surface((w, h), pygame.SRCALPHA)
        lp = [(p[0] - min_x + 2, p[1] - min_y + 2) for p in pts]
        idx = list(NORM_TARGET.keys()).index(name)
        pygame.draw.polygon(surf, (*COLORS[idx], GHOST_ALPHA), lp)
        pygame.draw.polygon(surf, (90, 90, 90, 220), lp, 2)
        ghosts[name] = (surf, (int(min_x) - 2, int(min_y) - 2))
    return ghosts


def draw_ghosts(surface, ghosts, pieces):
    mn = {p.name for p in pieces if p.matched}
    for name, (surf, tl) in ghosts.items():
        if name not in mn:
            surface.blit(surf, tl)


def create_pieces():
    pieces = []
    starts = [(110, 170), (350, 170), (110, 370),
              (350, 370), (540, 370), (110, 550), (350, 550)]
    for i, (name, pts) in enumerate(SHAPES.items()):
        pieces.append(Piece(name, pts, COLORS[i], starts[i]))
    return pieces


def draw_target_square(surface, font):
    ox, oy = TARGET_ORIGIN
    rect = pygame.Rect(ox, oy, S, S)
    pygame.draw.rect(surface, (200, 200, 200), rect, 2)
    surface.blit(font.render("目标区域", True, (150, 150, 150)), (ox, oy - 22))


def draw_ui(surface, pieces, font, small_font, matched, total, snapped, show_answer):
    pygame.draw.rect(surface, PANEL_COLOR, pygame.Rect(0, 0, WIDTH, 60))
    surface.blit(font.render("七巧板模拟器", True, TEXT_COLOR), (20, 8))
    pc = SUCCESS_COLOR if matched == total else (200, 50, 50)
    surface.blit(font.render(f"完成度: {matched}/{total}", True, pc),
                 (WIDTH - 180, 8))
    surface.blit(small_font.render(
        "左键拖拽 | 右键旋转15° | 滚轮旋转5° | 空格看答案 | R重置 | ESC退出",
        True, TEXT_COLOR), (20, 36))
    for p in pieces:
        if p.selected:
            surface.blit(small_font.render(
                f"选中: {p.name}  角度: {p.angle:.0f}°",
                True, (200, 50, 50)), (20, HEIGHT - 28))
            break
    if show_answer:
        surface.blit(small_font.render("参考答案: 显示中", True, (100, 100, 200)),
                     (WIDTH - 180, HEIGHT - 28))
    if snapped:
        surface.blit(small_font.render("已吸附", True, SNAP_COLOR),
                     (WIDTH - 90, HEIGHT - 28))


def main():
    clock = pygame.time.Clock()
    font = get_chinese_font(24)
    small_font = get_chinese_font(16)

    target_polys = build_target_polygons(*TARGET_ORIGIN)
    ghosts = make_ghost_surfaces(target_polys)

    pieces = create_pieces()
    active_piece = None
    snapped_flag = False
    show_answer = False

    running = True
    while running:
        mouse_pos = pygame.mouse.get_pos()
        snapped_flag = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key == pygame.K_r:
                    pieces = create_pieces()
                    active_piece = None
                elif event.key == pygame.K_SPACE:
                    show_answer = not show_answer

            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    for piece in reversed(pieces):
                        if piece.contains_point(mouse_pos):
                            for p in pieces:
                                p.selected = False
                            piece.selected = True
                            piece.dragging = True
                            piece.drag_offset = (
                                mouse_pos[0] - piece.pos[0],
                                mouse_pos[1] - piece.pos[1],
                            )
                            pieces.remove(piece)
                            pieces.append(piece)
                            active_piece = piece
                            break
                    else:
                        for p in pieces:
                            p.selected = False

                elif event.button == 3:
                    for piece in reversed(pieces):
                        if piece.contains_point(mouse_pos):
                            piece.angle = (piece.angle + 15) % 360
                            for p in pieces:
                                p.selected = False
                            piece.selected = True
                            break

                elif event.button == 4:
                    for piece in reversed(pieces):
                        if piece.contains_point(mouse_pos):
                            piece.angle = (piece.angle + 5) % 360
                            break

                elif event.button == 5:
                    for piece in reversed(pieces):
                        if piece.contains_point(mouse_pos):
                            piece.angle = (piece.angle - 5) % 360
                            break

            elif event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1 and active_piece:
                    new_pos, did = try_snap(active_piece, pieces, target_polys)
                    active_piece.pos = new_pos
                    snapped_flag = did
                    active_piece.dragging = False
                    active_piece = None

            elif event.type == pygame.MOUSEMOTION:
                if active_piece and active_piece.dragging:
                    active_piece.pos[0] = mouse_pos[0] - active_piece.drag_offset[0]
                    active_piece.pos[1] = mouse_pos[1] - active_piece.drag_offset[1]
                    new_pos, did = try_snap(active_piece, pieces, target_polys)
                    active_piece.pos = new_pos
                    snapped_flag = did

        matched, matched_names = update_match_flags(pieces, target_polys)

        screen.fill(BG_COLOR)
        draw_target_square(screen, small_font)

        if show_answer:
            draw_ghosts(screen, ghosts, pieces)

        for piece in pieces:
            piece.draw(screen)

        draw_ui(screen, pieces, font, small_font,
                matched, len(target_polys), snapped_flag, show_answer)

        tip = small_font.render(
            "提示: 空格键切换参考答案 | 靠近目标顶点会自动吸附",
            True, (120, 120, 120))
        screen.blit(tip, (20, HEIGHT - 55))

        if matched == len(target_polys):
            banner = font.render("拼图完成！", True, SUCCESS_COLOR)
            r = banner.get_rect(center=(WIDTH // 2, 90))
            screen.blit(banner, r)

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

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()