我正在尝试使用递归创建一个程序,它会像这样创建一个H树(这是1阶): H tree
零阶H树只是一个以中心点为中心的H,同一条线的H的所有三条线都是长的 该函数将接收一个乌龟对象,一个表示树顺序的整数,一个中心点和该行的长度。如果顺序大于零,则将在步骤1中绘制的H的四个端点中的每一个中心绘制四个较小阶(阶数-1)和较小长度线(线长度/ 2)的H树。
到目前为止,我有这个:
import turtle
def drawHTree(length, depth):
if depth > 0:
turtle.forward(length / 2)
turtle.right(90)
turtle.forward(length / 2)
turtle.left(90)
drawHTree(length / 2, depth - 1)
turtle.left(90)
turtle.forward(length)
turtle.right(90)
drawHTree(length / 2, depth - 1)
turtle.right(90)
turtle.forward(length / 2)
turtle.right(90)
turtle.forward(length)
turtle.left(90)
turtle.forward(length / 2)
turtle.left(90)
drawHTree(length / 2, depth - 1)
turtle.left(90)
turtle.forward(length)
turtle.right(90)
drawHTree(length / 2, depth - 1)
turtle.right(90)
turtle.forward(length / 2)
turtle.left(90)
turtle.forward(length / 2)
window = turtle.Screen()
drawHTree(200,2)
任何帮助或建议都会很棒!谢谢!
答案 0 :(得分:0)
如果您修复缩进,上面的(原始)代码是正确的。你似乎有关键原则:首先得到它来绘制 H ;确保函数离开乌龟的位置与调用函数时的位置完全相同。以下是我对您的代码的修订,以解决一些样式问题,获取深度/订单号以正确匹配所需的图形并匹配所述的API:
该函数将接收一个乌龟对象,一个表示该对象的整数 树顺序,中心点和线的长度
from turtle import Turtle, Screen
def drawHTree(turtle, order, center, length):
if order < 0:
return
if center is not None:
turtle.up()
turtle.goto(center)
turtle.down()
turtle.forward(length / 2)
turtle.right(90)
turtle.forward(length / 2)
turtle.left(90)
drawHTree(turtle, order - 1, None, length / 2)
turtle.left(90)
turtle.forward(length)
turtle.right(90)
drawHTree(turtle, order - 1, None, length / 2)
turtle.right(90)
turtle.forward(length / 2)
turtle.right(90)
turtle.forward(length)
turtle.left(90)
turtle.forward(length / 2)
turtle.right(90)
drawHTree(turtle, order - 1, None, length / 2)
turtle.right(90)
turtle.forward(length)
turtle.right(90)
drawHTree(turtle, order - 1, None, length / 2)
turtle.right(90)
turtle.forward(length / 2)
turtle.left(90)
turtle.forward(length / 2) # always leave the turtle where you found it!
yertle = Turtle()
drawHTree(yertle, 2, (0, 0), 200)
screen = Screen()
screen.exitonclick()
<强>产生强>