2017-10-08 57 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))