2

all.

I'm currently trying to use cPickle to create a 'save_game' function for my Roguelike.

save_game() pickles the game-state properly, but if I exit the game, the load_game() function flatly refuses to acknowledge that the pickled file exists when I try to reopen the saved game (it just tells me that there's no saved data to load).

Here's save_game():

def save_game():
#Write the game data to a cPickled file
f = open('savegame', 'wb')
cPickle.dump('map',f, protocol=cPickle.HIGHEST_PROTOCOL)
cPickle.dump('objects',f, protocol=cPickle.HIGHEST_PROTOCOL)
cPickle.dump('player_index',f, protocol=cPickle.HIGHEST_PROTOCOL)
cPickle.dump('stairs_index', f, protocol=cPickle.HIGHEST_PROTOCOL)
cPickle.dump('inventory',f, protocol=cPickle.HIGHEST_PROTOCOL)
cPickle.dump('game_msgs',f, protocol=cPickle.HIGHEST_PROTOCOL)
cPickle.dump('game_state',f, protocol=cPickle.HIGHEST_PROTOCOL)
cPickle.dump('dungeon_level',f, protocol=cPickle.HIGHEST_PROTOCOL)
f.close()

and this is load_game():

f = open('savegame', 'rb')
cPickle.load(f)

f.close()

Am I doing this properly, or is it all bass-ackwards? lol

1 Answers1

2

The most important thing that you're missing is that pickle.load() needs to assign what is loaded to something. My advice is to put everything you want to save into one dictionary, pickle that dictionary and then unpickle it:

saveData = {'map': mapData,
            'objects': objectData}
pickle.dump(saveData, f, -1)

then in load_game():

f = open...
saveData = pickle.load(f)
f.close()
mapData = saveData['map']
objectData = saveData['objects']

btw -- I'd suggest not calling cPickle directly, especially when you're debugging -- it's much easier to see any errors with pickle and then only switch to cPickle when everything is working. You could also do something like this:

try:
   import cPickle as pickleMod
except ImportError:
   import pickle as pickleMod

then your program will work (albeit more slowly) no matter what flavor of python you're working with, and it makes it easier to switch from pickle to cPickle or back when you're done programming. Good luck with the game!

  • Woo, thanks! I've got the file saving if I make some alterations, but now it tells me that the global for 'mapData' is undefined, and so forth. I've tried globalizing on both save_game and load_game, but neither seems to work.... – Graham Fielding Dec 10 '12 at 22:19
  • mapData was just a holder variable for whatever object you have your map data stored in. Is it 'map'? if so, then put {'map': map} in the dict. what you write to pickle are actual objects, not variable names. – Michael Scott Asato Cuthbert Dec 11 '12 at 06:40
  • Did it work? Just curious if you think this answer is worth an accept? – Michael Scott Asato Cuthbert Dec 14 '12 at 17:29