pythonpython-2.7adventure

Python text game save feature


hi I have been working on a text adventure in python and the game has got to big just to do in one sitting so I tried to make a save feature with pickle so it would save my main variables like location, gold and inventory to a .txt file but I can't get it to load the new variables the load and save features are at the bottom of the code. Thanks in advance.

def do_save(self, arg):
    savegame = open('savegame.txt', 'w') 
    pickle.dump(inventory, savegame)
    pickle.dump(gold, savegame)
    pickle.dump(location, savegame)




def do_load(self,arg):
    loadgame = open('savegame.txt', 'r') 
    inventory = pickle.load(loadgame)
    location = pickle.load(loadgame)
    gold = pickle.load(loadgame)

Solution

  • The first issue with this code is that you never close the file which can (and will) lead to memory issues because the stream will stay open, so never forget to close it using savegame.close()

    The second problem lies in the way the file is being opened. Pickle reads and writes in binary so the file should be read and written using binary mode (wb and rb instead of w and r).

    Next up, the pickling, this section is more of a suggestion and is not necessary to solve the issue that you are having. It is possible to Pickle multiple items into one file, but an easier solution might be to just put them into one object, for example a tuple containing all 3 values:

    def do_save(self, arg):
        saveGame = open('savegame.txt', 'wb')
        saveValues = (inventory, gold, location)
        pickle.dump(saveValues, saveGame)
        saveGame.close()
    
    def do_load(self, arg):
        loadGame = open('savegame.txt', 'rb')
        loadValues = pickle.load(loadGame)
        inventory = loadValues[0]
        gold = loadValues[1]
        location = loadValues[2]
        loadGame.close()
    

    This solution is less resource heavy considering it only reads and writes to the file once, and it allows the file stream to be open for a shorter duration.