Bird
Raised Fist0
LLDsystem_design~25 mins

Board, Player, Game classes in LLD - System Design Exercise

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Design: Turn-based Game System
Design classes for Board, Player, and Game to manage game logic and state. UI, network communication, and persistence are out of scope.
Functional Requirements
FR1: Support multiple players in a game
FR2: Manage the game board state
FR3: Allow players to take turns making moves
FR4: Track player scores and game progress
FR5: Detect game end conditions (win, draw, etc.)
Non-Functional Requirements
NFR1: Support up to 4 players per game
NFR2: Each move must be processed within 100ms
NFR3: System should be designed for easy extension to different game types
NFR4: Maintain game state consistency during concurrent player actions
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
Key Components
Board class to represent game state
Player class to represent each participant
Game class to manage game flow and rules
Design Patterns
State pattern for managing game phases
Observer pattern for notifying players of state changes
Command pattern for encapsulating player moves
Reference Architecture
  +----------------+       +----------------+       +----------------+
  |    Player      |<----->|     Game       |<----->|     Board      |
  +----------------+       +----------------+       +----------------+
         ^                        ^                        ^
         |                        |                        |
  playerId, name           gameId, players          boardState, size
  score, status            currentTurn, status      update(), reset()
Components
Player
Class
Represents a player with identity, score, and status in the game
Board
Class
Maintains the current state of the game board and provides methods to update and query it
Game
Class
Controls game flow, manages players and board, enforces rules, and tracks game progress
Request Flow
1. 1. Game initializes Board and Player instances.
2. 2. Game sets the first player's turn.
3. 3. Player makes a move by invoking Game's move method.
4. 4. Game validates the move and updates Board state.
5. 5. Game updates Player scores and checks for end conditions.
6. 6. Game switches turn to the next Player.
7. 7. Repeat steps 3-6 until game ends.
Database Schema
Entities: - Player: player_id (PK), name, score, status - Game: game_id (PK), current_turn (FK to Player), status - Board: board_id (PK), game_id (FK to Game), state (serialized board data) Relationships: - Game has many Players - Game has one Board - Player participates in many Games (if multiplayer across sessions)
Scaling Discussion
Bottlenecks
Handling concurrent moves from multiple players
Maintaining consistent game state under concurrent access
Extending to support multiple simultaneous games
Solutions
Use locking or transactional mechanisms to serialize moves per game instance
Implement optimistic concurrency control with versioning for board state
Design Game instances to be independent and scalable horizontally
Interview Tips
Time: Spend 10 minutes clarifying requirements and scope, 20 minutes designing classes and interactions, 10 minutes discussing scaling and improvements, 5 minutes for questions.
Explain clear separation of concerns between Board, Player, and Game classes
Discuss how turns and moves are managed to ensure fairness and consistency
Highlight extensibility for different game types and rules
Address concurrency and state consistency challenges
Mention design patterns that improve maintainability and flexibility

Practice

(1/5)
1. Which class is primarily responsible for keeping track of the current state of the game board in a typical game design involving Board, Player, and Game classes?
easy
A. Score class
B. Player class
C. Game class
D. Board class

Solution

  1. Step 1: Understand the role of the Board class

    The Board class holds the layout and current state of the game, such as positions of pieces or marks.
  2. Step 2: Compare with Player and Game classes

    The Player class stores player details, and the Game class manages turns and rules, not the board state.
  3. Final Answer:

    Board class -> Option D
  4. Quick Check:

    Board = game state holder [OK]
Hint: Board holds game state, Player holds info, Game controls flow [OK]
Common Mistakes:
  • Confusing Player with Board for state storage
  • Thinking Game class stores board state
  • Assuming Score class manages board
2. Which of the following is the correct way to define a Player class constructor that stores a player's name and ID in a typical object-oriented design?
easy
A. class Player { constructor(name, id) { this.name = name; this.id = id; } }
B. class Player { Player(name, id) { this.name = name; this.id = id; } }
C. function Player(name, id) { this.name = name; this.id = id; }
D. class Player { def __init__(self, name, id): self.name = name; self.id = id }

Solution

  1. Step 1: Identify the correct constructor syntax in JavaScript

    In JavaScript ES6+, the constructor method inside a class is named constructor.
  2. Step 2: Check other options for errors

    class Player { Player(name, id) { this.name = name; this.id = id; } } uses a method named Player instead of constructor; function Player(name, id) { this.name = name; this.id = id; } is a function, not a class; class Player { def __init__(self, name, id): self.name = name; self.id = id } uses Python syntax.
  3. Final Answer:

    class Player { constructor(name, id) { this.name = name; this.id = id; } } -> Option A
  4. Quick Check:

    JavaScript class constructor = constructor() [OK]
