python - 递归地在每个深度绘制带有颜色的谢尔宾斯基三角形?

标签 python recursion turtle-graphics

import turtle
w=turtle.Screen()

def Tri(t, order, size):

    if order==0:
        t.forward(size)
        t.left(120)
        t.forward(size)
        t.left(120)
        t.forward(size)
        t.left(120)

    else:
        t.pencolor('red')
        Tri(t, order-1, size/2, color-1)
        t.fd(size/2)
        t.pencolor('blue')
        Tri(t, order-1, size/2, color-1)
        t.fd(size/2)
        t.lt(120)
        t.fd(size)
        t.lt(120)
        t.fd(size/2)
        t.lt(120)
        t.pencolor('green')
        Tri(t, order-1, size/2,color-1)
        t.rt(120)
        t.fd(size/2)
        t.lt(120)

谁能帮忙解决这个问题?
我想要一个在特定深度有颜色的谢尔宾斯基三角形 像这样:

我不知道如何让三角形颜色在特定深度发生变化。
提前致谢!

最佳答案

我认为您已经差不多解决了这个问题。我看到您的递归调用已经在尝试将 color 值传递给递归的每个较低级别。要让它工作,您需要做的就是将它作为一个额外参数添加到您的函数中,并使您的颜色更改命令以它为零为条件(表明您已经下降到指定级别)。

在类似 python 的伪代码中:

def Tri(t, order, size, color):
    if order == 0:
         # draw a triangle (maybe doing coloring of the sides if color == 0 too?)

    else:
         if color == 0:
             # set first color

         Tri(t, order-1, size/2, color-1)

         if color == 0:
             # set second color

         # move to next position

         Tri(t, order-1, size/2, color-1)

         if color == 0:
             # set third color

         # move to next position

         Tri(t, order-1, size/2, color-1)

         # move to end position

可能还有其他一些小问题需要解决,例如确保您的移动命令不会在正确绘制三角形后最终重新着色它们的某些边缘。好久没做 turtle 图了,细节留给大家吧。

关于python - 递归地在每个深度绘制带有颜色的谢尔宾斯基三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13666549/

相关文章:

python - Tox 失败,因为 setup.py 找不到 requirements.txt

python - 使用 turtle 在python中用颜色填充矩形

Python。学习 turtle graphics

python - 如何编写一个Python程序来读取输入并将其转换为带有 turtle 图形的预定义14段字符?

Python:在二维数组中查找所有可能的唯一双索引组合

python - 如何绘制多个国家的时间序列?

python - 如何将 MP4 文件转换为文本文件并返回

haskell - 使用 cabal 管理两个相互依赖的库

python - 递归计算链表中的节点数

sql - 将平面表解析为树的最有效/优雅的方法是什么?