Velcrode
Velcrode

Reputation: 9

How to get certain outputs out of a dict block

My RPG-related issues have transmogrified. I have a dict block of weapons, defined with (I believe) their value and damage. 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:

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

The merchHasWeapon function block:

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

And the merch function:

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." If it comes after, it says "global name merch isn't defined." Could someone help me remedy this error?

Upvotes: 1

Views: 66

Answers (1)

TerryA
TerryA

Reputation: 60014

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(). Next, your merch_weapon function should return something so you can use it when accessing the dictionary:

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

Upvotes: 1

Related Questions