Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Reversed stack for cheaper units removing solution in Clear category for Army Battles by romeech
class Warrior(object):
def __init__(self):
self.health = 50
self.attack = 5
@property
def is_alive(self):
return self.health > 0
class Knight(Warrior):
def __init__(self):
super().__init__()
self.attack = 7
def fight(red, blue):
while red.is_alive and blue.is_alive:
blue.health -= red.attack
if blue.is_alive:
red.health -= blue.attack
return red.is_alive
class Army(object):
def __init__(self):
self.__units = []
def add_units(self, fighter_class, amount):
self.__units.extend([fighter_class() for _ in range(amount)])
def prepare_to_battle(self):
self.__units = self.__units[::-1]
def has_units(self):
return bool(len(self.__units))
def get_active_fighter(self):
return self.__units[-1]
def remove_active_fighter(self):
self.__units.pop()
class Battle(object):
@staticmethod
def fight(red_army, blue_army):
while red_army.has_units() and blue_army.has_units():
left = red_army.get_active_fighter()
right = blue_army.get_active_fighter()
if fight(left, right):
blue_army.remove_active_fighter()
else:
red_army.remove_active_fighter()
return red_army.has_units()
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
# fight tests
chuck = Warrior()
bruce = Warrior()
carl = Knight()
dave = Warrior()
mark = Warrior()
assert fight(chuck, bruce) is True
assert fight(dave, carl) is False
assert chuck.is_alive is True
assert bruce.is_alive is False
assert carl.is_alive is True
assert dave.is_alive is False
assert fight(carl, mark) is False
assert carl.is_alive is False
# battle tests
my_army = Army()
my_army.add_units(Knight, 3)
enemy_army = Army()
enemy_army.add_units(Warrior, 3)
army_3 = Army()
army_3.add_units(Warrior, 20)
army_3.add_units(Knight, 5)
army_4 = Army()
army_4.add_units(Warrior, 30)
battle = Battle()
assert battle.fight(my_army, enemy_army) is True
assert battle.fight(army_3, army_4) is False
print("Coding complete? Let's try tests!")
Jan. 22, 2020