from manim import *
import numpy as np
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 LightningAnimation(Animation):
    """自定义动画：带随机转折与分叉的闪烁闪电。"""
    def __init__(self, start_point, end_point, num_points=12,
                 color=YELLOW, seed=3, **kwargs):
        line = VMobject().set_stroke(color, width=5)
        super().__init__(line, **kwargs)
        self.start_point = np.array(start_point, dtype=float)
        self.end_point = np.array(end_point, dtype=float)
        self.num_points = num_points
        self.color = color
        rng = np.random.default_rng(seed)
        self.offsets = rng.uniform(-0.55, 0.55, num_points)
    def interpolate_mobject(self, alpha):
        vec = self.end_point - self.start_point
        perp = np.array([-vec[1], vec[0], 0.0])
        perp /= np.linalg.norm(perp)
        flick = 0.5 + 0.5 * np.sin(alpha * 22)
        pts = [self.start_point]
        for i in range(1, self.num_points + 1):
            t = i / (self.num_points + 1)
            pts.append(self.start_point + t * vec
                       + perp * self.offsets[i - 1] * flick)
        pts.append(self.end_point)
        self.mobject.set_points_as_corners(pts).set_stroke(
            self.color, width=5, opacity=0.45 + 0.55 * flick)
class LightningLong(Scene):
    def construct(self):
        self.camera.background_color = "#0d0d1a"
        self.add(head("闪电特效：长距离带分叉", "LightningAnimation / set_points_as_corners"))
        main = LightningAnimation([-5, 2.6, 0], [5, -2.6, 0], num_points=16, seed=5, run_time=4.0)
        fork = LightningAnimation([0.2, 0.1, 0], [2.6, -2.3, 0], num_points=7, color=BLUE, seed=9, run_time=4.0)
        fork2 = LightningAnimation([-1.2, 0.5, 0], [-3.2, -2.0, 0], num_points=6, color=BLUE, seed=13, run_time=4.0)
        self.add(main.mobject, fork.mobject, fork2.mobject)
        self.play(main, fork, fork2, run_time=4.0)
        self.play(FadeIn(foot("转折点加垂直方向随机偏移，正弦函数控制明暗闪烁")), run_time=0.4)
        self.wait(1.4)
