Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Army Battles by TheRing
from typing import Type
class Warrior:
def __init__(self):
self.health = 50
self.attack = 5
@property
def is_alive(self) -> bool:
return self.health > 0
class Knight(Warrior):
def __init__(self):
Warrior.__init__(self)
self.attack = 7
class Army:
def __init__(self):
self.warriors = []
def add_units(self, warrior_class: Type[Warrior], n: int):
self.warriors.extend(warrior_class() for _ in range(n))
def fight(unit_1: Warrior, unit_2: Warrior) -> bool:
while True:
if unit_1.is_alive:
unit_2.health -= unit_1.attack
else:
return False
if unit_2.is_alive:
unit_1.health -= unit_2.attack
else:
return True
class Battle:
def fight(self, army_1: Army, army_2: Army) -> bool:
while army_1.warriors and army_2.warriors:
if fight(army_1.warriors[0], army_2.warriors[0]):
army_2.warriors.pop(0)
else:
army_1.warriors.pop(0)
return bool(army_1.warriors)
June 7, 2023