Tic Tac Toe

Level: Beginner

Concepts: State Design


Create a program to implement the classic game of Tic Tac Toe.

Requirements

  1. Implement game rules:
    • 3x3 grid game board
    • Two players (X and O)
    • Players take turns placing their mark
    • First player to get 3 in a row (horizontally, vertically, or diagonally) wins
    • Game ends in a draw if all spaces are filled with no winner
  2. Handle game state:
    • Track current player's turn
    • Validate moves (prevent playing in occupied spaces)
    • Detect win conditions
    • Detect draw conditions
  3. Return appropriate results:
    • Current game state
    • Winner (if any)
    • Error messages for invalid moves

Test Cases

Scenario Moves Expected Result Notes
Empty Board None Game in progress Initial state
Horizontal Win X(0,0), O(1,0), X(0,1), O(1,1), X(0,2) X wins Top row win
Vertical Win X(0,0), O(0,1), X(1,0), O(1,1), X(2,0) X wins Left column win
Diagonal Win X(0,0), O(0,1), X(1,1), O(0,2), X(2,2) X wins Top-left to bottom-right
Draw X(0,0), O(0,1), X(0,2), O(1,0), X(1,1), O(2,0), X(1,2), O(2,2), X(2,1) Draw No winner
Invalid Move X(0,0), X(0,1) Error Same player twice

Edge Cases to Consider

  • Playing in an occupied space
  • Playing out of turn
  • Playing outside the board boundaries
  • Continuing play after game end
  • Multiple win conditions

Tips

  • Start with an empty board representation
  • Add move validation next
  • Then implement win detection
  • Finally add game state management
  • Consider using enums for player marks and game states