Python game save file
I'm writing a game in Python and have come to the point where I need a way开发者_如何学C 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?
Two different issues here:
- What to store in the file and how to store it
- 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.
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
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.
精彩评论