Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Army Battles by juestr
class Warrior:
def __init__(self):
self.health = 50
self.attack = 5
@property
def is_alive(self):
return self.health > 0
def hit(self, other):
'''Hit other unit, return True if other is dead'''
other.health -= self.attack
return not other.is_alive
class Knight(Warrior):
def __init__(self):
super().__init__()
self.attack = 7
def fight(unit_1, unit_2):
while True:
if unit_1.hit(unit_2): return True
if unit_2.hit(unit_1): return False
class Army:
def __init__(self):
self.units = []
def add_units(self, factory, number):
self.units.extend(factory() for _ in range(number))
def __iter__(self):
return iter(self.units)
class Battle:
# a class for just this is silly
def fight(self, army1, army2):
a1iter = (w for w in army1 if w.is_alive)
a2iter = (w for w in army2 if w.is_alive)
w1 = next(a1iter, None)
w2 = next(a2iter, None)
while True:
if w1 is None: return False
if w2 is None: return True
if fight(w1, w2):
w2 = next(a2iter, None)
else:
w1 = next(a1iter, None)
April 13, 2019
Comments: