我是python和编程的新手。我试图创建一个简单的(现在)文本游戏,并有一个问题。这是我的代码的一部分,我有
的问题 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
问题在于打印暴徒进行战斗时代码的最后部分。 每隔几次尝试,我就会收到错误:
AttributeError:'NoneType'对象没有属性'name,我找不到任何原因。
感谢任何建议
答案 0 :(得分:2)
错误来自您random_mob
函数。试试这个:
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()
说明:您应该只掷一次骰子,存储结果并针对所有子范围进行测试。在原始函数中,您可以多次掷骰子,并且您有可能所有测试都返回False,这意味着该函数返回None