[Tutor] how to save variables after a user quits in python

Steven D'Aprano steve at pearwood.info
Sun Sep 1 02:07:02 CEST 2013


On 01/09/13 07:30, Jack Little wrote:
> I am coding a game and I want the player to be able to quit the game and immediately take off right from where they started from.


That is trickier than it sounds. You have to save the internal state of the game, which means you first have to *identify* the internal state of the game. That means:

* everything about the user: name, health, score, ammunition, treasure, etc.;

* everything about every enemy: whether they are alive or dead, health, ammunition, etc.;

* everything about the internal state of the game: which parts of the game have already been visited, which parts haven't been;

* position of the user;

* anything else I have forgotten.

Once you have identified all of those things, then and only then can you start thinking about the best way to save that information to disk. Depending on what you need to save, you can then decide what module is best suited to that type of data. There are many choices:

http://docs.python.org/2/library/persistence.html
http://docs.python.org/2/library/fileformats.html
http://docs.python.org/2/library/json.html
http://docs.python.org/2/library/xml.html

It is difficult to tell what would be best without knowing what you need to save. Possibly as little as a Windows-style INI file would be enough:

[settings]
key: value


possibly you will need a custom solution that dumps the entire state of the Python interpreter to disk, then later restores it.




-- 
Steven


More information about the Tutor mailing list