1 回答

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個贊
我的建議是忘記autoflush并update()直到你的算法以最快的速度運(yùn)行。具體來說,您最終會得到 3000 個要更新的矩形,盡管屏幕上一次最多不會超過 15 個。你最好去掉從底部掉下來的矩形:
from random import seed, randint, choice
from graphics import *
WIDTH, HEIGHT = 800, 800
colorList = [
color_rgb(255, 170, 204),
color_rgb(255, 187, 204),
color_rgb(255, 204, 204),
color_rgb(255, 221, 204),
color_rgb(255, 238, 204)
]
def main():
seed()
win = GraphWin("Random Squares", WIDTH, HEIGHT)
win.setBackground("black")
rects = []
for _ in range(3000):
for rect in list(rects): # iterate over a shallow copy
rect.move(0, randint(10, 100))
if rect.getP1().getY() > HEIGHT:
rect.undraw()
rects.remove(rect)
x1 = randint(0, WIDTH - 5)
y1 = randint(0, 10)
rect = Rectangle(Point(x1, y1), Point(x1 + 5, y1 + 20))
rect.setFill(choice(colorList))
rect.draw(win)
rects.append(rect)
win.getMouse()
win.close()
if __name__ == '__main__':
main()
現(xiàn)在我們只跟蹤大約 15 個矩形,而不是數(shù)百或數(shù)千。只有在優(yōu)化算法之后,才考慮autoflush性能update()是否不符合您的喜好:
def main():
seed()
win = GraphWin("Random Squares", WIDTH, HEIGHT, autoflush=False)
win.setBackground("black")
rects = []
for _ in range(3000):
for rect in list(rects): # iterate over a shallow copy
rect.move(0, randint(10, 100))
if rect.getP1().getY() > HEIGHT:
rect.undraw()
rects.remove(rect)
x1 = randint(0, WIDTH - 5)
y1 = randint(0, 10)
rect = Rectangle(Point(x1, y1), Point(x1 + 5, y1 + 20))
rect.setFill(choice(colorList))
rect.draw(win)
update()
rects.append(rect)
win.getMouse()
win.close()
添加回答
舉報