在每个深度递归绘制Sierpinski三角形的颜色?

时间:2012-12-02 05:01:13

标签: 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)

任何人都可以帮忙解决这个问题吗? 我想要一个在特定深度具有颜色的sierpinski三角形 像这样:

我不知道如何在特定深度处改变三角形颜色 提前致谢!

2 个答案:

答案 0 :(得分:2)

我认为你已经解决了这个问题。我看到你的递归调用已经尝试将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图片已经很久了,所以我不得不把细节留给你。

答案 1 :(得分:0)

这是我能够提出的最简洁的方式

angles = [0, 120, 240]
colors = ["red", "blue", "magenta"]

def draw_equi_triang(t, size):
    for i in range(3):
        t.forward(size)
        t.left(120)

def shift_turtle(t, size, angle):

    # moves turtle to correct location to begin next triangle

    t.left(angle)
    t.penup()
    t.forward(size)
    t.pendown()
    t.right(angle)

def sierpinski(t, order, size, colorChangeDepth = -1):

    # draw an equilateral triangle at order 0

    if order == 0:
        draw_equi_triang(t, size)

    # otherwise, test if colorChangeDepth == 0 and when it does change the color

    else:
        if colorChangeDepth == 0:
            # get index of angles
            for (ind, angle) in enumerate (angles):
                t.color(colors[ind])
                sierpinski(t, order-1, size/2, colorChangeDepth-1)
                shift_turtle(t, size/2, angle)
        # if colorChangeDepth does not == 0 yet
        else:
            for angle in angles:
                sierpinksi(t, order-1, size/2, colorChangeDepth-1)
                shift_turtle(t, size/2, angle) 
相关问题