首页 > 解决方案 > 构建游戏,需要关于库存的建议

问题描述

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

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 命令来实现可能的工作:使用库存中的东西来制作其他东西并将其作为结果添加回来。

而且由于代码是按顺序运行的,这意味着如果某项运行正确,则下一项运行。如果出现错误,它将不会运行下一件事。问题是:如果你没有制作它的原料,它仍然会从库存中撕掉你所有的东西,并且什么也不会返回。

这是我看到的:

在职的:

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

不工作:

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

代码重写、修复或建议表示赞赏。

我是python的新手,一个月前才开始。

标签: pythonlist

解决方案


你很快就会意识到你想使用类来处理这个问题。因此,您的对象将是 Inventory、Item、Recipe 等。

但是,要在您已经达到的水平上为您提供实际提示,您可以尝试这样做:

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)

输出:

物品制作成功。

{'苹果':4,'橙色':1}

你没有制作这个的原料。

{'苹果':4,'橙色':1}


推荐阅读