linuxwindows-xppython-2.7save

Python game - creating a save file?


I'm creating a game in python 2.7.2, but I've hit a snag. I would like to save the game's state in the game by having the program create a python script and inside there being a module basically saying to jump to such and such module in the game.

It's an entirely console based hacking game, based on real techniques and programs. And it's set in an linux enviroment ;)

I did find this :

Python game save file

but some of the bits of code I'm not sure how to use and I'm not sure they would fit my scenario perfectly.

thanks in advance.


Solution

  • Like Kimvais said, using the pickle module is an easy option. I use it for my game to save and load profile data, and to save and load each level. Here's an example of a function that save's a player's profile which includes the levels she's unlocked, items collected etc.

    def writeProfile(profileName, profileData):
        """ pickle user profile data """
    
        os.chdir(PROFILE_DIR)
    
        fileName = profileName + ".dat"
        f = open(fileName, "wb")
        pickle.dump(profileData, f)
        f.close()
    
        os.chdir("..")
    

    profileName is a string with the name of a .dat file where player data is stored. profileData is the new data (stored in python objects like tuples, lists and dictionaries) that will overwrite the old data and be stored in the .dat file. PROFILE_DIR is a path to the directory where the saved game data should be stored. os is a python module that does stuff like navigating directories and finding files.