Jacob H wrote:
Hello list...

I'm developing an adventure game in Python (which of course is lots of
fun). One of the features is the ability to save games and restore the
saves later. I'm using the pickle module to implement this. Capturing
current program state and neatly replacing it later is proving to be
trickier than I first imagined, so I'm here to ask for a little
direction from wiser minds than mine!

When my program initializes, each game object is stored in two places
-- the defining module, and in a list in another module. The following
example is not from my actual code, but what happens is the same.

(code contained in "globalstate" module)
all_fruit = []

(code contained in "world" module)
class Apple(object): # the class hierarchy goes back to object, anyway
    def __init__(self):
        self.foo = 23
        self.bar = "something"
        globalstate.all_fruit.append(self)      
apple = Apple()

I enjoy the convenience of being able to refer to the same apple
instance through world.apple or globalstate.all_fruit, the latter
coming into play when I write for loops and so on. When I update the
instance attributes in one place, the changes are reflected in the
other place. But now comes the save and restore game functions, which
again are simplified from my real code:

My understanding of pickle is that it will correctly handle shared references in the saved data. So if you pack all your global dicts into one list and pickle that list, you will get what you want. See code changes below:



(code contained in "saveload" module) import pickle import world
import globalstate
def savegame(path_to_name):
world_data = {}
for attr, value in world.__dict__.items():
# actual code is selective about which attributes # from world it takes -- I'm just keeping this # example simple
world_data[attr] = value
the_whole_shebang = [ world_data, globalstate.all_fruit, globalstate.all_items ]
fp = open(path_to_name, "w")
pickle.dump(the_whole_shebang, fp)
fp.close()
def loadgame(path_to_name):
fp = open(path_to_name, "r")
      the_whole_shebang = pickle.load(fp)
      world_data, globalstate.all_fruit, globalstate.all_items = 
the_whole_shebang
    for attr, value in world_data.items():
        setattr(world, attr, value)
    fp.close()

Kent -- http://mail.python.org/mailman/listinfo/python-list

Reply via email to