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/