Implement Tic-Tac-Toe with classes

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2020-05-17

Problem Statement

Design a Tic-Tac-Toe game using object-oriented principles. The game should support two-player mode (and optionally single-player vs AI) with proper encapsulation, modularity, and reusability.


Functional Requirements (FR)


Board Management


•Maintain a 3x3 grid representing the game board.
•Track which cells are occupied and by which player.
•Provide methods to mark a cell and display the board.


Player Management


•Represent players with identifiers (X or O).
•Track current player’s turn.


Game Rules


•Validate moves (prevent overwriting a filled cell).
•Detect win conditions (row, column, diagonal).
•Detect tie conditions (all cells filled with no winner).
•Switch turns after each valid move.


Game Control


•Start a new game.
•End a game and announce winner or tie.
•Optionally restart a game.


Optional Features


•Single-player mode with AI opponent.
•Score tracking across multiple rounds.


Classes & Responsibilities (Suggested Design)



Class: Player


•Attributes: name, symbol (X or O).
•Methods: make_move(board) (returns cell coordinates).


Class: Board


•Attributes: grid (2D array or list of lists).
•Methods:
•display() – print or render the board.
•mark_cell(row, col, symbol) – marks the cell if empty.
•is_full() – checks if the board is full.
•check_winner(symbol) – checks if the given symbol has a winning combination.


Class: Game


•Attributes: player1, player2, board, current_player.
•Methods:
•start() – initialize board and set first player.
•switch_turn() – change current player.
•play_turn(row, col) – validate and process a move.
•check_game_status() – check win/tie condition.


Class (Optional): AIPlayer


•Extends Player.
•Methods: make_move(board) implements AI logic (random/minimax).


Data Flow (Example Sequence)


1.Game initialized → Board and Players created → Current player set.
2.Player makes a move → Board validates move → updates grid.
3.Game checks for win/tie → if not finished, switch turn.
4.Repeat steps 2–3 until a winner is found or board is full.
5.Announce result → Optionally restart or exit.


Key Design Considerations


•Ensure encapsulation: Board state should only be modified through class methods.
•Maintain single responsibility principle: Each class has a clear role.
•Support extensibility: Allow AI implementation or larger board sizes in the future.
•Error handling: Handle invalid moves gracefully.
•Optional: Implement unit tests for Board and Game logic.


Solution

Comments