turtle-graphics 有没有办法让我们改变填充颜色?

Is there a way turtle-graphics lets us change the fill color?

我想用这个分形代码做一个风景,我需要填充颜色每秒都在变化。我尝试了一个 for 循环来重绘整个东西,但这会干扰我的代码中不应重复的其他部分

有没有一种方法可以让 turtle-graphics 改变填充颜​​色?

from turtle import *
from time import sleep, perf_counter
tracer(0)
def hilbert(size, level, parity):
    if level == 0:
        return
    left(parity * 90)
    hilbert(size, level - 1, -parity)
    forward(size)
    right(parity * 90)
    hilbert(size, level - 1, parity)
    forward(size)
    hilbert(size, level - 1, parity)
    right(parity * 90)
    forward(size)
    hilbert(size, level - 1, -parity)
    left(parity * 90)
def fractal(dist, depth, dir):
    if depth < 1:
        fd(dist)
        return
    fractal(dist / 3, depth - 1, dir)
    lt(60 * dir)
    fractal(dist / 3, depth - 1, dir)
    rt(120 * dir)
    fractal(dist / 3, depth - 1, dir)
    lt(60 * dir)
    fractal(dist / 3, depth - 1, dir)
reset()
speed(0)
ht()
pu()
size = 6

setpos(-33*size, -32*size)
pd()
fillcolor("chocolate")
begin_fill()
fd(size)

hilbert(size, 6, 1)

fd(size)
for i in range(3):
    lt(90)
    fd(size*(64+i%2))
pu()
for i in range(2):
    fd(size)
    rt(90)
pd()
for i in range(4):
    fd(size*(66+i%2))
    rt(90)
end_fill()
update()

输出:

将绘图代码封装在函数中,并添加一个计时器,在幕后我们可以每秒重绘一次,并使用不同的背景颜色。这使您可以在背景颜色更改时自由地使用乌龟绘制其他东西:

from turtle import Screen, Turtle
from itertools import cycle

COLORS = ['chocolate', 'tomato', 'plum', 'salmon', 'bisque', 'lime', 'olive', 'wheat']

size = 6

def hilbert(t, size, level, parity=1):
    if level == 0:
        return

    t.left(parity * 90)
    hilbert(t, size, level - 1, -parity)
    t.forward(size)
    t.right(parity * 90)
    hilbert(t, size, level - 1, parity)
    t.forward(size)
    hilbert(t, size, level - 1, parity)
    t.right(parity * 90)
    t.forward(size)
    hilbert(t, size, level - 1, -parity)
    t.left(parity * 90)

def filled_hilbert(t, color):
    t.clear()
    t.setheading(0)

    t.penup()
    t.setposition(-33 * size, -32 * size)
    t.pendown()

    t.fillcolor(next(color))
    t.begin_fill()

    t.forward(size)

    hilbert(t, size, 6, 1)

    t.forward(size)

    for i in range(3):
        t.left(90)
        t.forward(size * (64 + i % 2))

    t.penup()

    for i in range(2):
        t.forward(size)
        t.right(90)

    t.pendown()

    for i in range(4):
        t.forward(size * (66 + i % 2))
        t.right(90)

    t.end_fill()

    screen.update()

    screen.ontimer(lambda: filled_hilbert(t, color), 1000)

screen = Screen()
screen.tracer(0)

turtle = Turtle()
turtle.hideturtle()

filled_hilbert(turtle, cycle(COLORS))

screen.mainloop()

但是,任何正在绘图的乌龟都会出现在前面,因此除非您将前景绘图与其同步,否则此图像不一定会留在背景中。