Search code examples
pythonpython-3.xpygame

Pygame pop() class crashing


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)

Solution

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