网站的建设与应用,打字赚钱,免费做h5的平台,建设部网站资质查询插图工具使用Python内置的turtle模块#xff0c;为什么叫这个turtle乌龟这个名字呢#xff0c;可以这样理解#xff0c;创建一个乌龟#xff0c;乌龟能前进、后退、左转、右转#xff0c;乌龟的尾巴朝下#xff0c;它移动时就会画一条线。并且为了增加乌龟画图的艺术价值…插图工具使用Python内置的turtle模块为什么叫这个turtle乌龟这个名字呢可以这样理解创建一个乌龟乌龟能前进、后退、左转、右转乌龟的尾巴朝下它移动时就会画一条线。并且为了增加乌龟画图的艺术价值可以改变尾巴宽度和尾巴浸入墨水的颜色。
1.递归绘制螺旋
我们让乌龟以line_len长度前进然后向右旋转90°然后缩短line_len长度递归调用draw_spiral函数
importturtle
my_turtleturtle.Turtle()
my_winturtle.Screen()defdraw_spiral(tur, line_len):if line_len 0:
my_turtle.forward(line_len)
my_turtle.right(90)
draw_spiral(tur, line_len- 1)
draw_spiral(my_turtle,100)
my_win.exitonclick()2.递归绘制二叉树
首先绘制branch_length长度的主干枝条然后向右旋转20°递归调用draw_tree绘制主干枝条上的右分支之后再向左旋转40°因为需要抵消右旋转的20°递归调用draw_tree绘制主干枝条的左分支然后再向右旋转20°原路返回。
importturtle
my_treeturtle.Turtle()
my_winturtle.Screen()defdraw_tree(branch_length, t):if branch_length 5:
t.forward(branch_length)
t.right(20)
draw_tree(branch_length-20, t)
t.left(40)
draw_tree(branch_length-20, t)
t.right(20)
t.backward(branch_length)
my_tree.left(90)
my_tree.up()#抬起尾巴
my_tree.backward(200)
my_tree.down()#放下尾巴
my_tree.color(green)
draw_tree(100, my_tree)
my_win.exitonclick()3.绘制谢尔宾斯基三角形
谢尔宾斯基三角形使用了三路递归算法从一个大三角形开始通过连接每一个边的中点将大三角型分为四个三角形然后忽略中间的三角形依次对其余三个三角形执行上述操作。
importturtledefdraw_triangle(points, color, my_angle):
my_angle.fillcolor(color)
my_angle.up()
my_angle.goto(points[0][0], points[0][1])
my_angle.down()
my_angle.begin_fill()
my_angle.goto(points[1][0], points[1][1])
my_angle.goto(points[2][0], points[2][1])
my_angle.goto(points[0][0], points[0][1])
my_angle.end_fill()defget_mid(p1, p2):return ((p1[0]p2[0])/2, (p1[1]p2[1])/2)defsierpinski(points, degree, my_angle):
colormap [blue, red, green, yellow,violet, orange, white]
draw_triangle(points, colormap[degree], my_angle)if degree 0:
sierpinski([points[0],
get_mid(points[0], points[1]),
get_mid(points[0], points[2])],
degree- 1, my_angle)
sierpinski([points[1],
get_mid(points[0], points[1]),
get_mid(points[1], points[2])],
degree- 1, my_angle)
sierpinski([points[2],
get_mid(points[2], points[1]),
get_mid(points[0], points[2])],
degree- 1, my_angle)
my_turtleturtle.Turtle()
my_winturtle.Screen()
my_points [[-100, -50], [0, 100], [100, -50]]
sierpinski(my_points,3, my_turtle)
my_win.exitonclick()