1 回答
TA贡献1852条经验 获得超1个赞
我的建议是忘记autoflush并update()直到你的算法以最快的速度运行。具体来说,您最终会得到 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()
现在我们只跟踪大约 15 个矩形,而不是数百或数千。只有在优化算法之后,才考虑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()
添加回答
举报