I'm new to python and programming. Im trying to create a simple (for now) text game and have a problem. Here's part of my code I have problem with
class Monster:
def __init__(self,name,hp,ac,exp,thaco):
self.name=name
self.hp=hp
self.ac=ac
self.exp=exp
self.thaco=thaco
class Zombie(Monster):
def __init__(self):
super().__init__(name="Zombie",
hp=10,ac=5,
exp=1,thaco=20)
POWER=[1,2,3,4,5,6,7]
class Ghul(Monster):
def __init__(self):
super().__init__(name="Ghul",
hp=12,ac=6,
exp=1,thaco=20)
POWER=[1,2,3,4,5,6]
class Skeleton(Monster):
def __init__(self):
super().__init__(name="Skeleton",
hp=6,ac=2,
exp=1,thaco=20)
POWER=[1,2,3,4]
class Ghost(Monster):
def __init__(self):
super().__init__(name="Ghost",
hp=5,ac=10,
exp=2,thaco=20)
POWER=[1,2,3,4,5,6]
class Slime(Monster):
def __init__(self):
super().__init__(name="Slime",
hp=26,ac=8,
exp=4,thaco=20)
POWER=[5,6,7,8,9,10]
def random_mob():
while twenty_sided_die.roll() <=5 :
mob=Zombie()
return mob
while 5 < twenty_sided_die.roll() <= 10:
mob=Ghul()
return mob
while 10 < twenty_sided_die.roll() <= 15:
mob=Skeleton()
return mob
while 15 < twenty_sided_die.roll() <= 19:
mob=Ghost()
return mob
while twenty_sided_die.roll() > 19:
mob=Slime()
return mob
mob = random_mob()
for command, action in hero.COMMANDS.items():
print("Press {} to {}".format(command, action[0]))
while True:
command = input("~~~~~~~Press key to continue~~~~~~~")
if command not in hero.COMMANDS:
print("Not a valid command")
continue
print("You are fighting " + mob.name)
time.sleep(1)
print("")
break
Problem is at the last part of the code when printing mob to fight. Every few tries, I got error:
AttributeError: 'NoneType' object has no attribute 'name and I cannot find any reason why.
Aprreciate for any advice
The error comes from you random_mob
function. Try this:
def random_mob():
roll = twenty_sided_die.roll()
if roll <= 5 :
return Zombie()
elif roll <= 10:
return Ghul()
elif roll <= 15:
return Skeleton()
elif roll <= 19:
return Ghost()
else:
return Slime()
Explanation: you should only roll your die once, store the result and test it against all sub-ranges. In your original function, you roll the die several times and you've got a chance that all tests return False, which means that the function returns None
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.