为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕容708150 2023-06-27 18:35:25
我刚刚开始使用graphics.py,并试图制造一些移动的雨。from graphics import *import random as rrects = []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()我认为我遇到的问题是,添加每个新矩形时都会发生移动更新。谁能帮我想出更好的方法来做到这一点?
查看完整描述

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


查看完整回答
反对 回复 2023-06-27
  • 1 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信