from manim import *
import numpy as np
import sympy as sp
def head(cn, en):
    t = Text(cn, font="STLiti", font_size=27).to_edge(UP)
    s = Text(en, font="Consolas", font_size=20, color=YELLOW).next_to(t, DOWN, buff=0.10)
    return VGroup(t, s)
def foot(cn):
    return Text(cn, font="STLiti", font_size=20, color=YELLOW).to_edge(DOWN)
def bg_image(h=60, w=100, mode=0):
    a = np.zeros((h, w, 4), dtype=np.uint8)
    a[:, :, 3] = 255
    if mode == 0:
        a[:, :, 0] = np.linspace(10, 90, w, dtype=np.uint8)[None, :]
        a[:, :, 2] = np.linspace(60, 160, w, dtype=np.uint8)[None, :]
    elif mode == 1:
        a[:, :, 1] = np.linspace(20, 110, h, dtype=np.uint8)[:, None]
        a[:, :, 2] = np.linspace(40, 130, h, dtype=np.uint8)[:, None]
    else:
        a[:, :, 0] = 120
        a[:, :, 1] = 70
        a[:, :, 2] = np.linspace(30, 140, w, dtype=np.uint8)[None, :]
    return ImageMobject(a)
class DynamicIntersection(Scene):
    def construct(self):
        self.add(head("两条直线的动态交点", "SymPy / add_updater"))
        axes = Axes(x_range=[-5, 5, 1], y_range=[-5, 5, 1], x_length=7.6, y_length=5.4,
                    axis_config={"color": GREY_B}).shift(DOWN * 0.3)
        k = ValueTracker(0.6)
        x, y = sp.symbols("x y")
        sol = sp.solve([sp.Eq(y, sp.Rational(1, 2) * x + 1), sp.Eq(y, -x + 4)], [x, y])
        lab = Text("fixed x = %s" % sp.nsimplify(sol[x]), font="Consolas",
                   font_size=21, color=GREY_A).to_corner(UR)
        self.add(lab)
        line1 = axes.plot(lambda t: 0.5 * t + 1, color=BLUE).set_stroke(width=5)
        line2 = always_redraw(lambda: axes.plot(lambda t: -k.get_value() * t + 3,
                                                color=GREEN).set_stroke(width=5))
        dot = always_redraw(lambda: Dot(axes.c2p(
            float(2 / (0.5 + k.get_value())), float(0.5 * 2 / (0.5 + k.get_value()) + 1)),
            color=YELLOW, radius=0.14))
        self.add(axes, line1, line2, dot)
        self.play(k.animate.set_value(2.0), run_time=3.8, rate_func=there_and_back)
        self.play(FadeIn(foot("斜率变化时，交点由两直线方程实时解出")), run_time=0.4)
        self.wait(1.4)
