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)

3
  • What does hitByBall do? Does it remove objects for the list? If so, iterate a copy tf the list for crate in Crate.Crates[:]: Commented Apr 17, 2021 at 12:39
  • Try printing length of array after for loop Commented Apr 17, 2021 at 12:40
  • thanks @Rabbid76. Iterating over the copy of the list works perfectly Commented Apr 17, 2021 at 12:51

1 Answer 1

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[:]:
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.