1

In my game I am trying to make with pygame i have my player able to shoot "bullets" created from instances of a class in an array (named "shots"), but when i try to delete them, the program crashes. Below is my code, what am I doing wrong that makes it crash?

for i in range(len(shots)):
    shots[i].shoot()
    shots[i].drawBullet()

    if shots[i].x > swidth or shots[i].x < 0:
        shots.pop(i)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
nth
  • 93
  • 6
  • [This](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) should solve your problem. – Asocia May 14 '20 at 21:19

1 Answers1

1

The issue is, that you traverse the list while you remove (pop) items. When you remove the last item of the list, then index of the item is still contained in the range range(len(shots)), but the access to shots[i] will fail.
A simple fix would be to traverse the list in reverse order. Reverse the range by reversed:

for i in reversed(range(len(shots))):
    shots[i].shoot()
    shots[i].drawBullet()

    if shots[i].x > swidth or shots[i].x < 0:
        shots.pop(i)

Another option would be to iterate a shallow copy of the list ([:]) and to remove elements from the original list. See Data Structures:

for shot in shots[:]:
    shot.shoot()
    shot.drawBullet()

    if shot.x > swidth or shot.x < 0:
        shots.remove(shot)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174