Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Army Battles by stics_232
class Warrior:
# Warrior class
def __init__(self):
self.health = 50
self.damage = 5
@property
def is_alive(self):
return self.health > 0
def take_damage(self, dmg):
# Takes damage
self.health = self.health - dmg
def attack(self, target):
# Attacks target
target.take_damage(self.damage)
class Knight(Warrior):
# Knight class
def __init__(self):
super().__init__()
self.damage = 7
class Army():
def __init__(self):
self.army = list()
@property
def is_alive(self):
return True if self.next_unit() else False
def add_units(self, unit_type, count):
for x in range(count):
self.army.append(unit_type())
def next_unit(self):
# Returns next alive unit in army
if self.army:
for unit in self.army:
if not unit.is_alive:
self.army.remove(unit)
return self.army[0] if self.army else None
class Battle():
def fight(self, army_1, army_2):
while True:
if army_1.is_alive:
unit_1 = army_1.next_unit()
else:
return False
if army_2.is_alive:
unit_2 = army_2.next_unit()
else:
return True
fight(unit_1, unit_2)
def fight(unit_1, unit_2):
# Fight continues before someone dead
while True:
unit_1.attack(unit_2)
if not unit_2.is_alive:
return True
unit_2.attack(unit_1)
if not unit_1.is_alive:
return False
July 2, 2020