功能运行不正常

2024-04-19 18:53:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个基于python2.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是另一个类的实例。你知道吗


Tags: toselfyouyouriswithdowhat
3条回答
while (player.health > 0) or (self.health > 0):

可能,您需要将此片段替换为:

while (player.health > 0) and (self.health > 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):

您存储的是一个方法,而不是小写输入字符串:

player.weapon = (raw_input("What do you attack with? >>").lower)

因为你没有在那里打电话。您可能没有存储在player.inventory中的str.lower方法,因此player.inventory.get(player.weapon)返回None。你知道吗

因为在Python2中,几乎所有东西都可以相对于其他对象排序,所以测试:

 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"

相关问题 更多 >