Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python text game: how to make a save feature?

Tags:

python

save

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.

like image 936
Nick56x Avatar asked Sep 04 '13 05:09

Nick56x


1 Answers

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.

like image 104
fjarri Avatar answered Sep 30 '22 17:09

fjarri