Skip to content

Commit 3efd6e7

Browse files
committed
python recursion
1 parent 4c71cf0 commit 3efd6e7

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

taiyangxue/recursion/fractalTree.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
from turtle import Turtle
2+
3+
def line(t):
4+
t.backward(100)
5+
6+
def drawSpiral(myTurtle, lineLen):
7+
if lineLen < 500:
8+
myTurtle.forward(lineLen)
9+
myTurtle.right(90)
10+
drawSpiral(myTurtle, lineLen+20)
11+
12+
def fractalTree1(branchLen, t):
13+
t.forward(branchLen)
14+
if branchLen > 5:
15+
t.right(20)
16+
fractalTree1(branchLen - 15, t)
17+
t.left(20)
18+
t.backward(branchLen)
19+
if branchLen > 5:
20+
t.left(20)
21+
fractalTree1(branchLen - 15, t)
22+
t.right(20)
23+
# t.backward(branchLen)
24+
def fractalTree2(branchLen, t):
25+
t.forward(branchLen)
26+
if branchLen > 5:
27+
t.right(20)
28+
fractalTree2(branchLen - 15, t)
29+
t.left(20)
30+
t.backward(branchLen)
31+
if branchLen > 5:
32+
t.left(20)
33+
fractalTree2(branchLen - 15, t)
34+
t.right(20)
35+
36+
def tree2(branchLen, t):
37+
t.forward(branchLen)
38+
if branchLen > 5:
39+
t.right(20)
40+
tree2(branchLen - 15, t)
41+
t.left(20)
42+
t.backward(branchLen)
43+
if branchLen > 5:
44+
t.left(20)
45+
tree2(branchLen - 15, t)
46+
t.right(20)
47+
48+
def fractalTree(branchLen, t):
49+
if branchLen > 0:
50+
t.forward(branchLen)
51+
t.right(20)
52+
fractalTree(branchLen - 15, t)
53+
t.left(40)
54+
fractalTree(branchLen - 15, t)
55+
t.right(20)
56+
t.backward(branchLen)
57+
58+
if __name__ == '__main__':
59+
t = Turtle() # 创建画布实例
60+
t.screen.delay(0) # 设置绘制显示延迟,以便观察过程
61+
62+
# 初始化画笔
63+
t.pensize(2) # 设置画笔粗细为 2 个像素
64+
t.color('green') # 设置画笔颜色为 绿色
65+
t.left(90) # 向左旋转 90 度,即让画笔朝上
66+
t.up() # 抬起画笔,即在移动时不会绘制
67+
t.backward(300) # 相对画笔朝向,向后退 300 个像素
68+
t.down() # 落下画笔,准备绘制
69+
70+
fractalTree2(130, t) # 绘制分形树,根树干长度为 105 像素
71+
72+
# 获取画布窗口,并设置关闭条件为点击窗口,以便在执行完成后保留绘图窗口
73+
t.getscreen().exitonclick()
74+
75+

0 commit comments

Comments
 (0)