473,700 Members | 2,539 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with saving and restoring program state

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 "globalstat e" 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(s elf)
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:

(code contained in "saveload" module)
import pickle
import world
def savegame(path_t o_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
fp = open(path_to_na me, "w")
pickle.dump(wor ld_data, fp)
fp.close()

def loadgame(path_t o_name):
fp = open(path_to_na me, "r")
world_data = pickle.load(fp)
for attr, value in world_data.item s():
setattr(world, attr, value)
fp.close()

The problem is that the game objects only get overwritten in the world
module. The instances in the globalstate.all _fruit list remain
unchanged, which is not the behaviour I want. I started to write code
to get around this. I figured that with each loadgame call, I could
reset all the lists in globalstate to empty, then reappend each game
object to the appropriate list. But this possibility got complicated
fast, because all game objects belong to more than one list. My apple
instance alone would belong to globalstate.all _things,
globalstate.all _fruit, globalstate.all _items, and perhaps others. Some
of the game objects contained in these lists don't need to be a part
of capturing program state in the first place! But I'm stuck, because
unpickling (so far as I understand it) creates a brand new instance
that doesn't know it used to have references to itself in the
globalstate lists.

Any advice out there? I'm looking for a clean, elegant way to
overwrite the same class instance in two arbitrary places at once.
Perhaps the example code I've provided isn't even the best way of
saving and restoring program state. Perhaps I can easily update my
globalstate lists and I'm just overlooking the simple way. Or perhaps
the solution lies in abandoning the concepts of referencing my game
objects through module attributes and lists. I'm open to any
suggestions.

Thanks in advance for any help!

Jacob
Jul 18 '05 #1
4 5451
Take a look at Zope. The ZODB is a highly optimized object
database that handles the pickling, loading, saving, etc. of
Python objects for restoring program state. A ZODB beginner's
tutorial is available here:

http://www.h7.dion.ne.jp/~harm/ZODB-Tutorial.py

Other info at:

http://zope.org/Members/adytumsoluti...LoveZODB_PartI
http://zope.org

Hope information helps.

Larry Bates
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 "globalstat e" 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(s elf)
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:

(code contained in "saveload" module)
import pickle
import world
def savegame(path_t o_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
fp = open(path_to_na me, "w")
pickle.dump(wor ld_data, fp)
fp.close()

def loadgame(path_t o_name):
fp = open(path_to_na me, "r")
world_data = pickle.load(fp)
for attr, value in world_data.item s():
setattr(world, attr, value)
fp.close()

The problem is that the game objects only get overwritten in the world
module. The instances in the globalstate.all _fruit list remain
unchanged, which is not the behaviour I want. I started to write code
to get around this. I figured that with each loadgame call, I could
reset all the lists in globalstate to empty, then reappend each game
object to the appropriate list. But this possibility got complicated
fast, because all game objects belong to more than one list. My apple
instance alone would belong to globalstate.all _things,
globalstate.all _fruit, globalstate.all _items, and perhaps others. Some
of the game objects contained in these lists don't need to be a part
of capturing program state in the first place! But I'm stuck, because
unpickling (so far as I understand it) creates a brand new instance
that doesn't know it used to have references to itself in the
globalstate lists.

Any advice out there? I'm looking for a clean, elegant way to
overwrite the same class instance in two arbitrary places at once.
Perhaps the example code I've provided isn't even the best way of
saving and restoring program state. Perhaps I can easily update my
globalstate lists and I'm just overlooking the simple way. Or perhaps
the solution lies in abandoning the concepts of referencing my game
objects through module attributes and lists. I'm open to any
suggestions.

Thanks in advance for any help!

Jacob

Jul 18 '05 #2

"Jacob H" <ja********@pos tmark.net> wrote in message
news:85******** *************** **@posting.goog le.com...
I'm developing an adventure game in Python


Since you are not the first, have you looked at what others have done to
save/restore? The Pygame site has code you can look at for adventure (I
believe) and other game types (I know).

Terry J. Reedy

Jul 18 '05 #3
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 "globalstat e" 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(s elf)
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_t o_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_sheba ng = [ world_data, globalstate.all _fruit, globalstate.all _items ] fp = open(path_to_na me, "w") pickle.dump(the _whole_shebang, fp) fp.close()

def loadgame(path_t o_name):
fp = open(path_to_na me, "r") the_whole_sheba ng = pickle.load(fp)
world_data, globalstate.all _fruit, globalstate.all _items = the_whole_sheba ng for attr, value in world_data.item s():
setattr(world, attr, value)
fp.close()


Kent
Jul 18 '05 #4
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 "globalstat e" 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(s elf)
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.tot al
.... 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.heigh t = 5.7
....store.secre t = 42
And get them back when needed.
Py>self.SetHieg ht(store.hieght )

Hth
M.E.Farmer

Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
7253
by: Michael Albanese | last post by:
Can you save objects a (custom class) to Viewstate and then get them on a later page?? I have a custom class for an ASP.Net application that I would like to make available across several web pages. For example: page1.aspx accepts a users's name, age and gender, instantiated the new class and redirects to page2.aspx
11
1930
by: cwdjrxyz | last post by:
Several threads have discussed the accuracy of time calculated using script when Daylight Saving Time (DST) is considered. A page at http://webexhibits.org/daylightsaving/ gives much information on DST, and how it differs in various parts of the world. There is a calculator for the US and EU systems. However there are other variations in the world. In the US, I live in the CST time zone. However this is called CDT when DST is in effect....
4
2654
by: ralphNOSPAM | last post by:
Is there a function or otherwise some way to pull out the target text within an XML tag? For example, in the XML tag below, I want to pull out 'CALIFORNIA'. <txtNameUSState>CALIFORNIA</txtNameUSState>
15
1509
by: Dan DeConinck | last post by:
Hello, I want to save the position of all the controls on my form. I would like to write them out to a preference file. I have done this in DOS BASIC like this: TO WRITE the preference open "c:\preferences.txt" for input as #1 input #1 ,a,b,c
1
1630
by: Tom | last post by:
I have a large application; lots of forms, multiple dynamic DLLs, etc. I also have, in the appliation, a general 'Preferences' class object (which is in itself a separate DLL, and I just include a reference to it so I can instantiate it at the beginning) which stores all my user preferences. I serialize the data to and from an XML file, thereby saving and restoring the user preferences with ease. I also have a Preferences form that the user...
15
3740
by: Marcus Kwok | last post by:
How do you save the formatting options for a stream? In the program below, notice that when I define my operator<<() for the custom type, it permanently changes the output format of the stream: #include <iostream> #include <iomanip> struct Data { double d; };
2
2178
by: Greg | last post by:
I am building an SVG interface (with Javascript) for client side control of some hardware. The svg will be hosted on a micro PC (http://www.picotux.com/indexe.html). It runs a uClinux OS with GCC 3.4.4 for C++ (and Fortran??) and a Web Server and Telnet and not much more. My SVG seems to be working fine and using Firefox's DOM browser I can see it change. What I can't do is find a way to capture these DOM state changes. All I need is to...
53
4690
by: Hexman | last post by:
Hello All, I'd like your comments on the code below. The sub does exactly what I want it to do but I don't feel that it is solid as all. It seems like I'm using some VB6 code, .Net2003 code, and .Net2005 code. I'm developing in vb.net 2005. This test sub just reads an input text file, writing out records to another text file, eliminating records that have a '99' in them (it is similar to a CSV file). Some of my concerns are:
1
1330
by: carlos123 | last post by:
Hello, I am using BlueJ and I am totally lost on my newest programming assignment. Here is my source code, i would really appreciate if someone helped me out. This is my assignment. Ive done some of the work like entering all the data in for the combo boxes. But I dont know how to get the combo box to display, and I dont know how to write and read to a file, im SOo lost. If someone could just PLEASE take a look at the code and try to fix the...
0
8649
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9081
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8975
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8931
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6564
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4408
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4660
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3097
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2032
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.