I am in the process of making a text based game with Python, and I have the general idea down. But I am going to make the game in depth to the point where, it will take longer than one sitting to finish it. So I want to be able to make the game to where, on exit, it will save a list of variables (player health, gold, room place, etc) to a file. Then if the player wants to load the file, they go to the load menu, and it will load the file.
I am currently using version 2.7.5 of Python, and am on Windows.
If I understand the question correctly, you are asking about a way to serialize objects. The easiest way is to use the standard module pickle:
import pickle
player = Player(...)
level_state = Level(...)
# saving
with open('savefile.dat', 'wb') as f:
pickle.dump([player, level_state], f, protocol=2)
# loading
with open('savefile.dat', 'rb') as f:
player, level_state = pickle.load(f)
Standard Python objects and simple classes with any level of nesting can be stored this way. If your classes have some nontrivial constructors it may be necessary to hint pickle
at what actually needs saving by using the corresponding protocol.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With