I am trying to make a save feature in a game so that a player could save, then quit the game, then open the window again to select proflie and play from when they left off. Thanks!!

Fine, all the best with your studies of json and ConfigParser modules!

Edited 3 Years Ago by pyTony

Here is an example. The program creates a dictionary containing the current state of the game, using simple data types, then saves this snapshot on disk in a json file:

import json

if __name__ == "__main__":

    state = {
        "player_name" : "bob",
        "level" : 3,
        "elapsed_time" : 24.3,
        "monsters" : ["ork", "dragon"]
    }

    # now save the state in a json file

    with open("mygame.json", "w") as ofh:
        json.dump(state, ofh)

    # load the state from the file

    with open("mygame.json", "r") as ifh:
        read = json.load(ifh)

    from pprint import pprint
    pprint(read)

""" my output -->
{'elapsed_time': 24.3,
 'level': 3,
 'monsters': ['ork', 'dragon'],
 'player_name': 'bob'}
"""

The advantage of the json format is that it is human readable and cross programming language. To store more complex python types, use the pickle format.

Edited 3 Years Ago by Gribouillis

Try making a main() function inside a Game object, setting every variable to self, and using pickle to save/load it.(and Creating and instance of Game if not loadable)

Edited 3 Years Ago by james.lu.75491856

Suppose you have a global variable NSCREENS with integer value, you can write

state['NSCREENS'] = NSCREENS

before you save the state on disk. When you load a previously saved state, you can restore the variable with

globals()['NSCREENS'] = state['NSCREENS']

Edited 3 Years Ago by Gribouillis

Suppose you have 3 global variables named foo, bar, baz,
you can write

state['globals'] = {}
for varname in [
    'foo', 'bar', 'baz',
    ]:
    state['globals'][varname] = globals()[varname]

The global variables can then be restored with

for varname, value in state['globals'].items():
    globals()[varname] = value
This question has already been answered. Start a new discussion instead.