Turn-based monster team battle simulator

0
Sign in

Write a deterministic simulator for a turn-based battle between two ordered teams of monsters, and return the battle log and the result.

class Monster:
    name: str     # unique within the battle
    health: int   # starting hit points
    attack: int   # damage dealt by one strike

class Team:
    name: str
    monsters: list[Monster]   # in the order they enter the fight

def battle(a: Team, b: Team) -> BattleResult: ...
# BattleResult has: winner (team name, or None for a draw), rounds, log (list of strings)

Rules

  • A team's active monster is its first monster with health above zero. A defeated monster never returns.
  • Each round, Team A's active monster strikes Team B's active monster, reducing its health by the attacker's attack. Then Team B's active monster strikes back the same way.
  • The counterattack happens even if the first strike already took the defender to zero or below. A monster is defeated only after both strikes of the round are done, so both active monsters can fall in the same round.
  • After a defeat, that team's next living monster becomes active.
  • The battle ends when a team has no living monster. If both teams run out in the same round, the result is a draw.

Log

Log every event in order: each monster sent out, each round number, each strike with the defender's health before and after, each defeat, and a final line naming the winner or Draw. For example: Ember attacks Tide for 4 (8 -> 4).

Constraints

  • 0 <= len(team.monsters) <= 1000; 0 <= health, attack <= 10^6.
  • Do not change the caller's Monster objects.
  • The battle must always end, even if no monster can do damage.

Example

Red:  Ember (health 10, attack 4), Blaze (health 6, attack 3)
Blue: Tide  (health 8,  attack 5)

Round 1: Ember hits Tide (8 -> 4), Tide hits Ember (10 -> 5).
Round 2: Ember hits Tide (4 -> 0), Tide still counters and hits Ember (5 -> 0). Both are defeated. Red sends out Blaze; Blue has no monsters left.

Result: Red wins after 2 rounds.

Example 2

A: x (health 5, attack 5)
B: y (health 5, attack 5)

Both monsters fall in round 1 and neither team has a monster left, so the result is a draw.

OpenAICodingMediumLast asked Aug 2026

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.