Tom与Jerry谁先死?

时间:2021-02-01 19:29:52

  有如下问题:Tom的攻击力为113,血量为688,Jerry的攻击力为112,血量为691。每一个回合他们各攻击对方一次,请问谁先死?

  这是一个简单的“人狗大战问题”,我们只要利用类的继承,在原有的基础上稍加改动即可实现:

 

Tom与Jerry谁先死?Tom与Jerry谁先死?
import time

class Hero:
    def __init__(self,name,attack_level,blood):
        self.name = name
        self.attack_level = attack_level
        self.blood = blood

    def attack(self,tar):
        tar.blood = tar.blood - self.attack_level
        print('%s 攻击 %s,%s剩余血量为:%s'%(self.name,tar.name,tar.name,tar.blood) )
        if tar.blood <= 0:
            print('%s Die!Game Over!'%tar.name)
            exit()
         
class People(Hero):
    def __init__(self,name,attack_level,blood):
        super().__init__(name,attack_level,blood)

    def attack(self,tar):
        super().attack(tar)

class Dog(Hero):
    def __init__(self,name,attack_level, blood):
        super().__init__(name,attack_level, blood)

    def attack(self, tar):
        super().attack(tar)

if __name__ == '__main__':
    tom = People('Tom',113,688)
    jerry = Dog('Jerry',112,691)
    while 1:
        tom.attack(jerry)
        time.sleep(1)
        jerry.attack(tom)
        time.sleep(1)
View Code

  演示如下:

Tom与Jerry谁先死?