繁体   English   中英

Python 3:为什么我的课程的函数运行两次?

[英]Python 3: Why does my class' function run twice?

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

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

好吧,如果看起来您实际上在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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM