Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Army Battles by viktor.chyrkin
class Warrior:
attack: int = 5
def __init__(self):
self.health = 50
self.is_alive = True
class Knight(Warrior):
attack = 7
class Army:
def __init__(self):
self.a = []
def add_units(self, typ, amo):
self.a.extend([typ for _ in range(amo)])
def fight(unit_1, unit_2):
while unit_1.is_alive and unit_2.is_alive:
unit_2.health -= unit_1.attack
if unit_2.health <= 0:
unit_2.is_alive = False
else:
unit_1.health -= unit_2.attack
if unit_1.health <= 0:
unit_1.is_alive = False
return unit_1.is_alive
class Battle:
def fight(self, ay1, ay2):
w1 = ay1.a[0]()
w2 = ay2.a[0]()
while ay1.a and ay2.a:
if w1.health <= 0:
w1 = ay1.a[0]()
if w2.health <= 0:
w2 = ay2.a[0]()
if fight(w1, w2):
ay2.a = ay2.a[1:]
else:
ay1.a = ay1.a[1:]
return bool(ay1.a)
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) == True
assert fight(dave, carl) == False
assert chuck.is_alive == True
assert bruce.is_alive == False
assert carl.is_alive == True
assert dave.is_alive == False
assert fight(carl, mark) == False
assert carl.is_alive == 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) == True
assert battle.fight(army_3, army_4) == False
print("Coding complete? Let's try tests!")
July 11, 2022