Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Clear OOP Solution (ready for next challenges of the saga) solution in Clear category for The Vampires by bsquare
from collections import deque
class Warrior:
_max_health = 50
def __init__(self, attack=5):
self._army = None
self._health = self._max_health
self._attack = attack
def join_army(self, army):
self._army = army
return self
@property
def health(self):
return self._health
@health.setter
def health(self, new_health):
self._health = min(new_health, self._max_health)
if not self.is_alive and self._army is not None:
self._army.notify_dead_warrior(self)
@property
def attack(self):
return self._attack
@attack.setter
def attack(self, new_attack):
self._attack = new_attack
@property
def is_alive(self):
return self.health > 0
def manage_hit(self, hit_power):
self.health -= hit_power
return hit_power
def hit(self, target):
return target.manage_hit(self._attack)
def fight(self, target):
attacking_unit, target_unit = self, target
while attacking_unit.is_alive and target_unit.is_alive:
attacking_unit.hit(target_unit)
attacking_unit, target_unit = target_unit, attacking_unit
return self.is_alive
def __str__(self):
return f"Type={self.__class__.__name__}; Health={self.health}; Attack={self._attack}"
class Knight(Warrior):
def __init__(self):
super().__init__(attack=7)
class Defender(Warrior):
_max_health = 60
def __init__(self, attack=3, defense=2):
super().__init__(attack=attack)
self._defense = defense
def manage_hit(self, hit_power):
return super().manage_hit(hit_power - self._defense)
def __str__(self):
return super().__str__() + f"; Defense={self._defense}"
class Vampire(Warrior):
_max_health = 40
def __init__(self):
super().__init__(attack=4)
self._vampirism = 50
def hit(self, target):
removed_health = super().hit(target)
self.health += self._vampirism * removed_health // 100
def __str__(self):
return super().__str__() + f"; Vampirism={self._vampirism}"
class Army(deque):
army_number = 0
def __init__(self):
super().__init__()
Army.army_number += 1
self._army_number = Army.army_number
@property
def units(self):
return self
def add_units(self, cls, unit_count):
self.extend(cls().join_army(self) for _ in range(unit_count))
@property
def is_alive(self):
return bool(len(self))
def notify_dead_warrior(self, warrior):
self.remove(warrior)
def fight(self, target):
attacking_army, target_army = self, target
while attacking_army.is_alive and target_army.is_alive:
attacking_army[0].fight(target_army[0])
return self.is_alive
def __str__(self):
return f"Army #{self._army_number}: " + "; ".join([f"({unit})" for unit in self])
# Defines cosmetic functions/methods to fit challenge requirements.
class Battle:
fight = staticmethod(Army.fight)
fight = Warrior.fight
Sept. 14, 2019
Comments: