克里斯保罗 发表于 2019-9-10 13:34:01

class Fighter:
          def __init__(self,name,health,attack):
                  self.name = name
                  self.health = health
                  self.damage_per_attack = attack
          def fight(self,Fb):
                  print(self.name+' attacks '+Fb.name)
                  Fb.health -= self.damage_per_attack
                  print(Fb.name+' now has %d health'%(Fb.health))
if __name__=='__main__':
          def declare_winner(fa,fb,name):
                  if fa.name == name:
                              fa.fight(fb)
                              while fa.health > 0 and fb.health > 0:
                                        fb.fight(fa)
                                        fa.fight(fb)
                  else:
                              fb.fight(fa)
                              while fa.health > 0 and fb.health > 0:
                                        fa.fight(fb)
                                        fb.fight(fa)
                  name = fa.name if fa.health > 0 else fb.name
                  print(name+' wins')
          declare_winner(Fighter("Lew", 10, 2), Fighter("Harry", 5, 4), "Lew")

Geoffreylee 发表于 2020-2-28 14:36:37

class Fighter():
    def __init__(self, name, health, dpa):
      self.name = name
      self.health = health
      self.dpa = dpa

    def attack(self, other):
      other.health -= self.dpa
      if other.health > 0:
            print('{a} attacks {b};{b}now has {c} health.'.format(a=self.name, b=other.name, c=other.health))
      else:
            print('{a} attacks {b};{b}now has {c} health and is dead.'.format(a=self.name, b=other.name, c=other.health))

# 递归实现互相攻击
def declare_winner(fighter_a, fighter_b, name):
    if fighter_a.health < 0:
      return print('{} wins'.format(fighter_b.name))
    elif fighter_b.health < 0:
      return print('{} wins'.format(fighter_a.name))

    if fighter_a.name == name:
      fighter_a.attack(fighter_b)
      declare_winner(fighter_a, fighter_b, fighter_b.name)
    else:
      fighter_b.attack(fighter_a)
      declare_winner(fighter_a, fighter_b, fighter_a.name)


declare_winner(Fighter("Lew", 10, 2), Fighter("Harry", 5, 4), "Harry")

holiday_python 发表于 2020-5-2 22:28:43

学习

19971023 发表于 2020-5-20 09:51:36

1

nononoyes 发表于 2020-9-17 20:49:47

666

wwwwwise 发表于 2021-4-20 21:26:43

1
页: 1 [2]
查看完整版本: Python: 每日一题 50