Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for The Defenders by PythonLearner
class Warrior(object):
def __init__(self):
self.health = 50
self.attack = 5
@property
def is_alive(self):
return self.health > 0
def take_attack(self, unit):
unit.get_wounded(self)
def get_wounded(self, unit):
self.health -= unit.attack
class Knight(Warrior):
def __init__(self):
super().__init__()
self.attack = 7
class Defender(Warrior):
def __init__(self):
super().__init__()
self.health = 60
self.attack = 3
self.defense = 2
def get_wounded(self, unit):
if unit.attack > self.defense:
self.health -= unit.attack-self.defense
class Army(object):
def __init__(self):
self.army = []
self.casualties = 0
@property
def army_size(self):
return len(self.army)-self.casualties
@property
def is_anyone_alive(self):
return self.army_size > 0
def add_units(self, unit_class, number):
self.army.extend(unit_class() for _ in range(number))
def get_unit(self, index):
return self.army[index]
def fight(unit1, unit2):
attacker, attacked = unit1, unit2
while unit1.is_alive and unit2.is_alive:
attacker.take_attack(attacked)
attacker, attacked = attacked, attacker
return unit1.is_alive
class Battle(object):
def duel(self, unit1, unit2):
return fight(unit1, unit2)
def fight(self, army1, army2):
unit1_index = 0
unit2_index = 0
while army1.is_anyone_alive and army2.is_anyone_alive:
if self.duel(army1.get_unit(unit1_index), army2.get_unit(unit2_index)):
army2.casualties += 1
if army2.is_anyone_alive:
unit2_index += 1
else:
army1.casualties += 1
if army1.is_anyone_alive:
unit1_index += 1
return army1.is_anyone_alive
Aug. 23, 2018
Comments: