1

So, I'm creating a little game in python to learn more about this language and I have two questions:

First - There is a way to every time that the player click on the 'new game', the program create a new save file?

Second - How can I load the saved files? They are text files and I don't know how to load them. The things that will be saved are the number coins, health, the name of the character, and other things. And the player can choice which file he want to load?

Thanks for the attention.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Which GUI are you using? – quickbug Mar 15 '15 at 22:47
  • 1
    You can save as many files as you have room for. You'll have to give each one a unique name — you can just number them sequentially. It's easy to save objects in Python, see [this answer](http://stackoverflow.com/questions/4529815/how-to-save-an-object-in-python/4529901#4529901) for simple examples. – martineau Mar 15 '15 at 22:51

1 Answers1

2

Saving is easy. You have many options, but two of the primary ones are:

1) The pickle module

https://docs.python.org/2/library/pickle.html

Built (by default, in Python3x) on C code, this is a very fast way to serialize objects and recover them. Use unique names for files, and look at the "dump" and "load" methods.

From the docs, this example should get you started:

# Save a dictionary into a pickle file.
import pickle

favorite_color = { "lion": "yellow", "kitty": "red" }

pickle.dump( favorite_color, open( "save.p", "wb" ) )

# Load the dictionary back from the pickle file.

favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }

In tkinter, this (the tkFileDialog)

http://tkinter.unpythonic.net/wiki/tkFileDialog

Should help you make a dialog for selecting file locations. Here's a good example of its usage:

Opening File (Tkinter)

2) Load/save and parse files yourself

You said that your game is for learning purposes, so doing things through manual file io isn't a bad idea. The documentation has a good place to get started, using "open" as the primary function for handling files. Again, "infinite" files simply means using unique name for each one

https://docs.python.org/2/tutorial/inputoutput.html

An example of manual io is

# writing data to a file
favorite_colors = {'tim':'yellow','mary':'blue'}

newsave_file = open(filename,'w')
for key, val in favorite_colors.items():
    newsave_file.write(str(key)+'|'+str(val)+'\n')

newsave_file.close()

# reading data from a file
favorite_colors = {}
open_file = open(filename,'r')
for line in open_file:
    pair = line.split('|')
    favorite_colors[pair[0]] = pair[1]
open_file.close()

You may want to do things like using try/catch block to ensure the program doesn't crash, or a more sophisticated parser technique. That's all up to you!

Community
  • 1
  • 1
en_Knight
  • 5,301
  • 2
  • 26
  • 46