saving part one (a roguelike in Python #7)

I’ve been having a go with saving and loading in the Python demo. It may seem a little silly to do this before I have a game or for that matter, any content at all, but I’m following a bit of advice I read on rgrd and I’m glad I’m doing it…especially with loading the save state back in, it makes you think of how you structure the data to be saved in the program in the first place.

Luckily this first try is rather simple given Python’s pickle module. To save on exit I put this in the main loop:

            if player.input.key.vk == libtcod.KEY_ESCAPE:
                file = open('centaur.sav', 'w')
                file2 = open('player.sav', 'w')
                pickle.dump(, file)
                pickle.dump(player.thing, file2)

This saves the level data and the player object to two separate files, then closes the game — though doesn’t actually change at all currently, the x,y position of the player object does change, and saving it allows you to start the demo, move the player, then restart the demo with the player in the new spot.

For a quick test I just did this in place of the creation of the player thing object;

        if os.path.isfile('player.sav'):
            print 'player file found'
            file = open('player.sav', 'r')
            self.thing = pickle.load(file)
            self.thing = Actor('player', 26, 16, Fov)

Note that I needed to add the player object back to the list — otherwise, the player object brain’s update method will never be called (nor its field-of-view handler), as you aren’t adding it to the list by instancing the Actor class! Not doing this at first was a strange sight, as I moved and changed the player’s position without the screen updating.

As I mentioned, this test was a good thing to do early, as now I’m looking at how to arrange these saving and loading methods in the code. It seems like it would be a good idea to consolidate the saving and especially the loading as much as possible. Furthermore I’m not completely sold on the pickle module, as it creates files that look like this (in ASCII mode):


I’m envisioning a case where I have a save file and I want to examine it without too much fuss. A simple text format would be much more readable. On the other hand, the pickle module is dead simple, and it is readable (and unpickle-able, of course).


No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: