建立一个游戏,需要关于库存的建议

2024-05-16 05:16:53 发布

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

我目前正在做一个游戏,我需要一些帮助。 你知道大多数游戏都有一个元素,你可以用你拥有的东西来制作东西,比如minecraft吗? 这就是我想说的:

def craftitem(item):
    if item == 'applepie':
        try:
            inventory.remove('apple')
            inventory.remove('apple')
            inventory.remove('apple')
            inventory.remove('apple')
            inventory.append('applepie')
            print('Item crafted successfully.')
        except ValueError:
            print('You do not have the ingredients to craft this.')

这是一个定义。我使用try命令来实现可能有效的功能:使用清单中的内容来生成其他内容,并将其作为结果添加回去。你知道吗

因为代码是按顺序运行的,这意味着如果某个东西运行正确,下一个东西就会运行。如果出现错误,它将不会运行下一个操作。问题是:如果你没有原料来制作它,它仍然会把你所有的东西从库存中撕掉,什么也不退。你知道吗

我看到的是:

Working:

>>>inventory = ['apple','apple','apple','apple']
>>>
>>>craftitem('applepie')
Item crafted successfully.
>>>
>>>>inventory
['applepie']

Not working:

>>>inventory = ['apple','apple','apple'] #Need one more apple
>>>
>>>craftitem('applepie')
You do not have the indredients to craft this.
>>>
>>>inventory
[]

代码重写、修复或建议。你知道吗

我是python的新手,一个月前才开始学习。你知道吗


Tags: you游戏applenotitemdoremoveinventory
2条回答

您很快就会意识到您想要使用类来处理这个问题。所以你的物品是库存,物品,食谱等等

但要给你实际的小费,你可以这样做:

recipes = {'applepie': [('apple', 4)],
           'appleorangepie': [('apple', 4), ('orange', 2)]}

inventory = {'apple': 8, 'orange': 1}


def craft_item(item):
    ingredients = recipes.get(item)
    for (name, amount) in ingredients:
        if inventory.get(name, 0) < amount:
            print('You do not have the ingredients to craft this.')
            return
    for (name, amount) in ingredients:
        inventory[name] -= amount
    print('Item crafted successfully.')


craft_item('applepie')
print(inventory)

craft_item('appleorangepie')
print(inventory)

输出:

Item crafted successfully.

{'apple': 4, 'orange': 1}

You do not have the ingredients to craft this.

{'apple': 4, 'orange': 1}

你首先要做的是计算库存中所需物品的数量,看看是否有足够的物品来制作。例如:

num_apples = sum(item == 'apple' for item in inventory)

相关问题 更多 >