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!!

Recommended Answers

All 13 Replies

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

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

""" 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.

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)

How would I save variables?

Variables are just values in locals() dictionary.

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


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

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

how would I load the state?

how would I load the state?

Read the code previously posted.

how would I write several variables to disk? Would I just do commas?

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

thanks to all the posters!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.