Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
"The Defenders" solution in Clear category for The Defenders by Vitaly_Titkov
# Taken from mission Army Battles
class Warrior:
health = 50
attack = 5
@property
def is_alive(self):
return self.health > 0
def hurt(self, attack):
self.health -= attack
class Defender(Warrior):
health = 60
attack = 3
defence = 2
def hurt(self, attack):
if attack > self.defence:
self.health -= (attack - self.defence)
else:
pass
class Knight(Warrior):
attack = 7
def fight(unit_1, unit_2):
startPair = [unit_1, unit_2]
while unit_1.health > 0 and unit_2.health > 0:
unit_2.hurt(unit_1.attack)
if unit_2.health > 0:
unit_1, unit_2 = unit_2, unit_1
return startPair[0].is_alive
def fight1(unit_1, unit_2):
startPair = [unit_1, unit_2]
while unit_1.health > 0 and unit_2.health > 0:
unit_2.hurt(unit_1.attack)
if unit_2.health > 0:
unit_1, unit_2 = unit_2, unit_1
return startPair
class Army():
def __init__(self):
self.capacity = []
def add_units(self, unit, number):
for i in range(number):
self.capacity.append(unit())
@property
def is_alive(self):
return len(self.capacity) > 0
class Battle():
def __init__(self):
pass
def fight(self, army1, army2):
while len(army1.capacity) > 0 and len(army2.capacity) > 0:
a = fight1(army1.capacity.pop(0), army2.capacity.pop(0))
if a[0].health > 0:
army1.capacity.insert(0, a[0])
else:
army2.capacity.insert(0, a[1])
return army1.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()
bob = Defender()
mike = Knight()
rog = Warrior()
lancelot = Defender()
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
assert fight(bob, mike) == False
assert fight(lancelot, rog) == True
# battle tests
my_army = Army()
my_army.add_units(Defender, 1)
enemy_army = Army()
enemy_army.add_units(Warrior, 2)
army_3 = Army()
army_3.add_units(Warrior, 1)
army_3.add_units(Defender, 1)
army_4 = Army()
army_4.add_units(Warrior, 2)
battle = Battle()
assert battle.fight(my_army, enemy_army) == False
assert battle.fight(army_3, army_4) == True
print("Coding complete? Let's try tests!")
Nov. 18, 2020