I would like to use pickle() to save the stats, progress, and location of a player in my text adventure. I know that pickle() write an object to a text file, and that file can be later recalled to load the information.
My curiosity is, would I be able to save the stats, inventory and last location of the player by pickling into one file? If so, how would I do this? I am not quite sure how to use pickle(), so if anyone has any spare source codes where they used pickle() which I could learn from it would be greatly appreciated. Also, would I have to create one object containing all of this information in order to pickle what I need?
And for refreshment, what is an object? I am going to go back through my tutorials to brush up on key terms and concepts, in the meantime. Thanks,
karim

Well using pickle is quite easy in some respects. Its a great tool. Here is an example of code using it:

#This saves a copy of the class Player.
import pickle

class Player():
    def __init__(self):
        self.last_location = (0,0)

    def setLocation(self,pos):
        self.last_location = pos



    #and so on

p = Player()
p.setLocation((10,10))

f = open("pickles.txt",'w')
pk = pickle.Pickler(f)

pk.dump(p)


f.close()
# and this re-loads it!
import pickle


class Player():
    def __init__(self):
        self.last_location = (0,0)

    def setLocation(self,pos):
        self.last_location = pos
        
        
f = open("pickles.txt")

pk = pickle.Unpickler(f)
p = pk.load()

print p.last_location #look it gets it right!

Hope that helps you out.

Thanks, I should be able to mess around with this code to make it do what I want. I appreciate the help, all of you guys!

Here is a typical example:

# use module pickle to save/dump and load a dictionary object
# or just about any other intact object

import pickle

# create the test dictionary
before_d = {}
before_d[1]="Name 1"
before_d[2]="Name 2"
before_d[3]="Name 3"

# pickle dump the dictionary
fout = open("dict1.dat", "w")
pickle.dump(before_d, fout)
fout.close()

# pickle load the dictionary
fin = open("dict1.dat", "r")
after_d = pickle.load(fin)
fin.close()

print before_d  # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}
print after_d   # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}

You could create a player dictionary like
player_name : [stats, inventory, position]
for instance
'thor' : [[80, 50], ['gun', 'gold'], [20, 120]]

Thank you Ene Uran, as always, you have been a great help!

This article has been dead for over six months. Start a new discussion instead.