Saturday, April 23, 2011

Clever Python Hacks Part II - Serialization

Serialization is Magecrawl is pretty good, however it is somewhat verbose. I write out a giant XML tree with all of the attributes of everything, and parse that in on load. It is about 200 lines of core code, along with about 100 for the map and about another 100 for the player.

Here's what my serialization code looks like in python so far:

    SaveVersion = 1
    def __save(self):
        with open( + ".sav", 'wb') as file:
            pickle.dump((self.SaveVersion, self.player, self.level), file)

    def __load(self, filename):
        with open(filename, 'rb') as file:
            fileSaveVersion, player, level = pickle.load(file)
            assert fileSaveVersion == self.SaveVersion
            self.player = player
            self.level = level

I do loose the XML format in exchange for a binary one, but you have to love that simplicity.

1 comment:

Claes Mogren said...

You could try something like if you want to mess with the save files a bit. :-)