Katkat

Implement a Single-Screen Tic-Tac-Toe Game with State Management

RampSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to model state transitions, encapsulate game logic, and handle user interactions in a clean, maintainable way.

Tic-Tac-Toe Game Engine

You are tasked with building the core logic for a 3x3 Tic-Tac-Toe game. You do not need to build the UI, but you must implement a class that manages the board state and enforces the rules of the game.

Requirements

  1. Initialize a 3x3 board (empty).
  2. Implement a make_move(row, col) method that places 'X' or 'O' depending on the current turn.
  3. Prevent invalid moves (e.g., placing a mark on an occupied cell, or making a move after the game has ended).
  4. Detect win conditions (row, column, or diagonal) and draw conditions.
  5. Implement a reset() method to clear the board.

Interface

class TicTacToe:
    def __init__(self):
        # Initialize board and state
        pass

    def make_move(self, row, col):
        # Returns True if move was successful, False otherwise
        pass

    def get_winner(self):
        # Returns 'X', 'O', 'Draw', or None (if game in progress)
        pass

    def reset(self):
        # Resets the game to the initial state
        pass

Examples

Example 1:

  • game.make_move(0, 0) -> Returns True (Board at (0,0) is 'X')
  • game.make_move(0, 0) -> Returns False (Cell occupied)

Example 2:

  • If player X plays (0,0), (0,1), (0,2), get_winner() should return 'X'.

Constraints

  • Board is always 3x3.
  • Rows and cols are 0-indexed.

Hints

Hint 1

Use a 2D list (or a flat list of size 9) to track the current state of the board.

Hint 2

Keep a 'turn' variable to toggle between 'X' and 'O' after every successful move.

Hint 3

After every move, check if the current row, column, or either diagonal contains three identical marks.

Follow-up questions

  • How would you modify your logic to support an N x N board size?
  • How would you implement an undo feature to revert the last move?
  • If this were part of a web application, how would you store the state so the game persists after a page refresh?