2017-10-08 60 views
0

所以我是新來的python,我正在製作一個文本基礎遊戲。我創建了一個庫存清單,如果玩家不止一次拿起物品,第二次應該能夠發出消息說他們已經擁有這個物品。我認爲它在某種程度上可以在某種程度上不超過一個值,但不會打印該消息。請幫忙!!基於文本的遊戲庫存列表(Python)

elif decision == "use H on comb": 
      global inventory 
      if inventory.count("comb")>1: 
       print ("You already got this item.") 
       print ("") 
       print ("Inventory: " + str(inventory)) 
      if inventory.count("comb")<1: 
       print ("(pick up comb)") 
       print ("You went over to the table and picked up the comb,") 
       print ("it's been added to your inventory.") 
       add_to_inventory("comb") 
       print("") 
       print ("Inventory: " + str(inventory)) 
      game() 

回答

2

只需使用in運算符來測試成員

if "comb" in inventory: 
    print("I have found the comb already...") 
else: 
    print("Nope not here") 

但是,爲什麼你的代碼是失敗是

inventory.count('comb') == 1 
# which fails inventory.count('comb') > 1 test 
# but also fails inventory.count('comb') < 1 test so its not re added 

你可以有通過打印輕鬆地解決了這個自己值爲inventory.count('comb'),這是一種用於爲初學者調試程序的有用方法...基本上,當某些東西不能正常工作時,嘗試打印它,有可能發生變化e是不是你認爲它是...

+0

謝謝你了!現在這太簡單了哇 – John

1

也許有點多結構可以做,並避免使用全局inventory .jsut以下基本思路:

def game(): 
    inventory = [] 
    # simulate picking up items(replace this loop with your custom logic) 
    while True: 
     item = raw_input('pick up something') 
     if item in inventory: # use in operator to check membership 
      print ("you already have got this") 
      print (" ".join(inventory)) 
     else: 
      print ("pick up the item") 
      print ("its been added to inventory") 
      inventory.append(item) 
      print (" ".join(inventory))