Python使用递归绘制谢尔宾斯基三角形
谢尔宾斯基三角形使用了三路递归算法,从一个大三角形开始,通过连接每一个边的中点,将大三角型分为四个三角形,然后忽略中间的三角形,依次对其余三个三角形执行上述操作。
运行效果:
源代码:
1 import turtle
2
3
4 def draw_triangle(points, color, my_angle):
5 my_angle.fillcolor(color)
6 my_angle.up()
7 my_angle.goto(points[0][0], points[0][1])
8 my_angle.down()
9 my_angle.begin_fill()
10 my_angle.goto(points[1][0], points[1][1])
11 my_angle.goto(points[2][0], points[2][1])
12 my_angle.goto(points[0][0], points[0][1])
13 my_angle.end_fill()
14
15
16 def get_mid(p1, p2):
17 return ((p1[0]+p2[0])/2, (p1[1]+p2[1])/2)
18
19
20 def sierpinski(points, degree, my_angle):
21 colormap = ['blue', 'red', 'green', 'yellow',
22 'violet', 'orange', 'white']
23 draw_triangle(points, colormap[degree], my_angle)
24 if degree > 0:
25 sierpinski([points[0],
26 get_mid(points[0], points[1]),
27 get_mid(points[0], points[2])],
28 degree - 1, my_angle)
29 sierpinski([points[1],
30 get_mid(points[0], points[1]),
31 get_mid(points[1], points[2])],
32 degree - 1, my_angle)
33 sierpinski([points[2],
34 get_mid(points[2], points[1]),
35 get_mid(points[0], points[2])],
36 degree - 1, my_angle)
37
38
39 my_turtle = turtle.Turtle()
40 my_win = turtle.Screen()
41 my_points = [[-100, -50], [0, 100], [100, -50]]
42 sierpinski(my_points, 3, my_turtle)
43 my_win.exitonclick()