0

任何人都知道如何根据此代码的递归深度更改海龟的笔颜色?我想不通。

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)
4

1 回答 1

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)

它开始产生的屏幕截图:

在此处输入图像描述

编辑:根据martineu在评论中的大量反馈,我修改了解决方案,使其对OP更容易理解并包括日志记录,运行时应输出如下:

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
于 2013-09-15T01:24:51.360 回答