递归地画出每一个深度都有颜色的Sierpinski三角形?

2024-05-18 20:54:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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三角形 像这样:

我不知道如何使三角形的颜色在特定的深度变化。
提前谢谢!


Tags: importltsize颜色deforderleftscreen
2条回答

以下是我能想到的最简洁的方法

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) 

我想你已经差不多解决了这个问题。我看到您的递归调用已经在尝试将一个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

可能还有一些其他的小问题需要解决,比如确保你的移动命令不会在正确绘制三角形的某些边后结束重新着色。我已经很久没有画海龟了,所以我得把细节留给你。

相关问题 更多 >

    热门问题