liveBook · Manning

Tic-Tac-Toe

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

Tic-tac-toe is a two-player game played on a three-by-three grid in which players alternately place marks and aim to form a line of three matching marks.

Tic-tac-toe is a two-player game on a three-by-three grid. Players alternate X and O placements, seeking three matching marks in a row, column, or diagonal. section 8.4

A playable model stores the nine squares, whose turn it is, and the last move. Immutable boards produce a new position after each legal move, while empty squares define the available actions. section 8.4

A complete game model checks:

  • Wins across three rows, three columns, or two diagonals. section 8.4
  • Draws when no legal moves remain and neither player has won. section 8.4
  • Best moves through minimax: maximize the current player's outcome and minimize the opponent's. section 8.4

Testing the decision maker

Test positions can require an immediate win, blocking an opponent's win, or finding a winning move two turns ahead. Each position is passed to findBestMove. section 8.4

enum Piece: String {
    case X = "X"
    case O = "O"
    case E = " "
    var opposite: Piece {
        switch self {
        case .X:
            return .O
        case .O:
            return .X
        case .E:
            return .E
        }
    }
}

Represent the two marks and empty squares with Piece, then switch turns through its opposite property. section 8.4

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Develops immutable state, terminal checks, recursive evaluation, and move selection, stopping short of larger-game optimization.
Examples
Uses one-dimensional boards, winning lines, draw positions, and tests for immediate wins, blocks, and two-move wins.
What it assumes
Assumes familiarity with standard tic-tac-toe rules while developing the state representation from basic structures.
What you can do after
Build a perfect tic-tac-toe AI using immutable Swift board structures and minimax search.
How it connects
Connects game state and recursion to minimax, Connect Four, checkers, and chess.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.