基于文本的游戏库存清单(Python)

时间:2017-10-08 04:42:45

标签: 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 个答案:

答案 0 :(得分: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')的值来轻松解决这个问题,这是一个为初学者调试程序的有用方法...基本上当某些东西无法正常工作时,尝试打印它,很可能是变量不是你认为的......

答案 1 :(得分:1)

也许可以进行更多的结构化,避免使用全局inventory。这是一个基本概念:

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))