manim 生成勾股树
时间: 2024-01-11 10:02:34 浏览: 150
以下是使用 Manim 生成勾股树的示例代码:
```python
from manim import *
class PythagorasTree(Scene):
def construct(self):
# 绘制勾股树
self.pythagoras_tree()
def pythagoras_tree(self, depth=4, size=2, angle=0, position=ORIGIN):
if depth == 0:
return
# 绘制直角三角形
triangle = Polygon(
ORIGIN, size * RIGHT, size * RIGHT + size * UP * np.sin(angle),
stroke_width=1, stroke_color=WHITE, fill_opacity=0
)
# 绘制斜边
hypotenuse = Line(size * RIGHT, size * RIGHT + size * UP * np.sin(angle), stroke_width=1, stroke_color=WHITE)
# 计算左右子树的位置
left_pos = hypotenuse.get_end()
right_pos = triangle.get_vertices()[2]
# 绘制左右子树
left_tree = self.pythagoras_tree(depth - 1, size * np.sin(angle), angle + PI / 4, left_pos)
right_tree = self.pythagoras_tree(depth - 1, size * np.cos(angle), angle - PI / 4, right_pos)
# 添加到场景中
self.play(Create(triangle), Create(hypotenuse))
self.play(left_tree, right_tree)
self.wait(0.5)
```
运行上述代码,即可生成勾股树的动画效果。可以根据需要修改 `depth`、`size`、`angle` 和 `position` 等参数来控制勾股树的形态。
阅读全文