[Tutor] Best way to save a D&D-like game's state?

Cameron Simpson cs at cskk.id.au
Fri May 21 21:03:56 EDT 2021


On 21May2021 19:25, boB Stepp <robertvstepp at gmail.com> wrote:
>I am contemplating the design of a D&D-like game where I will
>prototype various ideas I have in Python.  Currently I am pondering
>how such games typically have their state saved.  I imagine there will
>be plenty of custom data types, which represent the state of the game
>world when the players save.  I imagine the data involved could reach
>sizable proportions, depending on how complex and rich the game
>becomes.  The first thing that comes to mind is the pickle module,
>which my understanding is that it can save and restore any custom data
>types done in Python.

Pretty much. There are things that are not pickleable (I gather) and 
ways to accomodate that, either by adding support to the approriate 
class or by choosing to not save the object (eg a live database 
connection).

>Next that comes to mind is JSON, but my
>understanding is that it is limited in what it can save and restore
>without additional work by the programmer.

Yes, but I would use this as the first cut myself. You just need to make 
sure that things can be serialised to JSON and deserialised. I tend to 
give classes an as_dict() method to return a dict containing only things 
JSONable for that instance's state, and would be inclined to make a 
factory method from_dict(d) to instantiate an instance from a dict.

Then saving becomes f.write(json.dumps(obj.as_dict())) and loading 
becomes ObjClass.from_dict(json.load(f)).

If you've got a "root" object representing the whole game state you 
could have its as_dict() method call the as_dict() methods for the 
subsidiary objects, and so on.

This is ok for small things; it scales less well for large data. But 
might be fin for a D&D game.

>Still staying in the
>standard library I suppose an SQLite database could be made to work.

Aye, or step up to something with an ORM like SQLAlchemy. That requires 
you to cast all your db state as ORM objects - then doing things in the 
game causes writes to the db as you go. You need to define a schema and 
so on; it might be easier to start with JSON, get things right, then 
_if_ JSON becomes too cumbersome, then make an ORM from you mature data 
structures. You might want an import/export for JSON still - if nothing 
else it would aid the transition to a db :-)

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list