Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Army Battles by mikaeldovbnia
class Warrior:
life = 50
attack = 5
is_alive = True
class Knight(Warrior):
life = 50
attack = 7
is_alive = True
def fight(By, Uk):
while True:
Uk.life -= By.attack
if Uk.life <= 0:
Uk.is_alive = False
return By.is_alive
By.life -= Uk.attack
if By.life <= 0:
By.is_alive = False
return By.is_alive
class Army:
def __init__(self):
self.w = []
def add_units(self, a, c):
for _ in range(c):
self.w.append(a())
def death(self):
self.w.pop()
class Battle:
def fight(s, at, de):
while len(at.w) > 0 and len(de.w) > 0:
if fight(at.w[-1], de.w[-1]):
de.death()
elif fight(de.w[-1], at.w[-1]):
at.death()
if len(de.w) == 0:
return True
return False
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 12, 2022