0

我有一个包含此攻击功能的类:

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()
4

1 回答 1

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")
于 2013-05-31T00:59:58.240 回答