Katkat

Simulate Turn-Based Monster Battles

OpenAIMachine Learning Engineer · Onsite

Last updated

This problem tests your ability to design a stateful simulation engine that handles turn-based mechanics, complex status modifiers, and dynamic combat interactions.

Problem: Monster Battle Simulator

You are tasked with building the core engine for a turn-based monster battle game. Two monsters battle until one reaches zero HP. Each monster has a name, hp, attack, defense, speed, and type (Fire, Water, or Grass).

Rules:

  1. Type Effectiveness: Fire beats Grass, Grass beats Water, and Water beats Fire. When a monster has a type advantage, its damage is multiplied by 1.5x. Otherwise, damage is 1x (no disadvantage penalty in this version).
  2. Turn Order: The monster with the higher speed moves first. If speeds are tied, the first monster in the input list moves first.
  3. Damage Calculation: The base damage of a move is max(1, (attacker_attack - defender_defense) * 0.5). Apply the type effectiveness multiplier after this calculation.
  4. Turn Loop: The simulation continues until one monster's HP reaches 0 or below. The game returns the name of the winner or "Draw" if both hit 0 simultaneously.

Function Signature

def simulate_battle(monster1, monster2):
    # monster is a dict: {'name': str, 'hp': int, 'atk': int, 'def': int, 'spd': int, 'type': str}
    pass

Example

  • Monster A: {'name': 'A', 'hp': 20, 'atk': 10, 'def': 5, 'spd': 10, 'type': 'Fire'}
  • Monster B: {'name': 'B', 'hp': 20, 'atk': 8, 'def': 4, 'spd': 8, 'type': 'Grass'}
  • Turn 1: A attacks B. Base dmg: (10-4)0.5 = 3. Type bonus: 31.5 = 4.5 -> 4.5. B HP: 15.5

Constraints

  • hp > 0 initially.
  • atk, def, spd >= 0.
  • Use standard floating point for HP calculation; round to 2 decimal places if necessary.

Edge Cases

  • What happens if the damage results in a decimal? Keep it as is.
  • Ensure the game terminates immediately when a monster's HP <= 0.

Hints

Hint 1

Use a while-loop that breaks when either monster's HP is <= 0.

Hint 2

Determine the turn order once at the start of the battle based on the speed attribute.

Hint 3

Implement a helper function to determine the damage multiplier based on the 'type' attribute to keep your main loop clean.

Follow-up questions

  • How would you modify the simulator to support an arbitrary number of monsters in a team-based battle?
  • If we introduce 'Status Effects' (e.g., Poison), where would you inject that logic into the existing turn loop?
  • How would you optimize the simulation if you needed to run 1,000,000 battle trials to predict win probabilities?