【问题标题】:Change turtle's pencolor based on recursion depth根据递归深度更改海龟的笔颜色
【发布时间】:2013-09-19 09:18:51
【问题描述】:

有人知道如何根据这段代码的递归深度来改变海龟的笔颜色吗?我想不通。

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)

【问题讨论】:

  • 也许您应该说明您正在尝试做什么以及您正在使用什么库。您当前的问题非常不清楚
  • 由于 depth 是传递给函数的参数,因此请根据该参数选择颜色。

标签: python recursion colors turtle-graphics


【解决方案1】:

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

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 在 cmets 中的出色反馈,我修改了解决方案,使其对 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

【讨论】:

  • 当我尝试获取列表索引超出范围错误时。我完全复制了它。
  • 在调用 logging 时尝试使用数组的长度和深度值来调试哪个不是您期望的那样。在上面的示例中,数组中有 5 种颜色,因此可接受的值为 0,1,2,3 或 4
  • Leon: colors[0](例如blue)永远不会被使用。 @user2723477:使用此代码,初始调用 drawzig2() 时深度参数的最大值为 4。
  • 好点@martineau,我已经调整了代码,使 OP 的代码更加丰富多彩,并从数组中删除了额外的元素
  • 并不是colors 列表中的项目太多,只是pencolor=colors[depth] 永远不会在depth == 0 被执行——所以即使你改变了colors[0] 也永远不会执行被选中。我建议您使用 pencolor=colors[depth % len(colors}] 之类的东西,这也可以避免索引超出范围错误。
猜你喜欢
  • 2013-09-18
  • 1970-01-01
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
  • 2013-12-17
  • 2017-06-06
相关资源
最近更新 更多