2b3e815module-07(ex2): refactor and cleanup
2 files changed, +35, -62
author
mogi <git@mogiya.dev> on 21-05-2026 16:12 UTC+1
committer
mogi <git@mogiya.dev> on 21-05-2026 16:12 UTC+1
parentdc3a336
    @@ -1,18 +1,17 @@
 1 1 from abc import ABC, abstractmethod
 2  -from typing import cast
 3  -from ex0.creature import Creature
 4  -from ex1.capabilities import HealCapability, TransformCapability
   2+from ex0 import Creature
   3+from ex1 import HealCapability, TransformCapability
 5 4 from .exceptions import InvalidStrategyError
 6 5 
 7 6 
 8 7 class BattleStrategy(ABC):
 9 8     @abstractmethod
10  -    def act(self, creature: Creature) -> None:
11  -        pass
   9+    def is_valid(self, creature: Creature) -> bool:
  10+        ...
1211 
1312     @abstractmethod
14  -    def is_valid(self, creature: Creature) -> bool:
15  -        pass
  13+    def act(self, creature: Creature) -> None:
  14+        ...
1615 
1716 
1817 class NormalStrategy(BattleStrategy):
    @@ -20,6 +19,11 @@ class NormalStrategy(BattleStrategy):
2019         return True
2120 
2221     def act(self, creature: Creature) -> None:
  22+        if not self.is_valid(creature):
  23+            raise InvalidStrategyError(
  24+                f"Invalid Creature '{creature._name}'"
  25+                "for this normal strategy"
  26+            )
2327         print(creature.attack())
2428 
2529 
    @@ -33,10 +37,10 @@ class AggressiveStrategy(BattleStrategy):
3337                 f"Invalid creature '{creature._name}' "
3438                 "for this aggressive strategy"
3539             )
36  -        transform = cast(TransformCapability, creature)
37  -        print(transform.transform())
  40+        assert isinstance(creature, TransformCapability)
  41+        print(creature.transform())
3842         print(creature.attack())
39  -        print(transform.revert())
  43+        print(creature.revert())
4044 
4145 
4246 class DefensiveStrategy(BattleStrategy):
    @@ -47,8 +51,8 @@ class DefensiveStrategy(BattleStrategy):
4751         if not self.is_valid(creature):
4852             raise InvalidStrategyError(
4953                 f"Invalid creature '{creature._name}' "
50  -                "for this aggressive strategy"
  54+                "for this defensive strategy"
5155             )
52  -        heal = cast(HealCapability, creature)
  56+        assert isinstance(creature, HealCapability)
5357         print(creature.attack())
54  -        print(heal.heal())
  58+        print(creature.heal())
      @@ -19,22 +19,15 @@ from ex2 import (
 19 19 def battle(opponents: list[tuple[CreatureFactory, BattleStrategy]]) -> None:
 20 20     print("*** Tournament ***")
 21 21     print(f"{len(opponents)} opponents involved")
 22   -
 23   -    for i in range(len(opponents)):
 24   -        for j in range(i + 1, len(opponents)):
 25   -
 26   -            factory1, strategy1 = opponents[i]
 27   -            factory2, strategy2 = opponents[j]
 28   -
 29   -            creature1 = factory1.create_base()
 30   -            creature2 = factory2.create_base()
 31   -
    22+    fighters = [(factory.create_base(), strat) for factory, strat in opponents]
    23+    for i in range(len(fighters)):
    24+        for j in range(i + 1, len(fighters)):
    25+            creature1, strategy1 = fighters[i]
    26+            creature2, strategy2 = fighters[j]
 32 27             print("\n* Battle *")
 33   -
 34 28             print(creature1.describe())
 35 29             print(" vs.")
 36 30             print(creature2.describe())
 37   -
 38 31             print(" now fight!")
 39 32             strategy1.act(creature1)
 40 33             strategy2.act(creature2)
      @@ -45,29 +38,24 @@ def run_tournament(
 45 38 ) -> None:
 46 39     try:
 47 40         battle(opponents)
 48   -    except InvalidStrategyError as error:
    41+    except InvalidStrategyError as e:
 49 42         print(
 50   -            f"Battle error, aborting tournament: {error}"
    43+            f"Battle error, aborting tournament: {e}"
 51 44         )
 52 45 
 53 46 
 54 47 def main() -> None:
    48+    normal = NormalStrategy()
    49+    aggressive = AggressiveStrategy()
    50+    defensive = DefensiveStrategy()
    51+
 55 52     print("Tournament 0 (basic)")
 56 53     print(
 57 54         " [ (Flameling+Normal), (Healing+Defensive) ]"
 58 55     )
 59 56     run_tournament(
 60   -        [
 61   -            (
 62   -                FlameFactory(),
 63   -                NormalStrategy()),
 64   -            (
 65   -                HealingCreatureFactory(),
 66   -                DefensiveStrategy()
 67   -            )
 68   -        ]
    57+        [(FlameFactory(), normal), (HealingCreatureFactory(), defensive)]
 69 58     )
 70   -
 71 59     print()
 72 60 
 73 61     print("Tournament 1 (error)")
      @@ -75,38 +63,19 @@ def main() -> None:
 75 63         " [ (Flameling+Aggressive), (Healing+Defensive) ]"
 76 64     )
 77 65     run_tournament(
 78   -        [
 79   -            (
 80   -                FlameFactory(),
 81   -                AggressiveStrategy()),
 82   -            (
 83   -                HealingCreatureFactory(),
 84   -                DefensiveStrategy()
 85   -            )
 86   -        ]
    66+        [(FlameFactory(), aggressive), (HealingCreatureFactory(), defensive)]
 87 67     )
 88   -
 89 68     print()
 90 69 
 91 70     print("Tournament 2 (multiple)")
 92 71     print(
 93 72         " [ (Aquabub+Normal), (Healing+Defensive), (Transform+Aggressive) ]"
 94 73     )
 95   -    run_tournament(
 96   -        [
 97   -            (
 98   -                AquaFactory(),
 99   -                NormalStrategy()),
100   -            (
101   -                HealingCreatureFactory(),
102   -                DefensiveStrategy()
103   -            ),
104   -            (
105   -                TransformCreatureFactory(),
106   -                AggressiveStrategy()
107   -            )
108   -        ]
109   -    )
    74+    run_tournament([
    75+        (AquaFactory(), normal),
    76+        (HealingCreatureFactory(), defensive),
    77+        (TransformCreatureFactory(), aggressive)
    78+    ])
110 79 
111 80 
112 81 if __name__ == "__main__":