from manim import *
import numpy as np
from numpy import array
run_time = 1
data = [[1, 2], [3, 4]]
def dot(pos, **kwargs):
    return Dot(pos, **kwargs)
import sympy as sp
x, y = sp.symbols('x y', real=True)
a, b, c = 3, 5, 4  # BC, AC, AB
# 距离约束转化为方程
eq1 = (x - 0)**2 + (y - 0)**2 - b**2  # AC = 5
eq2 = (x - c)**2 + (y - 0)**2 - a**2  # BC = 3
solutions = sp.solve([eq1, eq2], (x, y))
# 输出两组解：[(4, -3), (4, 3)]  —— 对应镜像三角形
import sympy as sp
x, y = sp.symbols('x y', real=True)
b, c, theta = 4, 5, sp.rad(60)  # AC=4, AB=5, ∠A=60°
# C 到 A 的距离
eq1 = x**2 + y**2 - b**2
# 用余弦定理：BC² = AB² + AC² - 2·AB·AC·cosθ
bc_sq = c**2 + b**2 - 2*c*b*sp.cos(theta)
eq2 = (x - c)**2 + y**2 - bc_sq
solutions = sp.solve([eq1, eq2], (x, y))
# 筛选 y >= 0 的解（取上方三角形）
valid_solution = [sol for sol in solutions if sol[1] >= 0][0]
import sympy as sp
import numpy as np
class SSSCongruenceDemo(Scene):
    def construct(self):
        # 固定两个顶点
        A = np.array([-1, 0, 0])
        B = np.array([1, 0, 0])
        # 可调边长
        a_tracker = ValueTracker(2)  # BC
        b_tracker = ValueTracker(2)  # AC
        # 用 always_redraw 动态更新三角形（两个镜像三角形）
        triangles = always_redraw(
            lambda: self.get_triangles(
                A, B, a_tracker.get_value(), b_tracker.get_value()
            )
        )
        self.play(*[FadeIn(_o) for _o in [triangles]], run_time=1.0)
        # 顶点标签
        labels = always_redraw(
            lambda: self.get_labels(A, B, a_tracker.get_value(), b_tracker.get_value())
        )
        self.play(*[FadeIn(_o) for _o in [labels]], run_time=1.0)
        # 边长标注
        side_labels = always_redraw(
            lambda: self.get_side_labels(
                A, B, a_tracker.get_value(), b_tracker.get_value()
            )
        )
        self.play(*[FadeIn(_o) for _o in [side_labels]], run_time=1.0)
        # 动画：改变 BC 和 AC 的长度
        self.play(a_tracker.animate.set_value(3), run_time=2)
        self.play(b_tracker.animate.set_value(1), run_time=2)
        self.play(
            a_tracker.animate.set_value(2), b_tracker.animate.set_value(2), run_time=2
        )
        self.wait()
    def solve_vertex_C(self, A, B, a, b):
        """用 SymPy 求解顶点 C，返回两个镜像点的 np.array 坐标列表"""
        x, y = sp.symbols("x y", real=True)
        # AB 的长度
        c = np.linalg.norm(B - A)
        # 距离约束方程
        eq1 = (x - 0) ** 2 + (y - 0) ** 2 - b**2  # 以 A 为原点
        eq2 = (x - c) ** 2 + (y - 0) ** 2 - a**2  # 以 B 为原点
        solutions = sp.solve([eq1, eq2], (x, y), dict=True)
        if not solutions:
            return []
        # 转换到实际坐标系
        AB_vec = B - A
        x_axis = AB_vec / c
        y_axis = np.array([-x_axis[1], x_axis[0], 0])
        C_points = []
        for sol in solutions:
            sol_x = float(sp.N(sol[x]))
            sol_y = float(sp.N(sol[y]))
            # 局部坐标转全局坐标
            C = A + sol_x * x_axis + sol_y * y_axis
            C_points.append(C)
        return C_points
    def get_triangles(self, A, B, a, b):
        C_points = self.solve_vertex_C(A, B, a, b)
        if not C_points:
            return VGroup()  # 无法构成三角形时返回空
        triangles = VGroup()
        colors = [BLUE, GREEN]
        for i, C in enumerate(C_points):
            triangle = Polygon(
                A, B, C, color=colors[i % 2], fill_opacity=0.3, stroke_width=2
            )
            triangles.add(triangle)
        return triangles
    def get_labels(self, A, B, a, b):
        C_points = self.solve_vertex_C(A, B, a, b)
        if not C_points:
            return VGroup()
        label_A = MathTex("A", color=WHITE, font_size=28).next_to(A, DL, buff=0.15)
        label_B = MathTex("B", color=WHITE, font_size=28).next_to(B, DR, buff=0.15)
        labels = VGroup(label_A, label_B)
        for i, C in enumerate(C_points):
            direction = UP if C[1] >= A[1] else DOWN
            label_C = MathTex(f"C_{i+1}", color=WHITE, font_size=28).next_to(
                C, direction, buff=0.15
            )
            labels.add(label_C)
        return labels
    def get_side_labels(self, A, B, a, b):
        C_points = self.solve_vertex_C(A, B, a, b)
        if not C_points:
            return VGroup()
        c = np.linalg.norm(B - A)
        labels = VGroup()
        # AB 边长标注（共用）
        label_AB = MathTex(f"{c:.1f}", font_size=24, color=YELLOW).move_to(
            (A + B) / 2 + DOWN * 0.3
        )
        labels.add(label_AB)
        # 每个三角形的 AC 和 BC 边长标注
        for i, C in enumerate(C_points):
            direction = LEFT if C[0] < (A[0] + B[0]) / 2 else RIGHT
            label_AC = MathTex(f"{b:.1f}", font_size=24, color=RED).move_to(
                (A + C) / 2 + direction * 0.3
            )
            label_BC = MathTex(f"{a:.1f}", font_size=24, color=RED).move_to(
                (B + C) / 2 + (-direction) * 0.3
            )
            labels.add(label_AC, label_BC)
        return labels