我只是一个初学者,我试图通过制作一个递归函数来使用python的乌龟制作一个分形树。我认为我到目前为止已经有了这个功能,它使得我的分形的整个左侧,但它没有做出正确的一面。我该如何解决这个问题?任何和所有的建议将不胜感激!
def svTree( trunkLength, levels ):
""" uses the turtle drawing functions to return a tree with a specified number of levels
input: two integers, trunkLength and levels
"""
newtrunkLength = trunkLength *.5
forward(trunkLength)
if levels ==1:
penup()
else:
left(45)
forward(trunkLength * 0.5)
backward(trunkLength * 0.5)
right(90)
forward(trunkLength * 0.5)
backward(trunkLength * 0.5)
left(90)
return svTree(newtrunkLength,levels-1)
答案 0 :(得分:1)
在递归左侧分支之前保存乌龟的位置,然后重置乌龟并绘制右侧分支:
def svTree(length, level):
if level == 1:
return
#draw level's trunk
down()
forward(length)
up()
#save turtle position and heading
pos = position()
hdg = heading()
#draw left branch
left(45)
svTree(length / 2, level - 1)
#restore turtle position and heading
setposition(pos)
setheading(hdg)
#draw right branch
right(45)
svTree(length / 2, level - 1)
如果您不想在每次方法调用时保存位置和标题,您还可以确保乌龟光标在每个方法调用开始时的结尾和标题处结束。
def svTree(length, level):
if level == 1:
return
#draw level's trunk
down()
forward(length)
up()
#draw left branch
left(45)
svTree(length/2, level-1)
#draw right branch
right(90)
svTree(length/2, level-1)
#return cursor to state when function called
left(45)
backward(length)