Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save game feature for Python?

Recently I have started work on a new game. I have created games before but they have been relatively simple games that can be completed in one sitting of about 5-10 minutes. So I tried making a bigger game that needed more than one sitting, or a very long sitting if not. I started making a flow chart for this game when I stumbled across the fact that I needed a save game feature. I have looked around this website, and others alike, but I am not very experienced so I find them a bit difficult to understand. I would like to be able to save variables to a .txt file then reload them later on. If you do answer this could you please go into detail, so I could understand it that would be great.

The game I am making is a text based game and I am running Mac OS 10.6.7

like image 448
Dragaming Avatar asked Dec 06 '25 04:12

Dragaming


1 Answers

I would store the relevant statistics which are needed to recreate the previous state of the game in a dictionary, for example:

stats = {'health': 100, 'lives': 4, 'gold': 42}

You can export this as JSON with:

import json
with open('myfile', 'w') as f:
    f.write(json.dumps(stats))

You can load the stats with:

with open('myfile', 'r') as f:
    stats = json.load(f)

If you want to support several savegames, I would create one file for each.

like image 74
timgeb Avatar answered Dec 07 '25 16:12

timgeb