Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Random monsters appear, but saving the dragon for last

So I've been able to make random monsters appear, but I can't figure out how to make the dragon come last. Here's an incomplete version of my code: Also, I'm sorry if the formatting is wrong. I can't seem to make it appear properly.

class Game: def setup(self): self.player = Character() self.monsters = [ Goblin(), Goblin(), Troll(), Dragon() ]

self.monster = self.get_next_monster()

def get_next_monster(self): max_mon = len(self.monsters) new_mon = random.randint(0, max_mon)

try:

    return self.monsters.pop(new_mon) 

except IndexError:
  return None

I'm at a loss with what to do at this point. Any help is appreciated.

If you are using pop to summon monster you can make random selection to re-select when it picked dragon and length of monster list is 1. Or you can put dragon out of list and make it only appear when monster list is empty.

1 Answer

Pick a random number between 0 and max_mon-1, that way it will choose a random monster between the first monster and the last monster before the dragon. And when max mon = 1 you return the dragon.

def get_next_monster(self):
max_mon = len(self.monsters)
if max_mon > 1:   #more monsters besides the dragon
  new_mon = random.randint(0, max_mon-1)
else:   #just the dragon is left
  new_mon = 0
try:
  return self.monsters.pop(new_mon)
except:
  return None

Thanks! Your answer worked, with one minor adjustment: max_mon-1 still includes the dragon(since the index number of the dragon is max_mon-1), so I changed it to max_mon-2, and it started working.