根据递归深度更改乌龟的笔迹

时间:2013-09-14 23:33:27

标签: python recursion colors turtle-graphics

任何人都知道如何根据此代码的递归深度更改乌龟的笔迹?我无法理解。

def drawzig2(depth,size):
 if depth == 0:
    pass
 else:
    left(90)
    fd(size/2)
    right(90)
    fd(size)
    left(45)        
    drawzig2(depth-1,size/2)       
    right(45)
    fd(-size)
    left(90)
    fd(-size)
    right(90)
    fd(-size)
    left(45)        
    drawzig2(depth-1,size/2)        
    right(45)
    fd(size)
    left(90)
    fd(size/2)
    right(90)

drawzig2(3,100)

1 个答案:

答案 0 :(得分:0)

以下是代码的修改版本,它根据深度改变颜色:

import turtle
import logging

colors = ['green', 'yellow', 'blue']

def drawzig2(depth, size):
    if depth == 0:
        pass
    else:
        turtle.pen(pencolor=colors[depth % len(colors)])
        logging.error(
            "Depth: " + str(depth) + " " +
            "Color: " + colors[depth % len(colors)])
        turtle.left(90)
        turtle.fd(size / 2)
        turtle.right(90)
        turtle.fd(size)
        turtle.left(45)
        drawzig2((depth - 1),(size / 2))
        turtle.right(45)
        turtle.fd(-size)
        turtle.left(90)
        turtle.fd(-size)
        turtle.right(90)
        turtle.fd(-size)
        turtle.left(45)
        drawzig2((depth - 1), (size / 2))
        turtle.right(45)
        turtle.fd(size)
        turtle.left(90)
        turtle.fd(size / 2)
        turtle.right(90)

drawzig2(3,100)

它开始制作的截图:

enter image description here

编辑:根据评论中来自martineu的强烈反馈,我修改了解决方案,以便更容易理解OP并包含日志记录,运行时应输出如下: / p>

Depth: 3 Color: green
Depth: 2 Color: blue
Depth: 1 Color: yellow
Depth: 1 Color: yellow
Depth: 2 Color: blue
Depth: 1 Color: yellow
Depth: 1 Color: yellow