Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Army Battles by koolprashant2000
# Taken from mission The Warriors
from itertools import chain
class Army:
def __init__(self):
self.units = []
def add_units(self, warrior, num_warriors):
'''Add warrior units to the army '''
self.units += [warrior() for _ in range(num_warriors)]
class Battle:
def fight(self, army1, army2):
''' Engage army1 against army2 and decide the winner
winner: army1 returns True
winner: army2 returns False
'''
army1_unit = iter(army1.units)
army2_unit = iter(army2.units)
soldier1 = next(army1_unit)
soldier2 = next(army2_unit)
while True:
try:
if fight(soldier1, soldier2):
soldier2 = next(army2_unit)
else:
soldier1 = next(army1_unit)
except StopIteration:
return soldier1.is_alive
class Warrior:
def __init__(self):
self.health = 50
self.attack = 5
self.is_alive = True
def fight(self, warrior):
warrior.health -= self.attack
warrior.is_alive = warrior.health > 0
class Knight(Warrior):
def __init__(self):
Warrior.__init__(self)
self.attack = 7
def fight(unit_1, unit_2):
while unit_1.is_alive and unit_2.is_alive:
unit_1.fight(unit_2)
if unit_2.is_alive:
unit_2.fight(unit_1)
return True if unit_1.is_alive else False
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
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
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!")
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!")
March 28, 2020