0
我有一個程序,它使用ontimer
函數將Turtle圖形停車燈中的顏色從綠色變爲黃色再變回紅色並再次變回。這裏是一個完整的程序:如何使用hide/showturtle在Python中創建一個stoplight機器?
import turtle
turtle.setup(400,500)
wn = turtle.Screen()
wn.title("Tess becomes a traffic light!")
wn.bgcolor("lightgreen")
tess = turtle.Turtle()
def draw_housing():
""" Draw a nice housing to hold the traffic lights """
tess.pensize(3)
tess.color("black", "darkgrey")
tess.begin_fill()
tess.forward(80)
tess.left(90)
tess.forward(200)
tess.circle(40, 180)
tess.forward(200)
tess.left(90)
tess.end_fill()
draw_housing()
tess.penup()
tess.forward(40)
tess.left(90)
tess.forward(50)
tess.shape("circle")
tess.shapesize(3)
tess.fillcolor("green")
state_num = 0
def advance_state_machine():
global state_num
wn.ontimer(advance_state_machine, 2000)
if state_num == 0:
tess.forward(70)
tess.fillcolor("orange")
state_num = 1
elif state_num == 1:
tess.forward(70)
tess.fillcolor("red")
state_num = 2
else:
tess.back(140)
tess.fillcolor("green")
state_num = 0
advance_state_machine()
wn.mainloop()
但是現在,我想基本上是做同樣的事情,但是通過使用hideturtle
和showturtle
。我已經完全擺脫了advance_state_machine
函數。取而代之的是這樣的,draw_housing()
後馬上開始:
tess.penup()
tess.hideturtle()
green = turtle.Turtle()
green.pu()
green.forward(40)
green.left(90)
green.forward(50)
green.shape("circle")
green.shapesize(3)
green.fillcolor("green")
yellow = turtle.Turtle()
yellow.pu()
yellow.forward(40)
yellow.left(90)
yellow.forward(50)
yellow.shape("circle")
yellow.shapesize(3)
yellow.forward(70)
yellow.fillcolor("orange")
red = turtle.Turtle()
red.pu()
red.forward(40)
red.left(90)
red.forward(190)
red.shape("circle")
red.shapesize(3)
red.fillcolor("red")
Esentially,我試圖創造一種循環隱藏和顯示每個單獨的龜模仿我的第一個程序。我可以用手寫代碼來隱藏每個烏龜並將其展示在無限遠的計時器上,但我寧願它自己繼續!另外,有沒有簡單的方法可以讓一隻燈「開」,另外兩隻是「關」,表示爲變暗/變灰的顏色,而不是那隻烏龜完全消失?預先感謝您的幫助/建議。