如何让这段graphics.py代码中的动作更流畅?

How to make the movement in this graphics.py code more fluent?

我刚开始使用 graphics.py 并试图制造一些流动的雨。

from graphics import *
import random as r

rects = []
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():
    r.seed()
    win = GraphWin("Random Squares", 800, 800)
    win.setBackground("black")
    for i in range(3000):
        x1 = r.randint(0,800)
        x2 = r.randint(0,10)
        y1 = x1+5
        y2 = x2+20
        var = Rectangle(Point(x1,x2), Point(y1,y2))
        rects.append(var)
        rects[i].setFill(r.choice(colorList))
        rects[i].draw(win)
        for i in range(len(rects)):
            rects[i].move(0,r.randint(10,100))
            update(10000)
    win.getMouse()
    win.close()

if __name__ == '__main__':
    main()

我认为我遇到的问题是在添加每个新矩形时都会发生移动更新。 谁能帮我想出一个更好的方法来做到这一点?

我的建议是忘记 autoflushupdate(),直到您的算法达到最快速度 运行。具体来说,您最终会得到 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 个矩形而不是数百或数千个。只有在优化算法之后,如果性能不符合您的喜好,请考虑 autoflushupdate()

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()