0

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

4
Contributors
13
Replies
101
Views
4 Years
Discussion Span
Last Post by james.lu.75491856
0

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

Edited by pyTony

0

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 by Gribouillis

0

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 by james.lu.75491856

0

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 by Gribouillis

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.