Simulate Monster Team Battles
MetaMachine Learning Engineer · Technical ScreenLast updated
This question tests the ability to implement a stateful, turn-based simulation engine using object-oriented principles, efficient queue management, and rule-based damage calculations.
Problem Statement
You are building the core combat engine for a monster-battle game. Each monster has id, hp, attack, defense, and speed.
Implement a BattleSimulator class that takes two teams (lists of monsters) and returns a list of combat events in chronological order.
Rules:
- Turn Order: In every round, monsters act in descending order of
speed. If speeds are tied, the monster with the loweridacts first. - Combat Logic: When a monster acts, it targets the opponent with the lowest current
hpon the opposing team. If multiple opponents have the same lowesthp, the one with the lowestidis targeted. - Damage Calculation:
Damage = max(1, attacker.attack - target.defense). If the attacker has a status effect multiplier (default 1.0), multiply the damage by this factor before subtracting defense. - Death: If a monster's
hpdrops to <= 0, it is removed from the team immediately. - Termination: The battle ends when one team has no monsters remaining.
Interface
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):
# Return a list of strings: e.g., "Monster 1 attacked Monster 4 for 10 damage"
pass
Examples
- Input: Team A: [{id: 1, hp: 50, atk: 20, def: 5, spd: 10}], Team B: [{id: 2, hp: 30, atk: 10, def: 5, spd: 5}]
- Execution: Monster 1 acts, attacks Monster 2. Damage = 20 - 5 = 15. Monster 2 HP becomes 15.
- Constraints: Teams contain 1-5 monsters.
hp> 0. All stats are integers 1-100.
Hints
Hint 1
Sort the combined active participants by speed (desc) and id (asc) at the start of each round to determine the turn sequence.
Hint 2
Maintain the current state of each team in a list or heap, ensuring you remove monsters that reach zero HP immediately after they take damage.
Hint 3
Use a helper method to find the current 'weakest' target based on the provided tie-breaking rules before every attack.
Follow-up questions
- How would you modify the simulator to support area-of-effect (AoE) attacks that damage all members of the opposing team?
- If the simulation needs to run 10,000 times for balancing, how would you optimize the data structures for faster target selection?
- How would you integrate a 'status effect' system (e.g., poison, stun) that persists across multiple turns?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.