为什么我的列表会发生变化?

时间:2012-03-30 06:57:05

标签: python

我一直在玩一个小游戏,只是为了好玩,我遇到了一个问题。我会发布代码并尽力解释:

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)

因此,正如您所看到的,当您选择特定房间中可用的项目时,我希望项目字典中的项目列表能够更改。我可以拿起物品并将其添加到我的库存中但是如果我发出命令'look'它会显示其原始状态的物品清单。

我一直在谷歌搜索和堆栈溢出1天半,我找不到任何似乎可以解决这个问题。

如果有什么不清楚,请问我,我会尝试回答。

1 个答案:

答案 0 :(得分:4)

locations字典,即describeRoom函数从中获取其房间描述的字典,在程序启动时初始化一次。那时,玩家的位置是cookieroom,其中的对象是crowbarhammer。所以,就像这样创建一个字符串

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

即使您稍后更改了items字典的内容,此字符串也不会更改。

您的locations词典应仅包含会议室描述中不变的部分。每当用户请求房间的描述时,应该重新计算改变部分(例如房间中的项目列表等)。