Hint: JS class constructors use 'constructor' keyword [OK]
Common Mistakes:
  • Using method named same as class instead of constructor
  • Mixing Python syntax in JavaScript
  • Defining constructor as a separate function
3. Given the following simplified code snippet, what will be the output after calling game.playTurn() once?
class Player {
  constructor(name) { this.name = name; }
}
class Board {
  constructor() { this.state = ['-', '-', '-']; }
  mark(position, symbol) { this.state[position] = symbol; }
}
class Game {
  constructor() {
    this.board = new Board();
    this.players = [new Player('Alice'), new Player('Bob')];
    this.currentPlayerIndex = 0;
  }
  playTurn() {
    const player = this.players[this.currentPlayerIndex];
    this.board.mark(0, this.currentPlayerIndex === 0 ? 'X' : 'O');
    this.currentPlayerIndex = 1 - this.currentPlayerIndex;
    return this.board.state;
  }
}
const game = new Game();
console.log(game.playTurn());
medium
A. ['X', '-', '-']
B. ['O', '-', '-']
C. ['-', '-', '-']
D. Error: mark method not found

Solution

  1. Step 1: Analyze initial state and playTurn logic

    Board state starts as ['-', '-', '-']. Current player index is 0, so symbol 'X' is placed at position 0.
  2. Step 2: Update currentPlayerIndex and return state

    After marking, currentPlayerIndex switches to 1. The returned board state is ['X', '-', '-'].
  3. Final Answer:

    ['X', '-', '-'] -> Option A
  4. Quick Check:

    First turn marks 'X' at position 0 [OK]
Hint: First player marks 'X' at position 0 on first turn [OK]
Common Mistakes:
  • Assuming 'O' is placed first
  • Not updating currentPlayerIndex
  • Confusing board state initialization
4. In the following code snippet, what is the main issue that will cause the game to not switch players correctly?
class Game {
  constructor() {
    this.players = ['Alice', 'Bob'];
    this.currentPlayerIndex = 0;
  }
  nextTurn() {
    this.currentPlayerIndex += 1;
    if (this.currentPlayerIndex > this.players.length) {
      this.currentPlayerIndex = 0;
    }
  }
}
medium
A. Players array should contain Player objects, not strings
B. The condition should be >= players.length, not >
C. currentPlayerIndex should start at 1, not 0
D. nextTurn method should decrement currentPlayerIndex

Solution

  1. Step 1: Understand player index bounds

    Array indices go from 0 to length-1. If currentPlayerIndex equals players.length, it is out of bounds.
  2. Step 2: Check condition for resetting index

    The condition uses > players.length, which misses the case when currentPlayerIndex == players.length, causing an error.
  3. Final Answer:

    The condition should be >= players.length, not > -> Option B
  4. Quick Check:

    Index reset condition must include equality [OK]
Hint: Check array index bounds carefully for off-by-one errors [OK]
Common Mistakes:
  • Using > instead of >= for index reset
  • Ignoring zero-based indexing
  • Thinking player array type causes index error
5. You want to design a turn-based game system using Board, Player, and Game classes. Which design choice best supports adding new game rules and multiple player types (e.g., human, AI) without changing existing code much?
hard
A. Use global variables for player types and rules to simplify access
B. Keep all logic inside Game class and add if-else for player types and rules
C. Use inheritance: create subclasses like HumanPlayer and AIPlayer from Player, and extend Game with rule classes
D. Store all player and rule info in Board class to centralize state

Solution

  1. Step 1: Consider extensibility and separation of concerns

    Inheritance allows creating specialized Player types without modifying base Player class, supporting new behaviors.
  2. Step 2: Use modular design for rules

    Extending Game with separate rule classes or modules keeps code clean and easy to maintain.
  3. Final Answer:

    Use inheritance: create subclasses like HumanPlayer and AIPlayer from Player, and extend Game with rule classes -> Option C
  4. Quick Check:

    Inheritance and modular rules = easy extension [OK]
Hint: Use inheritance and modular rules for easy feature addition [OK]
Common Mistakes:
  • Putting all logic in one class causing messy code
  • Using global variables leading to hard-to-maintain code
  • Storing rules in Board instead of Game