Python: 结合输入使用字典

Python: using dictionaries in conjunction with input

我正在写一个相当简单的文字冒险。一个功能是吃功能,允许你吃掉你库存中的一个物体并获得饥饿感。玩家输入想吃的物品名称,然后获得 饥饿基于对象的食物价值。不过好像不行。

food = ("Bread")
Bread = {"name": "Bread", "foodvalue": 10}
inv = []
inv.append("Bread")
def eat():
    global hunger
    print(*inv,sep='\n')
    print("Eat which item?")
    eatitem = input("> ")
    if eatitem in food and eatitem in inv:  
        hunger = hunger + eatitem["foodvalue"]
        inv.remove(eatitem)
        print("Yum.")
        time.sleep(1)

编辑:饥饿感每回合下降一次,当达到零时你就会饿死。因此,通过进食,您会增加饥饿感。

eatitem是用户的输入。 "foodvalue" 是你字典里的一个关键字,Bread。你想要:

hunger = hunger + Bread["foodvalue"]

您必须将 对象 放入清单 (inv) 并使用它的 name 键查找它:

food = ("Bread")
Bread = {"name": "Bread", "foodvalue": 10}
inv = []
# put the object (dict) in the inventory, not the string
inv.append(Bread)

之后:

eatitem = input("> ")
# iterate all items
for item in inv:
    # look for item in 'inv'
    if item['name'] == eatitem:
        # gain item's 'food value'
        hunger = hunger + item["foodvalue"]
        inv.remove(item)
        print("Yum.")
        time.sleep(1)
        # stop the loop to consume a single item instead of all items
        break

正如 Hugh Bothwell 在评论中所建议的那样,如果您需要通过食物的名称来查找食物,您可以使用字典结构,例如:

foods = {"Bread": {"foodvalue": 10, ...}}

在任何键下都有食物所具有的属性列表。

这将使您能够直接访问食物及其属性:

foods['Bread']['foodvalue'] # 10

eatitem 是一个字符串 ('Bread'),但您希望 eatitem 成为对象 Bread。有几种方法可以实现这一点(例如,您可以评估用户输入的字符串,但这.. 不好。),我将在这里概述一个:

food = {"Bread"} # changed to a set
Bread = {"name" : "Bread", "foodvalue" : 10}
items = { "Bread" : Bread }

[...]

def eat()
    global hunger 
    print(*inv,sep='\n')
    print("Eat which item?")
    eatitem_input = input("> ")
    eatitem = items[eatitem_input]
    if eatitem in food and eatitem in inv:  
        hunger = hunger + eatitem["foodvalue"]
        inv.remove(eatitem)
        print("Yum.")
        time.sleep(1)

这仍然可以通过使用 类(或者 named tuples)来改进。此外,将程序分成一个 Input/Output 部分和一个 "Engine part" 部分可能是个好主意。