首页 > 解决方案 > 如何在 Pygame 中动态生成形状?

问题描述

我正在尝试生成多个矩形,它们在屏幕上平移,任意两个连续矩形之间的间距不同。

这是代码片段-

win = pygame.display.set_mode((500, 500)) #canvas size is 500x500

width = 40
height = 60
x = 500 - width
y = 500 - height
vel = 5

state = True
while(state):
   pygame.time.delay(50)
   x -= vel
   pygame.draw.rect(win, (0, 0, 255), (x, y, width, height))
   pygame.display.update()

#I have not included the pygame exit code

现在,我该如何解决这个问题,而不会在每次尝试生成新矩形时都消失?

标签: pythonpygame

解决方案


创建一个矩形列表:

rect_list = []

当您想添加一个新矩形时,将一个新pygame.Rect对象附加到列表中:

rect_list.append(pygame.Rect(x, y, width, height))

在主应用程序循环中更改矩形的位置并循环绘制矩形:

state = True
while state:
    # [...]

    for rect_obj in rect_list:
        rect_obj.x -= vel
        pygame.draw.rect(win, (0, 0, 255), rect_obj)

    # [...]

推荐阅读