如何在递归函数中返回海龟的原点

2024-10-01 17:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在编写一个递归函数时遇到了麻烦,它将圆绘制到一定的“深度”。在

  • 例如,在深度1处,程序应该绘制如下:depth 1
  • 在深度2,程序应该画出这个:depth 2
  • 在深度3,程序应该画出这个:depth 3
  • 作为参考,我的程序画了这个:myTurtleDrawing
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号线附近

^{pr2}$

我不知道如何让乌龟回到原来的位置和方向。在

在乌龟。家或者乌龟。去因为我不想用那些


Tags: ofthe程序ifdef绘制downprint
1条回答
网友
1楼 · 发布于 2024-10-01 17:31:25

代码的特定问题:

turtle.mode('logo')

我理解使用North==0的愿望,但在这种设计中,这对您不利,我将使用默认方向。这行不通:

^{pr2}$

它必须是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()

enter image description here

相关问题 更多 >

    热门问题