python for循环执行次数不够

问题描述

我正在尝试在 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

解决方法

如果方法 crate.hitByBall() 方法从列表中删除对象,则必须迭代列表的副本(另请参阅 How to remove items from a list while iterating?):

for crate in Crate.Crates:

for crate in Crate.Crates[:]: