2012-03-30 66 views
2

我一直在玩一個小遊戲,只是爲了好玩,而且我遇到了問題。所以爲什麼我的清單沒有更改?

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',它會顯示處於原始狀態的物品列表。

我一直在谷歌搜索和stackoverflowing現在1.5個一天,我找不到任何似乎解決這個問題。

如果有什麼不清楚的地方,只要問我,我會盡力回答。

回答

4

locations字典是從describeRoom函數獲取其房間描述的字典在程序啓動時初始化一次。那時候,玩家的位置是cookieroom,對象是crowbarhammer。因此,一個字符串,像這樣

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

創建這個字符串永遠不會改變,即使你後來改變items詞典的內容。

您的locations字典應該只包含房間描述的不變部分。每當用戶請求房間的描述時,應該重新計算改變部分(例如房間中的物品列表等)。

+0

太棒了!謝謝Noufal。雖然我沒有足夠的聲望,但我無法讚揚這一點。 – 2012-03-30 07:29:13

相關問題