如何解决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[:]:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。