简体   繁体   English

如何从字典块中获取某些输出

[英]How to get certain outputs out of a dict block

My RPG-related issues have transmogrified. 我的与RPG有关的问题已变得无处可寻。 I have a dict block of weapons, defined with (I believe) their value and damage. 我有一个dict武器块,定义了(我相信)它们的价值和伤害。 How do I generate a certain weapon as output, say, for a merchant to have for sale? 我如何生成某种武器作为输出,例如,供商人出售?

Here's the weapon class: 这是武器类:

class weapon(object):
  def __init__(name, loot_worth, damage):
    Character.__init__(self)
    self.damage = Damage
  def Damage(weapon):
    self.damage = Damage

Segment of dict block: dict块的片段:

weapon_dict = {"None"             : [0, 0],
               "Imaginary Sword"  : [0, 0],
               "Twig"             : [0, 1]
              }

The merchHasWeapon function block: merchHasWeapon功能块:

def merchHasWeapon(self):
    if self.merchstate == 'buy':
      return random.choice(weapon_dict.keys())

And the merch function: 和Merch功能:

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)

The error message that prints if the "def merchHasWeapon" block comes before the "def merch" block is "zero length field name in format." 如果“ def merchHasWeapon”块位于“ def merch”块之前,则显示的错误消息是“格式的零长度字段名称”。 If it comes after, it says "global name merch isn't defined." 如果出现这种情况,则会显示“未定义全局名称merch”。 Could someone help me remedy this error? 有人可以帮助我纠正此错误吗?

The problem is this: 问题是这样的:

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]))

Firstly, merch_weapon is a function, so you actually have to call it by doing self.merch_weapon() . 首先, merch_weapon是一个函数,因此实际上您必须通过执行self.merch_weapon()来调用它。 Next, your merch_weapon function should return something so you can use it when accessing the dictionary: 接下来,您的merch_weapon函数应返回一些内容,以便您在访问字典时可以使用它:

def merch_weapon(self):
    if self.merchstate == 'buy':
      return random.choice(weapon_dict.keys()) # list() isn't needed here

Now, when you go to print your weapon and armour stats, don't forget the parentheses: 现在,当您打印武器和盔甲统计数据时,请不要忘记括号:

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]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM