I am trying to make a save function in a text adventure. The function must save some variables and parameters for the player.
I have tried to Google it and asking on forums, but I can't make it work.
The entire code is here: http://pastebin.com/8Y3PNnRx
The saving function should save the player = player('Niels', 'Knight, 0, 0, 0, 0, 0, 0, 1)
(line 417) and variables like player.gold
and player.potion
(line 420) at location 'C:\\Users\\XXXXX\\Desktop\\SmallDungeons\\save.dat'
Thank you for your time!
For a minimal example, we build a class in
foo.py
(this is similar to your classplayer
).Now we import it, and add some attributes (this is similar to you adding
player.gold
), and then pickle the class instance. When we're done, we terminate the python interpreter session.Then, we restart the session, and load the pickle.
You'll see that just by saving the class instance, even the added attributes (like f.y) are preserved. This is because
pickle
preserves a reference to your file (where to import it from) as well as any added attributes. You can see this in the pickle string itself.My suggestion is to use
pickle
protocol-1
, as it makes the pickles smaller. You add this flag to any of the places you usedump
ordumps
.You can save with:
and load with