【问题标题】:Change color based on recursion depth Python Turtle根据递归深度 Python Turtle 改变颜色
【发布时间】:2013-09-18 19:45:24
【问题描述】:

我遇到了一个编码问题。我正在学习递归,到目前为止玩得很开心。我们从使用 python 海龟图形模块的基本海龟绘图开始。我已经把图片代码写下来了,但我也应该根据深度改变海龟笔的颜色。我的教授只是简单地谈到了 mod (%) 来实现这一点,但我不知道从哪里开始,希望能得到一些帮助。提前致谢。我无法添加图片,因为我的代表不够高,但基本上如果您运行代码,它会绘制“S”数字。第一个“S”应该是绿色,第二个两个红色,第三个三个绿色,等等。再次感谢。代码如下:

from turtle import *

def drawzig2(depth,size):
    if depth == 0:
        pass
    elif depth:
        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(4,100)

【问题讨论】:

    标签: python recursion colors modulo turtle-graphics


    【解决方案1】:

    试试这个。

    from turtle import *
    
    colors = ['green', 'red']
    
    def drawzig2(depth,size):
    
        if depth == 0:
            pass
        elif depth:
            pencolor(colors[depth % len(colors)])
            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(4,100)
    

    【讨论】:

    • 嗯,这改变了颜色。但整个事情最后都变成了红色。我将不得不玩它。感谢您的回复!
    【解决方案2】:

    正如您所指出的,@xfx 的解决方案设置然后无意中取消设置颜色,因为它没有正确处理递归颜色。这是一个小的修改,它在进入例程时跟踪当前颜色(也可以计算),然后在退出时恢复它。这样,您就不必担心递归调用对颜色做了什么,他们应该保持原样:

    from turtle import Turtle, Screen
    
    colors = ['green', 'red']
    
    def drawzig2(turtle, depth, size):
    
        if depth == 0:
            return
    
        color = turtle.pencolor()
    
        turtle.pencolor(colors[depth % len(colors)])
    
        turtle.left(90)
        turtle.fd(size / 2)
        turtle.right(90)
        turtle.fd(size)
        turtle.left(45)
    
        drawzig2(turtle, depth - 1, size / 2)
    
        turtle.right(45)
        turtle.bk(size)
        turtle.left(90)
        turtle.bk(size)
        turtle.right(90)
        turtle.bk(size)
        turtle.left(45)
    
        drawzig2(turtle, depth - 1, size / 2)
    
        turtle.right(45)
        turtle.fd(size)
        turtle.left(90)
        turtle.fd(size / 2)
        turtle.right(90)
    
        turtle.pencolor(color)
    
    yertle = Turtle()
    
    drawzig2(yertle, 4, 100)
    
    screen = Screen()
    
    screen.exitonclick()
    

    输出

    【讨论】:

      猜你喜欢
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      相关资源
      最近更新 更多