Python 建立一个游戏,需要关于库存的建议
我目前正在做一个游戏,我需要一些帮助。 你知道大多数游戏都有一个元素,你可以用你拥有的东西制作东西,比如minecraft吗? 这就是我在这里要说的:Python 建立一个游戏,需要关于库存的建议,python,list,Python,List,我目前正在做一个游戏,我需要一些帮助。 你知道大多数游戏都有一个元素,你可以用你拥有的东西制作东西,比如minecraft吗? 这就是我在这里要说的: def craftitem(item): if item == 'applepie': try: inventory.remove('apple') inventory.remove('apple') inventory.remove('apple')
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命令来实现可能有效的功能:使用清单中的内容制作其他内容,并将其作为结果添加回去
由于代码是按顺序运行的,这意味着如果某个东西正确运行,下一个东西就会运行。如果出现错误,它将不会运行下一步。问题是:如果你没有制作它的原料,它仍然会把你所有的东西从库存中撕掉,什么也不归还
以下是我看到的:
工作:
不工作:
代码重写、修复或建议
我是python的新手,大概一个月前才开始学习。首先要做的事情是计算库存中所需的物品数量,看看是否有足够的物品来制作该物品。例如:
num_apples = sum(item == 'apple' for item in inventory)
您很快就会意识到您想要使用类来处理这个问题。所以你的目标是库存、物品、配方等 但是,为了给你现有水平的实际小费,你可以试着这样做:
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)
recipes={'applepie':[('apple',4)],
“appleorangepie”:[('apple',4),('orange',2)]]
库存={'apple':8,'orange':1}
def工艺_项目(项目):
配料=配方。获取(项目)
成分中的(名称、数量):
如果库存.get(名称,0)<金额:
打印('你没有制作这个的原料')
返回
成分中的(名称、数量):
存货[名称]-=金额
打印('项目制作成功')
工艺项目('applepie')
打印(库存)
工艺项目('appleorangepie')
打印(库存)
输出:
项目制作成功
{‘苹果’:4,‘橙色’:1}
你没有制作这个的原料
{‘苹果’:4,‘橙色’:1}
我会使用dict使用ID和ID槽。我不会从列表中删除项目,而是从dict中清除一个特定ID。这允许我向每个项目添加特殊信息,如“数量、价值、供应商价值、可制作性等”。实际上这很好,而不是在一个列表中重复。所以定义定义了制作的功能,对吗?
num_apples = sum(item == 'apple' for item in inventory)
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)