我的RPG相关问题已经变形了。我有一个dict块武器,定义为(我相信)它们的价值和损害。如何生成某种武器作为输出,例如,商家要出售?
这是武器类:
class weapon(object):
def __init__(name, loot_worth, damage):
Character.__init__(self)
self.damage = Damage
def Damage(weapon):
self.damage = Damage
dict块的段:
weapon_dict = {"None" : [0, 0],
"Imaginary Sword" : [0, 0],
"Twig" : [0, 1]
}
merchHasWeapon功能块:
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)
如果“def merchHasWeapon”块出现在“def merch”块之前,则打印出的错误消息是“格式为零长度字段名称”。如果它出现,它说“全局名称merch没有定义。”有人可以帮我解决这个错误吗?
答案 0 :(得分:1)
问题在于:
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]))