Question

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

Was it helpful?

Solution

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top