Help with saving and restoring program state

M.E.Farmer mefjr75 at hotmail.com
Tue Jan 25 18:16:32 EST 2005


Jacob H wrote:
> Hello list...
>
> I'm developing an adventure game in Python (which of course is lots
of
> fun).

I am glad you are having fun ,
after all life is so short,
isn't that what it is all about ;)

> 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()
[snip]
Ok here is a guess. (I recently did something similar, maybe this will
help)
If you already knew about this stuff then just ignore me :)

You have defined a class for your objects, which is a nifty
'container'.
The apple class can also keep track of the total amount of apple
instances handed out.
Sometimes it is better to let the objects handle there own state.
Py> class Apple(object):
...     total = 0 # this is a 'class variable' shared by all instances

...     def __init__(self):
...             self.__class__.total += 1
...     	self.foo = 23 # this is an 'instance variable/name'
...      	self.bar = "something"
... apple = Apple()
... apple_two = Apple()
... print apple_two.total
... 2
... apple_three = Apple()
... print apple.total
... 3
... print apple_three.total
... 3
Now you can just pickle them and when you unpickle them as usual.

Also another idea is to use a class instead of a global.
I'll admit it I have a personal distaste for them, but classes work so
well I never miss them.

Py>class Store(object):
...    pass

Now just create an instance and add your attributes.
Py>store = Store()
...store.color = 'red'
...store.height = 5.7
...store.secret = 42
And get them back when needed.
Py>self.SetHieght(store.hieght)

Hth
M.E.Farmer




More information about the Python-list mailing list