我的 RPG 相关问题已经发生了变化。我有一个武器字典 block ,定义了(我相信)它们的值(value)和伤害。我如何生成某种武器作为输出,例如供商人出售?
这是武器类别:
class weapon(object):
def __init__(name, loot_worth, damage):
Character.__init__(self)
self.damage = Damage
def Damage(weapon):
self.damage = Damage
字典 block 的片段:
weapon_dict = {"None" : [0, 0],
"Imaginary Sword" : [0, 0],
"Twig" : [0, 1]
}
merchHasWeapon 功能 block :
def merchHasWeapon(self):
if self.merchstate == 'buy':
return random.choice(weapon_dict.keys())
还有商品功能:
def merch(self):
self.merchstate == 'buy'
self.merchstim = randint (0, 10)
self.merchammo = randint (0, 50)
if randint(0, 1):
temp_wpn = self.merchHasWeapon()
temo_armr = self.merchHasArmor()
print("Merch weapon: {} , Stats: {}".format(temp_wpn,weapon_dict[temp_wpn]))
print("Merch armor: {} , Stats: {}".format(temo_armr,armor_dict[temo_armr]))
print "%s goes to the Merchants' Clearing. For help with merchants, type mh." % self.name
print "Merchant's items:\n~Potions:%d\n~Arrows:%d\n" % (self.merchstim, self.merchammo)
如果“defmerchHasWeapon” block 出现在“defmerch” block 之前,则打印的错误消息是“格式中的零长度字段名称”。如果它出现在后面,则表示“未定义全局名称商品”。有人可以帮我纠正这个错误吗?
最佳答案
问题是这样的:
if randint(0, 1):
print("Merch weapon: {} , Stats: {}".format(merch_weapon,weapon_dict[merch_weapon]))
print("Merch armor: {} , Stats: {}".format(merch_armor, armor_dict[merch_armor]))
首先,merch_weapon
是一个函数,因此您实际上必须通过 self.merch_weapon()
来调用它。接下来,您的 merch_weapon
函数应该返回一些内容,以便您可以在访问字典时使用它:
def merch_weapon(self):
if self.merchstate == 'buy':
return random.choice(weapon_dict.keys()) # list() isn't needed here
现在,当您要打印武器和盔甲统计数据时,请不要忘记括号:
if randint(0, 1):
temp_wpn = merch_weapon()
temo_armr = merch_armor()
print("Merch weapon: {} , Stats: {}".format(temp_wpn, weapon_dict[temp_wpn]))
print("Merch armor: {} , Stats: {}".format(temo_armr, armor_dict[temo_armr]))
关于python - 如何从 dict block 中获取某些输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17386604/