简体   繁体   中英

Why doesn't my list change?

I've been hacking away on a little game, just for fun, and I've run into a problem. I'll post the code and try my best to explain:

def parseCmd(string):
    cmd = string.split(' ')
    if cmd[0] == 'help':
        showHelp()
    elif cmd[0] == 'add':
        addServer()
    elif cmd[0] == 'bag':
        viewInventory(inventory)
    elif len(cmd) == 1 and cmd[0] == 'look':
        describeRoom()
    elif len(cmd) == 1 and cmd[0] == 'take':
        print 'What do you want me to take?'
    elif cmd[0] == 'take':
        pickUp(cmd[1],  items)
    elif cmd[0] == 'exit':
        sys.exit(0)
    else:
        print 'I don\'t know how to '  + cmd[0]

def describeRoom():
    print locations[player_location]

def pickUp(item,  item_list):
    if item in item_list[player_location]:
        item_list[player_location].remove(item)
        inventory.append(item)
        print 'You took the ' + item        
    else:
        print 'I can\'t find any ' + item

inventory = ['id card',  'money',  'keys']
player_location = 'cookieroom'
items = {'cookieroom': ['crowbar',  'hammer']}
locations = {'cookieroom': 'The cookieroom, where all the hard work gets done. \n\nNORTH: LFA - ITEMS: %s' % items[player_location], 
                'LFA': 'The infamous LFA, where dreams of office supplies become reality. there is a big guy sleeping in his chair next to a fire extinguisher.\n\nSOUTH: Cookieroom, WEST: WC'}

if __name__ == "__main__":
    while 1:
        t = raw_input('-> ')
        parseCmd(t)

So, as you can see I want the list of items in the items dictionary to change when you pick up an item available in that specific room. I can pick up the item and it gets added to my inventory but if I issue the command 'look' it shows the list of items in it's original state.

I've been googling and stackoverflowing for 1½ day now and I can't find anything that seems to solve this problem.

If something is unclear, just ask me and I'll try to answer.

The locations dictionary, which is from where the describeRoom function picks up its room description, is initialised once when the program starts. At that time, the location of the player is the cookieroom and the objects there are the crowbar and the hammer . So, a string is created like so

'The cookieroom, where all the hard work gets done. \n\nNORTH: LFA - ITEMS: ["crowbar", "hammer"]'

This string never changes even if you later alter the contents of the items dictionary.

Your locations dictionary should only contain the non changing part of the room description. The changing part (eg the list of items in the room etc.) should be recomputed everytime the users requests the description of the room.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM