Katkat

Simulate a Turn-Based Two-Player Game

OpenAISoftware Engineer · Technical Screen

Last updated

This problem tests your ability to design a robust state management system and implement validation logic for a rule-based game.

Problem Statement

Design a class GameSimulator for a 1D board game played on a grid of size N. The board positions are indexed from 0 to N-1. Two players, P1 and P2, start at positions 0 and N-1 respectively.

Players take turns moving. P1 always goes first. On each turn, a player chooses to move their piece by +1, -1, or +0 (stay put).

Rules:

  1. A player cannot move to a position already occupied by the opponent.
  2. A player cannot move outside the boundaries [0, N-1].
  3. The game ends when one player lands on the position exactly equal to the opponent's current position (a capture).

Implementation Requirements:

Implement the following interface:

  • __init__(self, n): Initializes the board of size N.
  • move(self, player_id, direction): player_id is 1 or 2, direction is -1, 0, or 1. Returns a tuple (is_valid, game_over).

Examples:

sim = GameSimulator(5)
# P1 is at 0, P2 is at 4
sim.move(1, 1) # P1 moves to 1. Returns (True, False)
sim.move(2, -1) # P2 moves to 3. Returns (True, False)

Constraints:

  • N is between 2 and 1000.
  • player_id is always 1 or 2.
  • Moves must follow the turn order (P1, then P2, then P1...).
  • If an invalid move is attempted, the state must remain unchanged and return (False, False).

Hints

Hint 1

Use variables to track the current position of both players and a variable to keep track of whose turn it is.

Hint 2

For each move, check if the calculated new position is within the board boundaries and not equal to the opponent's current position.

Hint 3

The capture condition is met if the new position of the current player equals the static position of the opponent.

Follow-up questions

  • How would you modify your design to support a 2D grid instead of a 1D board?
  • What changes are needed to support a 'history' feature to undo the last move?
  • How would you ensure the class is thread-safe if multiple clients attempt to make moves simultaneously?