I’m writing a game in Python and I’m looking for some advice on how to redesign my code. Below is the definition of the movement component for a game entity.
The load function takes a PropertyTree object and sets the attributes of self accordingly. The save function does the opposite: based on the attributes of self, a PropertyTree is generated and returned.
class Movement(EntityComponent):
def __init__(self):
# Default values
self.speed = 0
self.acceleration = 0
def load(self, properties):
self.speed = int(properties['Speed'])
self.acceleration = int(properties['Acceleration'])
def save(self):
pt = PropertyTree()
pt['Speed'] = str(self.speed)
pt['Acceleration'] = str(self.acceleration)
return pt
The problem with code is that there is a lot of information duplication going on. First, I duplicate the information that associates keys in the PropertyTree with attributes of self, and I also duplicate the keys themselves ('Speed' and 'Acceleration' strings appear twice). Obviously, there’s a lot of room for mistakes.
How can I refactor this?
As a starting point:
Basically, create a separate save/load system, perhaps in the EntityComponent class. Just provide the list of data for the fields to tell the system how to serialize the current object.
If you aren’t familiar with it, you could also checkout how Python’s pickle module works. I don’t recommend using it for anything beyond trivial cases, but it might give you some ideas.