Python 3:为什么我的类'函数运行两次?

时间:2013-05-31 00:01:52

标签: python

我有一个包含此攻击函数的类:

def attack(self, victim):
    strike = 0
    if victim.strength > self.strength:
        strike = 40
    else:
        strike = 70
    successChance = randint(1,100)
    if successChance > strike:
        self.lives -= 1
        return False
    else:
        victim.lives -= 1
        return True

每次用户按下一个按钮时,它应该只运行一次,但是它会运行两次,这意味着每次按下按钮都会计为两次。我知道错误在我的类函数中,因为错误发生在类的测试运行期间。

调用该函数的类中唯一的代码是我的测试函数,它只在内部运行。但问题仍存在于我的GUI代码中。

这是我的班级职能:

class Player(object):

def __init__(self, name="", lives=DEFAULT_LIVES):
    self._name = name
    self.lives = lives
    self.strength = randint(1,10)
    if self._name== "Test":
        self.lives = 1000
    if self._name== "":
        self._name = "John Smith"
def __str__(self):
    return (self._name +  " Life: " + str(self.lives) + " Strength: " + str(self.strength))

def getLives(self):
    return self.lives

def getStrength(self):
    self.strength = randint(1,10)
    return self.strength

def getName(self):
    return self._name

def isAlive(self):
    if self.lives <= 0:
       return False
    return True

def attack(self, victim):
    if victim.strength > self.strength:
        strike = 40
    else:
        strike = 70
    successChance = randint(1,100)
    if successChance > strike:
        print(successChance)
        self.lives -= 1
        return False
    else:
        print(successChance)
        victim.lives -= 1
        return True


def test():
    player = Player("Tyler")
    opponent = Player(choice(opponentList))
    while player.isAlive() == True and opponent.isAlive() == True:
        print(player)
        print(opponent)
        player.attack(opponent)
        player.isAlive()
        opponent.isAlive()
        if not player.attack(opponent):
            print("You lost")
        else:
            print("You won")
    print("Game Over")

if __name__ == '__main__':
    test()

1 个答案:

答案 0 :(得分:4)

好吧,看起来你实际上是在test()中调用了两次函数:

#your old code:
while player.isAlive() == True and opponent.isAlive() == True:
    print(player)
    print(opponent)
    player.attack(opponent) #called once here
    player.isAlive()
    opponent.isAlive()
    if not player.attack(opponent):#called 2nd time here
        print("You lost")
    else:
        print("You won")
print("Game Over")

我试试这个:

while player.isAlive() and opponent.isAlive():
    print(player)
    print(opponent)
    player_attack_was_successful = player.attack(opponent)
    #player.isAlive() #(does this line even do anything?)
    #opponent.isAlive()
    if player_attack_was_successful:
        print("You won")
    else:
        print("You lost")
print("Game Over")
相关问题