Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Army Battles by shadowpanther
# Taken from mission The Warriors
class Warrior:
health = 50
attack = 5
is_alive = True
def take_damage(self, damage):
self.health -= damage
if self.health <= 0:
self.is_alive = False
class Knight(Warrior):
attack = 7
class Army:
def __init__(self):
self.units = []
def add_units(self, unit_class, unit_count):
for i in range(unit_count):
self.units.append((unit_class)())
class Battle:
def fight(self, army_1, army_2):
while len(army_1.units) > 0 and len(army_2.units) > 0:
fight(army_1.units[0], army_2.units[0])
if not army_1.units[0].is_alive:
del(army_1.units[0])
if not army_2.units[0].is_alive:
del(army_2.units[0])
return len(army_1.units) > 0
def fight(unit_1, unit_2):
turn_1 = True
while unit_1.is_alive and unit_2.is_alive:
if turn_1:
unit_2.take_damage(unit_1.attack)
else:
unit_1.take_damage(unit_2.attack)
turn_1 = not turn_1
return unit_1.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!")
Aug. 22, 2018