sometimes I like to go through every line of code and just change something

Usually it’s for a good reason, to fix something I did earlier for no reason, or maybe for a bad reason that I didn’t understand at the time.

Up to now I’ve been passing objects around by referring to the object itself (I guess this is passing by reference? I think this is what Python does by default). However when you save the game state with yaml (and perhaps with the pickle module too, though I haven’t investigated this), it saves every reference as the actual object data. For example, if you had an attribute on every thing that referenced a map object, that whole map object including its map array would be saved once for each thing.

That in itself wasn’t a problem, as you can clear data that you don’t need to save in your saving routine before you exit the game. However my future plans for the game include a lot of cross-referencing between objects, and I do want to be able to save that state without saving the same object data over and over.

So now instead of passing objects around by reference, each object has a unique game id (the gid). This gets created in a thing’s __init__ method like so:

class Thing(object):
    def __init__(self, name, x, y, properties, *handlers):
        self.gid = id(self)
        while self.gid in game.gids:
            self.gid = self.gid + 1
        game.gids[self.gid] = self

The reason for the while loop is if I create a thing after a game has been saved and reloaded, there is a slim chance that a new gid could match an old gid (as I’m just using Python’s id() function to create the number). If that does happen, I create a new gid until I have a unique one.

Of course this is not as simple as what I was doing before (though saving is actually a little simpler, as I just save a single dictionary of gids and re-use it when I load it back in). Every time I want to look up a thing’s properties I need to look up the thing’s object first in the gids dictionary. Nevertheless I think it’ll pay off in the long run.

Advertisements

No comments yet

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: