Bird
Raised Fist0
LLDsystem_design~7 mins

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

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
Problem Statement
When designing a game, mixing responsibilities like managing the game state, player actions, and board layout in one place causes confusion and bugs. Without clear separation, the code becomes hard to maintain, test, and extend for new game rules or features.
Solution
Separate the game into three classes: Board to manage the game layout and state, Player to represent each participant and their actions, and Game to control the overall flow and rules. This clear division lets each class focus on one job, making the system easier to understand and modify.
Architecture
┌─────────┐       ┌─────────┐       ┌─────────┐
│  Player │──────▶│   Game  │──────▶│  Board  │
└─────────┘       └─────────┘       └─────────┘
      ▲                                │
      │                                │
      └────────────────────────────────┘

This diagram shows Player interacting with Game, which manages the Board. The Board holds the game state, while Game controls the rules and flow.

Trade-offs
✓ Pros
Clear separation of concerns improves code readability and maintainability.
Easier to add new features like different game rules or player types.
Simplifies testing each part independently.
✗ Cons
Requires more initial design effort to define clear interfaces.
May introduce slight overhead in communication between classes.
Beginners might find multiple classes harder to grasp at first.
Use when building any turn-based or board game with multiple players and a defined game state, especially if the game rules might evolve or the codebase will grow.
Avoid if the game is extremely simple (e.g., single-player with no complex state) or a quick prototype where speed of coding is more important than structure.
Real World Examples
Google
Google's online chess game uses separate classes for Board, Player, and Game to manage moves, enforce rules, and track game state cleanly.
Amazon
Amazon's game development teams use this pattern to build scalable multiplayer games with clear role separation.
Discord
Discord bots that run games like tic-tac-toe use distinct classes to handle player input, game logic, and board state.
Code Example
The before code mixes board state and player turns inside one Game class, making it hard to extend. The after code splits responsibilities: Board manages the grid, Player holds player info, and Game controls turns and rules. This separation improves clarity and flexibility.
LLD
### Before: Monolithic Game class without separation
class Game:
    def __init__(self):
        self.board = [['' for _ in range(3)] for _ in range(3)]
        self.players = ['X', 'O']
        self.current_player = 0

    def make_move(self, row, col):
        if self.board[row][col] == '':
            self.board[row][col] = self.players[self.current_player]
            self.current_player = 1 - self.current_player

### After: Separate Board, Player, and Game classes
class Board:
    def __init__(self, size=3):
        self.size = size
        self.grid = [['' for _ in range(size)] for _ in range(size)]

    def place_mark(self, row, col, mark):
        if self.grid[row][col] == '':
            self.grid[row][col] = mark
            return True
        return False

class Player:
    def __init__(self, name, mark):
        self.name = name
        self.mark = mark

class Game:
    def __init__(self, player1, player2, board):
        self.board = board
        self.players = [player1, player2]
        self.current_index = 0

    def make_move(self, row, col):
        player = self.players[self.current_index]
        if self.board.place_mark(row, col, player.mark):
            self.current_index = 1 - self.current_index
            return True
        return False
OutputSuccess
Alternatives
Monolithic Game Class
Combines board, player, and game logic into one class without separation.
Use when: Choose when building very simple games or quick prototypes where design overhead is not justified.
Entity-Component-System (ECS)
Uses entities with components and systems to manage game state and behavior instead of fixed classes.
Use when: Choose for complex games requiring high flexibility and performance, like real-time strategy or action games.
Summary
Separating Board, Player, and Game classes prevents mixing responsibilities and reduces bugs.
Each class focuses on a single role: Board for state, Player for participants, Game for rules and flow.
This design improves code clarity, extensibility, and testing.

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