The game state is defined by the following items:
* All Containers in the GameMap
* The Things in those Containers
* Any Containers in those Things (e.g. inventory, equipment)
* Any Things in those Containers, etc. etc. etc.
In other words, we need to be able to recursively serialize all of the Things in the game, as well as their relationships (i.e. the Containers). Note that serializing a Thing also includes serializing its Stats and any relevant Procs, but that's comparatively straightforward, so I'm ignoring it for the moment.
It seems to me that the simplest way to handle this is to have a class that is responsible for martialling all of these serializations. The basic flow would look like this:
Code:
1) The user selects the "Save" command.
2) This calls GameMap.save()
In GameMap class:
def save(self, filename):
serializer = gameSerializer.GameSerializer()
for container in self.idToContainerMap.values():
serializer.addContainer(container)
serializer.writeFile(filename)
In GameSerializer class:
def addContainer(self, container):
if container.id in self.idToContainerContents:
# Already have this container.
return
self.idToContainerContents[container.id] = []
for thing in container.contents:
self.idToContainerContents[container.id].append(thing.id)
self.addThing(thing)
def addThing(self, thing):
if thing.id in self.idToThingSerialization:
# Already serialized this Thing.
return
self.idToThingSerialization[thing.id] = thing.getSerialization()
self.idToThingContainers[thing.id] = []
for container in thing.getContainers():
self.addContainer(container)
In other words, we build up a mapping of Container IDs to Thing IDs ("This Container holds these Things"), a mapping of Thing IDs to lists of Container IDs ("This Thing has these Containers"), and a mapping of Thing IDs to shallow serializations of Things ("shallow" meaning "can be used to reconstruct the Thing, but not the containers in the Thing").
The generated file then contains all of the Container <-> Thing relationships, as well as the Thing serializations, all appropriately labeled. When we want to recreate the game state, first we create all of the necessary Containers; then, as we deserialize Things, we can put them into Containers, and put Containers into them, as appropriate.
There are a lot of details I'm glossing over here; in particular, Proc serialization and deserialization is going to be moderately tricky. That should all be handled as a subset of Thing [de]serialization though (i.e. Procs don't ever exist independent of Things). The above-described system ought to be enough to get us working, though.
Thoughts?
I certainly agree that bows, crossbows, and slings could be more differentiated, but if possible I'd like to put that off for a bit.
Leave a comment: