我在编写一个递归函数时遇到了麻烦,该函数将圆圈绘制到某个“深度”。
import turtle
# These are basic instructions that do not affect the drawing if changed, only the appearance of the entities within the window
turtle.mode('logo')
turtle.speed(1)
turtle.shape('classic')
turtle.title("Circle")
def recCircle(d, r):
if d == 0:
pass
if d == 1:
print("Drawing to the depth of: ", d)
turtle.down()
turtle.circle(r)
turtle.up()
else:
print("Drawing to the depth of: ", d)
turtle.circle(r)
turtle.seth(90)
turtle.down()
recCircle(d - 1, (r / 2)) # Draw the leftmost circle
turtle.seth(360)
turtle.up
turtle.seth(270)
turtle.forward(2 * r)
turtle.down()
recCircle(d - 1, - r / 2) # Draw the rightmost circle
turtle.up()
turtle.seth(360)
turtle.forward(2*r)
def main():
d = 3 #depth of recursion
r = 100 #radius of circle
recCircle(d, r)
turtle.done()
main()
我认为问题出在20号线附近
turtle.circle(r)
我无法弄清楚如何将乌龟归还到相同的位置和方向。
turtle.home或turtle.goto,因为我试图不使用它们
您的代码的具体问题:
turtle.mode('logo')
我理解与North == 0合作的愿望,但在这种设计的情况下,它不是你的优势,我会保持默认方向。这不起作用:
turtle.up
它需要是turtle.up()
。我没有看到你如何在代码中得到你的示例输出,因为它应该抛出一个错误。还行吧:
turtle.seth(270)
只要你假设垂直方向。但总的来说,如果我们想要以任何角度绘制,你就不能使用setheading()
,因为它像turtle.goto()
或turtle.home()
一样绝对。但是这看起来很奇怪:
turtle.seth(360)
与简单的turtle.setheading(0)
。做这样的绘图时的一个关键概念是将乌龟返回到它开始的位置,或者在绘图命令中隐式地返回,或者通过撤消你为乌龟定位所做的任何事情来明确地。下面是我对代码的完整修改:
from turtle import Screen, Turtle
def recCircle(depth, radius):
if depth == 0:
return
print("Drawing to the depth of: ", depth)
turtle.pendown()
turtle.circle(radius)
turtle.penup()
if depth > 1:
length = 11 * radius / 8 # no specific ratio provided, so eyeballed
turtle.left(45)
turtle.forward(length)
turtle.right(45)
recCircle(depth - 1, radius / 2) # Draw the leftmost circle
turtle.backward((2 * length ** 2) ** 0.5)
recCircle(depth - 1, radius / 2) # Draw the rightmost circle
turtle.right(45)
turtle.forward(length)
turtle.left(45)
screen = Screen()
screen.title("Circle")
turtle = Turtle('classic')
turtle.speed('fast')
depth = 3 # depth of recursion
radius = 100 # radius of circle
recCircle(depth, radius)
screen.exitonclick()