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

Dani AI

Generated

A few practical points to tie the replies together and give a straightforward, robust pattern you can drop into a game.

Keep one explicit, versioned save structure

  • Put only the data you actually need to persist (player id, level index, score, inventory as plain lists/dicts, time, save_version). Avoid dumping whole interpreter state or file/GUI handles. That makes loads predictable and easier to migrate when your code changes. pointed you toward a state object; build on that by adding a save_version and profile metadata so you can detect and upgrade old saves.

Prefer simple, explicit serialization over dumping everything

  • JSON (or a small custom dict format) is great for primitives and portability. Pickle/shelve can be convenient but unsafe if you ever load saves from untrusted sources; they can execute arbitrary code. Instead, give game objects to_dict() and from_dict() methods and serialize those dictionaries. Example pattern:
class Game:
    def to_dict(self):
        return {"player": self.player_name, "level": self.level, "inventory": [i.to_dict() for i in self.inventory]}
    @classmethod
    def from_dict(cls, data):
        g = cls()
        g.player_name = data["player"]
        g.level = data["level"]
        g.inventory = [Item.from_dict(d) for d in data["inventory"]]
        return g

Write/read safely and handle corruption

  • Use atomic saves (write to a temp file then rename/replace), catch parsing errors on load, validate save_version, and fall back to a clean new game if the file is corrupted. Don’t rely on globals() or locals() to capture state automatically; explicit mapping is clearer and less brittle than the approach mentioned by and the globals loop shown by .

Extras to consider

  • Save slots, autosave intervals, and simple integrity checks (a checksum or JSON schema) improve UX. Store saves in a per-user app directory, and write small unit tests to verify save->load roundtrips after refactors.

Recommended Answers

All 13 Replies

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

what do you mean?

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.

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)

@Grib
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

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']

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!

pickle a dictionary with variables

Be a part of the DaniWeb community

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