gpt4 book ai didi

python - 将元素添加到游戏库存中的堆叠中

转载 作者:行者123 更新时间:2023-11-30 22:53:12 24 4
gpt4 key购买 nike

我尝试解决这个问题一个半小时以上,但最终还是放弃了。尽我所能,我无法将类似的元素堆叠在库存中。

具体来说,我随机生成一个“drop”,它的名称和数量存储在数组中。 “drops”是一个保存这些子数组的二维数组。我正在尝试在玩家的库存中搜索该掉落物,该掉落物也有一定的数量,当将掉落物添加到其中时,数量会增加......如果它工作正常的话。

import random as rd

inventory = []

items = ["gunk","gear","bolt","wheel","pinion"]
drops = []



while True:
enter = input("")
if enter == "":
drops = []
quantity = 1
drops.append([rd.choice(items),quantity])
print("drops",drops)
for i in range(len(drops)):
try:
add_to = inventory.index(drops[i])
inventory[add_to][1] += quantity
except:
inventory.append(drops[i])


print("inv",inventory)

输出(反复按回车键):

drops [['pinion', 1]]
inv [['pinion', 1]]
drops [['gunk', 1]]
inv [['pinion', 1], ['gunk', 1]]
drops [['pinion', 1]]
inv [['pinion', 2], ['gunk', 1]]
drops [['bolt', 1]]
inv [['pinion', 2], ['gunk', 1], ['bolt', 1]]
drops [['pinion', 1]]
inv [['pinion', 2], ['gunk', 1], ['bolt', 1], ['pinion', 1]]

如您所见,由于数量与搜索的数量不匹配,因此它只是添加了一个新数量。知道如何解决这个问题吗?

最佳答案

对于这种事情,更好的数据类型是使用 dict 作为库存,因为它可以跟踪给定键(项目)的数量:

import random as rd

inventory = {}

items = ["gunk","gear","bolt","wheel","pinion"]
drops = []



while True:
enter = input("")
if enter == "":
drops = []
quantity = 1
drops.append([rd.choice(items),quantity])
print("drops",drops)

for drop in drops:
item = drop[0]
qty = drop[1]
if item in inventory:
inventory[item] += qty
else:
inventory[item] = qty

print("inv", [[key, inventory[key]] for key in inventory])

以下是输出示例:

drops, [['gunk', 1]]
inv, [['gunk', 1]]
drops, [['wheel', 1]]
inv, [['wheel', 1], ['gunk', 1]]
drops, [['gunk', 1]]
inv, [['wheel', 1], ['gunk', 2]]
drops, [['gear', 1]]
inv, [['wheel', 1], ['gunk', 2], ['gear', 1]]
drops, [['pinion', 1]]
inv, [['wheel', 1], ['pinion', 1], ['gunk', 2], ['gear', 1]]
drops, [['gunk', 1]]
inv, [['wheel', 1], ['pinion', 1], ['gunk', 3], ['gear', 1]]

关于python - 将元素添加到游戏库存中的堆叠中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com