~/problems / Simulation & OOP design / Object-oriented design and extensible simulations

Monster team battle

easy 3 levels ~40 min OpenAI

Level 1 Turn-based team battle

Model a fight between two teams of monsters. Write three pieces:

  • Monster(name, health, attack): health and attack are positive ints. Give it is_alive() -> bool (health above 0) and take_damage(amount) (subtract from health; health may go negative).
  • Team(name, monsters): keeps its list of monsters in order. Give it first_alive() -> Monster | None and is_defeated() -> bool (no monster alive).
  • battle(team_a, team_b) -> list[str]: run the fight and return the event log.

Rules:

  1. team_a moves first; the teams then alternate, one hit per turn.
  2. On a turn, the attacking team's first living monster hits the defending team's first living monster. The defender loses health equal to the attacker's attack. There is no counter-damage.
  3. A monster whose health drops to 0 or below is out. The fight stops as soon as one team has no monster left.

The battle mutates the monsters (their health goes down). Each team starts with at least one monster.

Log lines, exactly:

  • first: "Start: <team_a name> vs <team_b name>"
  • each hit that leaves the target alive: "<attacker> hits <target> for <damage>, <target> has <hp> HP left"
  • each hit that knocks it out: "<attacker> hits <target> for <damage>, <target> is out"
  • last: "Winner: <team name>"
a = Team("Red", [Monster("Ogre", 30, 12)])
b = Team("Blue", [Monster("Imp", 20, 5), Monster("Bat", 5, 3)])
battle(a, b)
# ["Start: Red vs Blue",
#  "Ogre hits Imp for 12, Imp has 8 HP left",
#  "Imp hits Ogre for 5, Ogre has 25 HP left",
#  "Ogre hits Imp for 12, Imp is out",
#  "Bat hits Ogre for 3, Ogre has 22 HP left",
#  "Ogre hits Bat for 12, Bat is out",
#  "Winner: Red"]

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Topic: Object-oriented design and extensible simulations. Classes that survive new requirements: games, payments, subscriptions, refactors.

0:00
Ctrl ' run · Ctrl ↵ submit
esc