我正在制作一个基于python 2.7文本的RPG,而且我的战斗功能运行不正常。这是我的代码:
def attack(self):
print "A %r appears! It wants to fight!" % (self.name)
while (player.health > 0) or (self.health > 0):
player.health = player.health - ( ( randint(0,5) ) + attack_multiplier(self.level) )
print "%r strikes! Your health is down to %r" %(self.name, player.health)
try:
player.weapon = (raw_input("What do you attack with? >>").lower)
if (player.inventory.get(player.weapon) > 0) and (player.health > 0) and (self.health > 0):
if weapon_probability() == "critical hit":
self.health = self.health - (((randint(0,5))) + (attack_multiplier(weapon_levels.get(player.weapon))) * 2)
print "Critical Hit!"
elif weapon_probability() == "hit":
self.health = self.health - ((((randint(0,5))) + (attack_multiplier(weapon_levels.get(player.weapon)))))
print "Hit!"
elif weapon_probability() == "miss":
self.health = self.health
print "Miss"
print "Enemy health down to %r!" % (self.health)
elif player.health <= 0:
print "Your health...it’s falling"
break
elif self.health <= 0:
print "Enemy vanquished!"
break
except ValueError:
print "You don't have that"
我看到的是:
'Bat' strikes! Your health is down to 95
What do you attack with? >>sword
'Bat' strikes! Your health is down to 91
What do you attack with? >>sword
'Bat' strikes! Your health is down to 87
What do you attack with? >>sword
'Bat' strikes! Your health is down to 85
What do you attack with? >>sword
'Bat' strikes! Your health is down to 82
What do you attack with? >>
这只是不断重复,player.health
甚至不断陷入负面。我找不到错误。此函数是类的方法,player
是另一个类的实例。
答案 0 :(得分:0)
您正在存储方法,而不是存储小写的输入字符串:
player.weapon = (raw_input("What do you attack with? >>").lower)
因为你实际上并没有调用 str.lower()
。您可能不会在str.lower
中存储player.inventory
方法,因此player.inventory.get(player.weapon)
会返回None
。
因为在Python 2中几乎所有东西都可以相对于其他对象进行排序,测试:
player.inventory.get(player.weapon) > 0
始终是False
。
调用该方法至少应解决该问题:
player.weapon = raw_input("What do you attack with? >>").lower()
而不是使用player.inventory.get()
(返回默认设置并屏蔽您的问题),请使用player.inventory[player.weapon]
。这会投出KeyError
来表明用户不会有这个武器,所以调整你的异常处理程序来捕获它:
except KeyError:
print "You don't have that"
答案 1 :(得分:0)
在这一行:
player.weapon = (raw_input("What do you attack with? >>").lower)
它应该是:
player.weapon = (raw_input("What do you attack with? >>").lower())
否则您存储的是函数,而不是结果。 Python将所有内容视为对象
您可能也遇到问题:
while (player.health > 0) or (self.health > 0):
可能是:
while (player.health > 0) *and (self.health > 0):
答案 2 :(得分:-2)
while (player.health > 0) or (self.health > 0):
您可能需要将此片段替换为:
while (player.health > 0) and (self.health > 0):