1

I am trying to make a game in pygame. The program involves looping through an array of objects, and determining whether they collide with another object. However, when I run the for loop it doesn't execute as many times as there is objects in the list.

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")

The output I get after running this code is the following:

Length of array: 25
loop has executed 23 times

Here is the GitHub repository where you can find the entire code: https://github.com/Mateusz9/game (the code fragment mentioned above is located game/crates/Bomb/crate.py)

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

1

If the method crate.hitByBall() method removes objects from the list, you must iterate over a copy of the list (see also How to remove items from a list while iterating?):

for crate in Crate.Crates:

for crate in Crate.Crates[:]:
Rabbid76
  • 202,892
  • 27
  • 131
  • 174