Dylan Armstrong
Dylan Armstrong

Reputation: 21

Python game save file

I'm writing a game in Python and have come to the point where I need a way of saving the players progress. I was thinking of having the script create a text file and write a couple of lines (for storing stat variables, and the room number) when the player exits the game. But I also need it to check if that file exits on startup and, if so, apply the stored values to the corresponding variables. Can anybody help?

Upvotes: 1

Views: 2913

Answers (3)

Senthil Kumaran
Senthil Kumaran

Reputation: 56823

import os
if os.path.exists('yourplayerfile'):
   with open('yourplayerfile') as f:
        # work with f
with open('yourplayerfile','a') as f:
     # update f

That's the outline you have to work with.

Upvotes: 0

Mohammad Efazati
Mohammad Efazati

Reputation: 4910

i suggest you save in sqlite or some things like this ... but i can't understand where is your question? saving file or read file?

try:
   f=open('/tmp/workfile', 'w')
   # i find file 
except:
   #there is no file
<open file '/tmp/workfile', mode 'w' at 80a0960>

... read docs http://docs.python.org/release/2.5.2/tut/node9.html

Upvotes: 0

Eli Bendersky
Eli Bendersky

Reputation: 273376

Two different issues here:

  1. What to store in the file and how to store it
  2. The logic of when to store and when to load

The first issue is simpler to address as it's more generic. You have several good options here: one is using Python's ConfigParser class for Windows .ini - like configuration files. Alternatively you can use pickle to simply dump some sort of a configuration/settings data structure (may be a nested dict). Then there's the built-in SQLite binding. There are other options - it all depends on the level of complexity you want.

The second issue is more specific to your application. You can try to open the config file on startup and if it's there, read its contents. Later, you can periodically store the settings/progress into it. A word of advice: keep the complete set of settings in a consistent data structure at all times - even if only part of the settings are in the config file when you're reading it (for some reason), have default values for your settings.

Upvotes: 4

Related Questions