Python:结合inpu使用字典

2024-09-29 23:29:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个相当简单的文本冒险。其中一个功能是eat功能,它允许你吃掉库存中的一个对象并获得饥饿感。玩家输入他们想吃的东西的名字,然后他们就得到了 饥饿基于对象的食物价值。不过,这似乎不管用。你知道吗

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)

编辑:饥饿感每回合下降一次,当达到零时你就会饥饿。所以吃东西会增加你的饥饿感。你知道吗


Tags: 对象in文本功能food冒险print饥饿
3条回答

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)来改进。另外,最好将程序分成一个输入/输出部分和一个“引擎部分”。你知道吗

您必须将对象放入清单(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是用户的输入。““食物价值”是你字典里的关键,面包。你想要:

hunger = hunger + Bread["foodvalue"]

相关问题 更多 >

    热门问题