无法理解这个递归 turtle python 代码

Unable to understand this recursive turtle python code

这是我第一次提问,希望大家抽空回答。

所以我的目标是使用 turtle 模块编写一个 python 脚本来编写毕达哥拉斯树。

我花了好几天时间,我真的无法超过某个点,所以我在网上寻找帮助。我找到了一个代码,它可以满足我的需求,但代码行很少:

import turtle
t = turtle.Pen()




LIMIT  =11
SCALAR = 0.5 * (2 ** 0.5)


def drawTree(size, depth):

    drawSquare(size)

    if depth + 1 <= LIMIT:

        t.left(90)
        t.forward(size)
        t.right(45)
        drawTree(size * SCALAR, depth + 1)

        t.forward(size * SCALAR)
        t.right(90)
        drawTree(size * SCALAR, depth + 1)

        t.left(90)
        t.backward(size * SCALAR)
        t.left(45)
        t.backward(size)
        t.right(90)



def drawSquare(sideLength):

    for i in range(4):
        t.forward(sideLength)
        t.left(90)



t.up(); t.goto(-100, -200); t.down()
drawTree(170.0, 0)

所以我理解大部分代码,除了 "if" 的第二段和第三段:为什么它们会被执行?如果函数不断重复,它永远不会正常到达那个点! 我确定我在这里遗漏了一些非常简单的东西,我希望你们都能理解我的问题:) 再次感谢!

例如,"depth" 是 10,程序在第一段中调用了 drawTree(size * SCALAR, 10 + 1)。 "depth" 变为 11,IF 为假,程序 returns 返回 drawTree,其中 "depth" 为 10。然后程序执行下一行,第二段的第一行。

同理,程序在第二段调用drawTree(),"depth"没有达到LIMIT,然后returns返回第三段第一行。

drawTree 函数不会一直调用自己,所以最终会执行递归调用 do 之后的语句。当 depth == LIMIT returns 处的递归调用时,控制权返回到上一个调用,其中 depth == LIMIT-1.

这是您的代码的一个稍微修改的版本,其中插入了几个 print 调用以帮助跟踪执行。

我还做了一些其他的小改动。我简化了SCALAR的计算:0.5 * sqrt(2) == sqrt(0.5),只在乌龟真正画正方形的时候才放下笔。我还添加了一个 turtle.mainloop() 调用,以便 window 在绘图完成后保持打开状态。

from __future__ import print_function
import turtle

LIMIT = 3
SCALAR = 0.5 ** 0.5
INDENT = ' ' * 4

def drawTree(size, depth, branch):
    print(INDENT * depth, branch, depth, 'start')

    drawSquare(size)

    if depth + 1 <= LIMIT:

        t.left(90)
        t.forward(size)
        t.right(45)
        drawTree(size * SCALAR, depth + 1, 'left ')

        t.forward(size * SCALAR)
        t.right(90)
        drawTree(size * SCALAR, depth + 1, 'right')

        t.left(90)
        t.backward(size * SCALAR)
        t.left(45)
        t.backward(size)
        t.right(90)

    print(INDENT * depth, branch, depth, 'stop')


def drawSquare(sideLength):
    t.down()
    for i in range(4):
        t.forward(sideLength)
        t.left(90)
    t.up()


t = turtle.Pen()
t.up() 
t.goto(-100, -200)
drawTree(100.0, 0, 'root')

turtle.mainloop()

输出

 root 0 start
     left  1 start
         left  2 start
             left  3 start
             left  3 stop
             right 3 start
             right 3 stop
         left  2 stop
         right 2 start
             left  3 start
             left  3 stop
             right 3 start
             right 3 stop
         right 2 stop
     left  1 stop
     right 1 start
         left  2 start
             left  3 start
             left  3 stop
             right 3 start
             right 3 stop
         left  2 stop
         right 2 start
             left  3 start
             left  3 stop
             right 3 start
             right 3 stop
         right 2 stop
     right 1 stop
 root 0 stop