【发布时间】:2021-04-17 12:36:17
【问题描述】:
我正在尝试在 pygame 中制作游戏。该程序涉及遍历对象数组,并确定它们是否与另一个对象发生碰撞。 但是,当我运行 for 循环时,它的执行次数不如列表中的对象多。
print(f"Length of array: {str(len(Crate.Crates))}")
counter = 0
for crate in Crate.Crates:
counter += 1
if crate.colide and crate.rect.colliderect(self.explosionRect):
crate.hitByBall()
print(f"loop has executed {str(counter)} times")
运行此代码后得到的输出如下:
Length of array: 25
loop has executed 23 times
这里是 GitHub 存储库,您可以在其中找到完整代码:https://github.com/Mateusz9/game (上面提到的代码片段位于game/crates/Bomb/crate.py)
【问题讨论】:
-
hitByBall是做什么的?它会删除列表的对象吗?如果是这样,迭代一个副本 tf 列表for crate in Crate.Crates[:]: -
在for循环后尝试打印数组长度
-
感谢@Rabbid76。遍历列表的副本非常有效