0

I don't know if there is a way to do this or not. I am trying to create a object only if a certain criteria is met. I can create the object with an if statement, but I don't know how to use it in later code. Should I use 'global'? I wasn't sure since the same object name is used if each of the if/elif statements.

Here's the first part.

def dm_roll():
  roll = random.randint(1, 20)
  print(roll)
  if roll > 0 and roll <= 10:
    opponent = Monster('Goblin', 6, 2)
  elif roll > 10 and roll <= 16:
    opponent = Monster('Zombie', 8, 3)
  elif roll > 16 and roll <= 19:
    opponent = Monster('Ogre', 15, 5)
  else:
    opponent = Monster('Dragon', 1000000, 10)

  print("You have run into a {}!".format(opponent.name))

So here I would have created an object based on a random number generator. Let's say a 3 was generated and a 'Goblin' was created. I want to be able to use that object in another function like the one below.

def fight():

  while opponent.alive() and hero.alive():
    hero.print_status()
    opponent.print_status()

My issue is that I cannot currently use the object that is randomly generated. Any ideas?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271

1 Answers1

1

You need to write a main script where you'll need to pass the opponent variable around, something like this:

def dm_roll():
  roll = random.randint(1, 20)
  print(roll)
  if roll > 0 and roll <= 10:
    opponent = Monster('Goblin', 6, 2)
  elif roll > 10 and roll <= 16:
    opponent = Monster('Zombie', 8, 3)
  elif roll > 16 and roll <= 19:
    opponent = Monster('Ogre', 15, 5)
  else:
    opponent = Monster('Dragon', 1000000, 10)
  return opponent   #you need to return the opponent


def fight(opponent,hero):
  # Takes in the opponent and hero
  while opponent.alive() and hero.alive():
    hero.print_status()
    opponent.print_status()

def createHero():
  hero= Hero("<Hero Parameter">) #create hero object as per the conditions you might have
  return hero

if __name__="__main__":
  opponent = dm_roll() # returns the Monster object
  print("You have run into a {}!".format(opponent.name))
  hero = createHero() #returns the Hero Object
  fight(opponent,hero) #Let them fight
Vimanyu
  • 625
  • 2
  • 9
  • 24