Medullan Medullan - 6 months ago 26
Python Question

How to make this code pick a random number each call Python?

#randomly picks a monster for a random encounter
class RanMob:
#randint(1,2)
roll=Dice.die(2)
if roll ==1:
mob=Goblin(Goblin.name,Goblin.hp,Goblin.thaco,Goblin.ac,Goblin.inventory)
if roll ==2:
mob=Orc(Orc.name,Orc.hp,Orc.thaco,Orc.ac,Orc.inventory)

while True:
#pick a new random monster
RanMob()
#print the name of the random monster
print(RanMob.mob.name)


When I run this code the
RanMob
class picks a new random number the first time through and then never picks a new number. How do I get it to pick a new mob each time I call
RanMob
in the main game loop?

Answer

Don't use a class. A class body is executed just the once (when Python encounters the class statement). The RanMob() line is entirely redundant here, it is not that line that executed the Dice.die() call.

Use a function and return the result:

def ranmob():
    #randint(1,2)
    roll=Dice.die(2)
    if roll ==1:
        return Goblin(Goblin.name,Goblin.hp,Goblin.thaco,Goblin.ac,Goblin.inventory)
    if roll ==2:
        return Orc(Orc.name,Orc.hp,Orc.thaco,Orc.ac,Orc.inventory)

while True:
    #pick a new random monster
    mob = ranmob()
    #print the name of the random monster
    print(mob.name)
Comments