python - 如何在 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
现在,我该如何解决这个问题,而不会在每次尝试生成新矩形时都消失?
解决方案
创建一个矩形列表:
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)
# [...]
推荐阅读
- wpf - WPF 将参数传递给内部转换器的样式
- python - azure 函数连接到 3rd 方 API 在部署时不起作用
- r - R:df 从几天到几周
- inno-setup - InnoSetup 如何处理 INI 文件编码
- python - 将函数应用于字典值不起作用
- mysql - MYSQL 你如何区分它的数量
- c# - WinForm ListBox - 如何显示对象中的文本?
- javascript - ngFor 正在延迟显示,直到下一个项目被推送到数组
- flutter - Flutter:如何使用 flutter_local_notification 将模型从 API 发送到其他屏幕
- javascript - 用Javascript中的字符串和数字数组减少多维