Turn-Based Squad Combat Engine with Deterministic Ordering
Data Structure DesignModel answerLast updated
Simulate a fight between two squads of monsters with fixed turn order, weakest-first targeting and a damage formula, and return the ordered list of attack events.
Squad Combat Engine
You are writing the battle core for a creature-fighting game. Every creature (a "monster") has these attributes: id, hp, attack, defense, speed, plus a multiplier that defaults to 1.0.
Two squads fight until one has nobody left. Implement simulate_battle(team_a, team_b) (you may back it with a BattleSimulator class) that returns the attack events in the order they happened.
class Monster:
def __init__(self, id, hp, attack, defense, speed):
self.id = id
self.hp = hp
self.attack = attack
self.defense = defense
self.speed = speed
self.multiplier = 1.0
def simulate_battle(team_a, team_b):
# returns a list of strings such as
# "Monster 1 attacked Monster 4 for 10 damage"
pass
Rules
- Acting order. A battle proceeds in rounds. Within a round, living monsters from both squads act one at a time, from highest
speedto lowest. Equal speeds are broken by the smalleridgoing first. - Choosing a target. The acting monster attacks the enemy with the lowest current
hp. If several enemies share that value, it picks the one with the smallestid. - Damage.
damage = max(1, attacker.attack * attacker.multiplier - target.defense). The multiplier scales the attack value before the defense is subtracted. Damage must be an integer, so round the scaled attack down. - Defeat. A monster whose
hpreaches 0 or below leaves its squad immediately. - End of battle. The fight stops as soon as one squad has no monsters left, even in the middle of a round.
Example
Squad A: {id: 1, hp: 50, atk: 20, def: 5, spd: 10}
Squad B: {id: 2, hp: 30, atk: 10, def: 5, spd: 5}
Monster 1 is faster, so it attacks first and deals 20 - 5 = 15, leaving Monster 2 at 15 hp. The fight continues from there.
Constraints
- Each squad holds 1 to 5 monsters.
hp > 0, and every stat is an integer from 1 to 100.- Ids are unique across both squads.
What to cover
Give your approach, explain any ambiguity you resolve and how, state the complexity, and provide working code. Also discuss how you would extend it to area-of-effect attacks and how you would make it fast enough to run thousands of battles.
Hints
Hint 1
Treat each round as a snapshot: sort all living monsters once by (-speed, id), then walk that list. What must you check before a monster in the snapshot actually acts?
Hint 2
Use a tuple key such as (current_hp, id) with min() for targeting, and keep hp in a separate map so the caller's Monster objects are not changed and re-runs are safe.
Hint 3
Check for an empty enemy squad right after every kill, not only at the end of a round. Also argue why the loop must terminate: every hit deals at least 1 damage and total hp is finite.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a deterministic simulation. There is no clever algorithm to find. The score comes from exact state handling, exact tie-breaking and clearly stated assumptions.
Decisions to state up front
- Multiplier meaning. "Scale before subtracting defense" gives
damage = max(1, floor(attack * multiplier) - defense). Flooring keeps hp and log lines as integers. With the default1.0it reduces tomax(1, attack - defense), which matches the example. - No mutation of inputs. Keep live hp in a dictionary keyed by id, so the caller's objects stay unchanged and the same teams can be simulated again.
- Unique ids. They serve as tie-breakers and as dictionary keys, so confirm they are unique across both squads.
Algorithm
- Build a squad list for each side, a map
id -> side, and a mapid -> current hp. - While both squads are non-empty, start a round. Sort all living monsters by
(-speed, id). This is the round's turn list. - For each monster in the turn list:
- If its hp is 0 or less, skip it, because it was killed earlier in this round.
- Pick the target as the enemy minimizing
(hp, id), using current hp. - Compute the damage, subtract it from the target's hp, and append the event string.
- If the target's hp is 0 or less, remove it from its squad. If that squad is now empty, return the events immediately.
- If the loop ends because a squad was empty at the start, return whatever has been collected (for empty input,
[]).
Why it is correct
- Order. The sort key implements rule 1 exactly, and recomputing it each round drops monsters that have died. Speed never changes, so one sort per round is enough.
- Dead monsters never act. The turn list is a snapshot taken at the start of the round. The hp check enforces "removed immediately" for monsters that die mid-round.
- Targeting.
minover(hp, id)reads current hp, so damage dealt earlier in the same round affects later choices. - Termination. Each attack removes at least 1 hp, and total hp is bounded (at most 5 x 100 per side). So the number of attacks is finite, and one side must eventually be empty. No iteration cap is needed.
- Early stop. Returning at the moment a squad empties guarantees no events appear after the outcome is decided.
Complexity
Let n be the total monster count (at most 10) and H the total starting hp (at most 1,000).
- Time: O(H * n). There are at most H attacks, each with an O(n) target scan. Sorting once per round adds O(n log n) per round, and there are at most H rounds, so it fits within the same bound.
- Space: O(n) for state, plus O(H) for the event log.
With these limits the run time is trivial. The point of the exercise is correctness.
Code
import math
from typing import List
class Monster:
def __init__(self, id, hp, attack, defense, speed):
self.id = id
self.hp = hp
self.attack = attack
self.defense = defense
self.speed = speed
self.multiplier = 1.0
class BattleSimulator:
def __init__(self, team_a: List[Monster], team_b: List[Monster]):
self.squads = [list(team_a), list(team_b)]
self.side = {m.id: 0 for m in team_a}
self.side.update({m.id: 1 for m in team_b})
self.hp = {m.id: m.hp for m in team_a + team_b}
def _damage(self, attacker: Monster, target: Monster) -> int:
scaled = math.floor(attacker.attack * attacker.multiplier)
return max(1, scaled - target.defense)
def _choose_target(self, enemies: List[Monster]) -> Monster:
return min(enemies, key=lambda m: (self.hp[m.id], m.id))
def run(self) -> List[str]:
log = []
while self.squads[0] and self.squads[1]:
turn_list = sorted(self.squads[0] + self.squads[1],
key=lambda m: (-m.speed, m.id))
for actor in turn_list:
if self.hp[actor.id] <= 0:
continue
enemies = self.squads[1 - self.side[actor.id]]
target = self._choose_target(enemies)
dmg = self._damage(actor, target)
self.hp[target.id] -= dmg
log.append(f"Monster {actor.id} attacked Monster "
f"{target.id} for {dmg} damage")
if self.hp[target.id] <= 0:
enemies.remove(target)
if not enemies:
return log
return log
def simulate_battle(team_a, team_b):
return BattleSimulator(team_a, team_b).run()
On the sample, the log is:
Monster 1 attacked Monster 2 for 15 damage(Monster 2 at 15)Monster 2 attacked Monster 1 for 5 damage(Monster 1 at 45)Monster 1 attacked Monster 2 for 15 damage(Monster 2 at 0, removed, battle over)
Edge cases
- Defense at or above attack: the floor of 1 still applies, so the fight is slow but finite.
- Killed before acting: skipped via the hp check.
- Squad wiped mid-round: return immediately, and the remaining actors do not act.
- Ties: speed ties and hp ties both fall back to the lower id, across squads as well.
- Empty squad as input: the battle is already over, so return
[]. - Overkill: hp may go negative. Log the computed damage, not a value clamped to remaining hp, unless told otherwise.
- Fractional or sub-1 multipliers: floor first, then apply
max(1, ...).
Common mistakes
- Forgetting to skip monsters that died earlier in the same round.
- Removing a unit from a list while iterating over that same list.
- Sorting once before the battle and never filtering out the dead.
- Using original hp instead of current hp when picking targets.
- Mutating the caller's monsters, which breaks repeated runs.
- Checking for victory only at the end of a round.
Follow-ups
Area-of-effect attacks. Add an attack type or ability list to Monster, and move targeting into _select_targets(actor, enemies) -> List[Monster]. Single-target returns the weakest enemy. AoE returns a snapshot copy of the enemy list. Apply damage to each target and log one event per hit. Collect the dead and remove them after the loop, then check for termination once the whole attack resolves.
Running thousands of battles for balance testing.
- With 5 monsters per side, linear scans are already near optimal, so constant factors matter more than big-O.
- Replace objects and dicts with parallel arrays (hp, defense, alive mask), or NumPy arrays.
- Since speed is static, compute the turn order once per battle and skip dead entries while iterating.
- Skip string formatting in bulk runs. Record tuples, or only the winner.
- For much larger squads, keep a min-heap per squad keyed by
(hp, id)with lazy invalidation, giving O(log n) target selection. - Battles are independent, so they parallelize trivially across processes.