Search code examples
pythonpygamerestartinstances

Python/Pygame: All Instances Still On Screen After Restart


I'm working on a side-scrolling shooter in Python and Pygame. At the beginning of play, I create a bunch of lists such as enemies[] and shots[]. When the game restarts, I have tried everything I can think of, but all the instances are still on the screen from the last playthrough!

In my restart code I have this...

for item in enemies:
    enemies.remove(item)
    del item
for item in shots:
    shots.remove(item)
    del item

I even have added code after that to reinitialize the list, so:

enemies=[]
shots=[]

But then on the new playthrough everything is still there. Help!


Solution

  • Your main problem is that your lists do exist in more than one context (another method or another function)

    When you do enemies = [] you clear the local variable named "enemies" - but it ceases to point to the previous object, which is used in another funtcion/method (although you don't list the code for that here).

    Your other approach, using for tries to iterate on a list while modifying it - it should (and does) break in unexpected ways.

    Simply do:

    enemies[:] = []
    shots[:] = []
    

    instead: these will change the object currently referenced by those names, not create new objects and use them locally. This way, the contents on whatever other function that uses these lists will be emptied as well.(It is not magic: the [:] slice syntax addresses all elements of the list - from the first to the last, and the attribution makes those elements be replaced by the contents of the empty list: nothing)

    While this will work for now, if you are using enemies, shots and other data structures across several functions/methods, maybe you'd have a cleaner design using a class, holding all your data structures as attributes of that class, and promote your functions to methods (even if otherwise you are not currently making other uses of an Object Oriented design). This way, it would be explicit that you are trying to modify the same objects that are used in other parts of the code.

    Another advice: read the docs, and get familiarized with pygame Groups (and Sprites) - they are quite handy for a clean design, and certainly can perform better anything you are doing with your list objects above (for example, if enemies were a group, you'd just call enemies.empty() in this case)