Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Generators and Zip solution in Clear category for Army Battles by ayubutrym
class Warrior:
attack = 5
def __init__(self, health=50):
self.health = health
@property
def is_alive(self):
return self.health > 0
def hit(self, other):
other.accept_damage(self.attack)
def accept_damage(self, damage):
self.health -= damage
class Knight(Warrior):
attack = 7
def fight(unit1, unit2):
attacker, defender = unit1, unit2
while attacker.is_alive:
attacker.hit(defender)
attacker, defender = defender, attacker
return unit1.is_alive
class Army:
def __init__(self):
self._troops = []
def add_units(self, unit_type, number):
for _ in range(number):
self._troops.append(unit_type())
def first_alive(self):
for unit in self._troops:
while unit.is_alive:
yield unit
class Battle:
def fight(self, army1, army2):
for (attacker, defender) in zip(army1.first_alive(), army2.first_alive()):
fight(attacker, defender)
return attacker.is_alive
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 6, 2022