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)
class SlopeCompare(Scene):
    def construct(self):
        self.add(head("一次函数：不同斜率对比", "SymPy / solve / Axes.plot"))
        x, y = sp.symbols("x y")
        axes = Axes(x_range=[-5, 5, 1], y_range=[-5, 5, 1], x_length=7.6, y_length=5.2,
                    axis_config={"color": GREY_B})
        ks = [2, 1, sp.Rational(-1, 2)]
        cols = [BLUE, GREEN, YELLOW]
        lines = VGroup()
        labels = VGroup()
        for k, c in zip(ks, cols):
            kk = float(k)
            g = axes.plot(lambda t, kk=kk: kk * t + 1, x_range=[-4.5, 4.5], color=c)
            g.set_stroke(width=5)
            lines.add(g)
            root = float(sp.solve(sp.Eq(k * x + 1, 0), x)[0])
            labels.add(Text("k=%s, x0=%.2f" % (k, root), font="Consolas",
                            font_size=18, color=c))
        labels.arrange(DOWN, aligned_edge=LEFT, buff=0.16).to_corner(UL).shift(DOWN * 1.1)
        self.add(axes, labels)
        self.play(LaggedStart(*[Create(g) for g in lines], lag_ratio=0.3), run_time=3.4)
        self.play(FadeIn(foot("与 x 轴交点由 SymPy 解方程得到，不用手算")), run_time=0.4)
        self.wait(2.1)
