vido.ardes vido.ardes - 4 months ago 22
Python Question

How do I reset a python script (clear all objects from memory)?

I've built a small text RPG in python, which has an end state where you run out of health and takes you back to the main menu. The problem is when you start a new game, all of the objects are still in the previous state (enemies dead, loot collected etc).

Is there anyway of effectively resetting it, as if I'd killed and restarted the script without actually doing so?

EDIT: I was wondering if there was a generic way of reinitialising, but if it helps my project is here


The straight forward way to do this is to have an object representing your Game state:

game = GameEngineState()

and then the interactions / state are kept within that object. This object is created when the player presses start, and is recreated when the user starts a new game:

if start:
    game = GameEngineState()

That way there is no global state regarding how the current game is progressing, and you can implement saving/loading by serializing the active game object.

If you need to have explicit deallocation routines (for example resources loaded to the GPU or libraries that require a notification when things are shutting down), you can implement a close() method in your game state that you call before restarting the game, or even better, use with to let Python handle it for you when the object goes out of scope.

with GameEngine() as game:
    # do stuff to game / read inputs / change state / let the player play..