【问题标题】:python for loop not executing enough timespython for循环没有执行足够的次数
【发布时间】: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。遍历列表的副本非常有效

标签: python loops pygame


【解决方案1】:

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

for crate in Crate.Crates:

for crate in Crate.Crates[:]:

【讨论】:

    猜你喜欢
    • 2018-11-13
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多