python - 构建游戏,需要关于库存的建议
问题描述
我目前正在开发一款需要一点帮助的游戏。你知道大多数游戏都有一个元素,你可以用你拥有的东西来制作东西,比如我的世界吗?这就是我在这里想要做的:
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的新手,一个月前才开始。
解决方案
你很快就会意识到你想使用类来处理这个问题。因此,您的对象将是 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}
推荐阅读
- tensorflow - 如何清除 Colab Tensorflow TPU 内存
- java - 我想使用 java(XSSF 格式)从扩展名为“.xlsx”的 Excel 文件中复制特定列
- node.js - VS代码反应项目中的npm start不起作用
- ios - 致命错误:无法从应用程序包中解码 productsTest.json
- node.js - 使用 nodejs 和 scoketio 发送实时通知
- python - ImportError:在 WINDOWS 上导入时 DLL 加载失败
- rabbitmq - 有没有办法为 Bitnami 上的 RabbitMQ 管理控制台启用 SSL?
- google-apps-script - 关于映射特定范围的googlesheet脚本问题
- ruby-on-rails - 如何使用带有自定义“get”路由的路径助手
- typescript - 如何在 Overlapping Marker Spiderfier for Leaflet 中应用特定的标记单击功能?