Question

I'm trying to create a game-save file in python, using a dict which looks like this:

       user = {
        'Name': 'craig',
        'HP': 100,
        'ATK': 20,
        'DEF' : 10,
        'GOLD' : 300,
        'INV' : [0, pants],
        'GEAR' : [0, axe],
        'CityLevel' : 0,
        'BadAns': 0,
        }

I'm passing it through classes just like in excercise 43 of learn python the hard way

the code in

"############

code here

#######"

works, but replacing all of that with name = temp doesn't pass the 'user' variable along with the return like the current code does.

class User():
  def enter(self, user):

    def writing(self, user):
        pickle.dump(user, open('users.pic', 'a'))

    print "Is this your first time playing?"
    answer = prompt()

    if answer == 'yes':
        print "Welcome to the Game!"
        print "What do you want to name your character?"
        user['Name'] = prompt()
        writing(self, user)
        print "You'll start out in the city, at the city entrance, Good luck!"
        gamesupport.print_attributes(player)
        return 'City Entrance'
    elif answer == 'no':
        print "what is your character's name?"
        charname = prompt()
        temp = pickle.load(open('users.pic'))
        ######################################
        user['Name'] = temp['Name']
        user['GOLD'] = temp['GOLD']
        user['HP'] = temp['HP']
        user['ATK'] = temp['ATK']
        user['DEF'] = temp['DEF']
        user['GEAR'] = temp['GEAR']
        user['CityLevel'] = temp['CityLevel']
                    ############################################
        print user
        return 'City Entrance'
    else:
        print "we're screwed"

the 'print user' works as expected, and prints everything correctly even if i just use 'user = temp', but then the user variable isn't saved and passed on to the rest of the game

why is this and how can I fix it? having to type in each attribute line by line isn't good, because then I can't append anything to 'user' and have it save and load up again.

Was it helpful?

Solution

This has to do with how Python references objects. Take a look at this example:

>>> test = {}
>>> test2 = test
>>> test2 is test
True
>>> def runTest(test):
...     print test is test2
...     test = {}
...     print test is test2
... 
>>> runTest(test)
True
False

As you can see, in the runTest function if you use test = ... the variable references a new dictionary. The way to solve this is to use the update method. This copies all values from the source dictionary into the target dictionary:

>>> source = {'a':'b', 'c':'d'}
>>> target = {'a':'g', 'b':'h'}
>>> target.update(source)
>>> print target
{'a':'b', 'b':'h', 'c':'d'}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top