Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
40-liner: limited looping solution in Speedy category for Army Battles by przemyslaw.daniel
class Warrior:
def __init__(self, health=50, attack=5):
self.health, self.attack = health, attack
@property
def is_alive(self):
return self.health > 0
class Knight(Warrior):
def __init__(self):
super().__init__(attack=7)
def fight(unit_1, unit_2):
''' Do not iterate here as we can calculate final health '''
my_steps_to_die = -(-unit_1.health // unit_2.attack)
enemy_steps_to_die = -(-unit_2.health // unit_1.attack)
steps = min(my_steps_to_die, enemy_steps_to_die)
if my_steps_to_die >= enemy_steps_to_die:
unit_1.health -= (steps-1)*unit_2.attack
unit_2.health = 0
return True
unit_2.health -= steps*unit_1.attack
unit_1.health = 0
return False
class Army(list):
def add_units(self, unit_type, amount):
self += [unit_type() for _ in range(amount)]
class Battle:
@staticmethod
def fight(army1, army2):
army1, army2 = army1[::-1], army2[::-1]
amries = [army1, army2]
while all(amries):
amries[fight(army1[-1], army2[-1])].pop()
return bool(army1)
Nov. 22, 2018