0
我寫了一個程序,它從列表中拉出一個隨機的座標/顏色集,並在圖形窗口中繪製一個圓。我希望它一旦至少繪製了一次每個座標/顏色集合,就立即到停止繪製圓圈。我還想記錄9個可能的座標/顏色集合中每一個的使用次數。我已經初始化了一個計數器,count = [0, 0, 0, 0, 0, 0, 0, 0, 0]
,每次繪製新的圓時我都要打印一個計數器,並附加每個狀態的使用次數。如何做到這一點的提示?Python中的計數器列表
例輸出外殼:
count = [1, 0, 0, 0, 0, 0, 0, 0, 0]
count = [2, 0, 0, 0, 0, 0, 0, 0, 0]
count = [2, 1, 0, 0, 0, 0, 0, 0, 0]
count = [2, 1, 0, 0, 1, 0, 0, 0, 0]
count = [2, 1, 1, 0, 1, 0, 0, 0, 0]
count = [2, 1, 1, 0, 1, 0, 0, 0, 1]
count = [2, 1, 1, 0, 1, 0, 1, 0, 1]
count = [2, 1, 1, 0, 1, 0, 1, 1, 1]
count = [2, 1, 1, 1, 1, 0, 1, 1, 1]
count = [2, 1, 1, 1, 1, 1, 1, 1, 1]
請和謝謝你在前進!
import random, turtle
wn = turtle.Screen()
alex = turtle.Turtle()
alex.pensize(3)
alex.color("black")
def turtle_draw():
'''draws a circle with given coordinates and in a
given color, prints a counter.'''
color, place = random_state_finder()
alex.pu()
alex.goto(place)
alex.shape("circle")
alex.shapesize(3)
alex.fillcolor(color)
count = [0, 0, 0, 0, 0, 0, 0, 0, 0]
wn.ontimer(turtle_draw, 250)
def random_state_finder():
'''randomly generates a state number from 0 to 8
and assigns the state's data to color and place.'''
rng = random.Random()
state_num = rng.randrange(0, 8)
L = [((-150, 150), "red"), ((0, 150), "orange"),
((150, 150), "yellow"), ((-150, 0), "green"),
((0, 0), "blue"), ((150, 0), "violet"),
((-150, -150), "cyan"), ((0, -150), "magenta"),
((-150, -150), "purple")]
random_state = L[state_num]
color = random_state[1]
place = random_state[0]
return color, place
turtle_draw()
對於初學者來說,每次選擇狀態都需要更新'count';要做到這一點,它不能只在本地定義爲'turtle_draw'。 –