Start learning free

LESSON 69 OF 70 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in TypeScript: A Two-Player Game Class

Practice Read the full explanation

Build a TicTacToe class for two players, X and O, on a 3 by 3 board. One object is one game: it remembers the board and whose turn it is, lets the players take turns, and tells who has won.

The board: rows and columns are numbered 0, 1 and 2. Cell (0, 0) is the top-left corner, (0, 2) the top-right, (2, 0) the bottom-left and (2, 2) the bottom-right. A cell holds 'X', 'O' or '.' when it is still empty.

Build:

  • A new game. The class has two typed fields, set up when the object is created: board: string[][], three rows of three '.', and player: string = 'X'. Every row must be its own array (build them with Array.from, not by repeating one row). All nine cells are empty and X moves first.
  • move(r: number, c: number): void plays one turn at the given row and column (always between 0 and 2, so you do not need to check the range).
    • If the cell is not empty, ignore the call: nothing changes and it is still the same player's turn.
    • Otherwise put the current player's mark in the cell, then give the turn to the other player (X becomes O, O becomes X).
  • winner(): string returns the winner as a one-character string: 'X', 'O' or '.'.
    • A player wins by having the same mark in all three cells of a row, a column, or one of the two diagonals ((0,0), (1,1), (2,2) and (0,2), (1,1), (2,0)). Three empty cells in a line are not a win.
    • If nobody has three in a row, return '.'. That covers a game still in progress, an empty board and a draw.

You start with this code, which plays six games and prints the result of each one:

let game: TicTacToe = new TicTacToe();
game.move(0, 0);
game.move(1, 0);
game.move(0, 1);
game.move(1, 1);
game.move(0, 2);
console.log(game.winner() + " wins!");
game = new TicTacToe();
game.move(0, 0);
game.move(0, 1);
game.move(0, 0);
game.move(1, 0);
game.move(1, 1);
game.move(2, 2);
game.move(2, 1);
console.log(game.winner() + " wins!");
game = new TicTacToe();
game.move(0, 0);
game.move(0, 1);
game.move(1, 1);
game.move(0, 2);
game.move(2, 2);
console.log(game.winner() + " wins!");
game = new TicTacToe();
game.move(0, 2);
game.move(0, 0);
game.move(1, 1);
game.move(0, 1);
game.move(2, 0);
console.log(game.winner() + " wins!");
game = new TicTacToe();
game.move(0, 0);
game.move(0, 1);
game.move(0, 2);
game.move(1, 1);
game.move(1, 0);
game.move(1, 2);
game.move(2, 1);
game.move(2, 0);
game.move(2, 2);
console.log("No winner: " + game.winner());
game = new TicTacToe();
console.log("No winner: " + game.winner());

Games played: X fills the top row; then a game where X tries to play on a cell that is already taken (ignored, and still X's turn) and O wins the middle column; X on the main diagonal; X on the other diagonal; a full board with no three in a row; and a brand-new game.

Expected output:

X wins!
O wins!
X wins!
X wins!
No winner: .
No winner: .

There are eight winning lines: three rows, three columns and two diagonals. A loop over i from 0 to 2 can check row i and column i together; the two diagonals come after the loop. Skip a line whose first cell is empty.

Check for a taken cell first and leave the move method before touching the board or the turn. Only a successful move passes the turn to the other player.

class TicTacToe {
    board: string[][] = Array.from({length: 3}, () => Array(3).fill('.'));
    player: string = 'X';

    move(r: number, c: number): void {
        if (this.board[r][c] !== '.') return;
        this.board[r][c] = this.player;
        this.player = this.player === 'X' ? 'O' : 'X';
    }

    winner(): string {
        const b: string[][] = this.board;
        for (let i = 0; i < 3; i++) {
            if (b[i][0] !== '.' && b[i][0] === b[i][1] && b[i][1] === b[i][2]) return b[i][0];
            if (b[0][i] !== '.' && b[0][i] === b[1][i] && b[1][i] === b[2][i]) return b[0][i];
        }
        if (b[0][0] !== '.' && b[0][0] === b[1][1] && b[1][1] === b[2][2]) return b[0][0];
        if (b[0][2] !== '.' && b[0][2] === b[1][1] && b[1][1] === b[2][0]) return b[0][2];
        return '.';
    }
}

STEP 1 OF 15
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in TypeScript, explained

    Problem overview

    The lesson asks for a TicTacToe class for two players, X and O, on a 3 by 3 board. One object is one game. It remembers the board and whose turn it is, lets the players take turns, and tells who has won.

    Rows and columns are numbered 0, 1 and 2, and cell (0, 0) is the top-left corner. A cell holds 'X', 'O' or '.' when it is still empty. The class has:

    • a field board: string[][] with three rows of three dots, and a field player: string that starts as 'X', because X moves first;
    • move(r: number, c: number): void, which marks a cell for the current player and then passes the turn. If the cell is taken, the call is ignored: nothing changes and it is still the same player's turn;
    • winner(): string, which returns 'X' or 'O' when that player has three marks in a row, a column or a diagonal, and '.' otherwise. A game in progress, an empty board and a draw all give '.'.

    The driver plays six games. In the first, X takes the top row while O plays below. In the second, X tries to play on the cell it already holds, which is ignored, and O wins the middle column. The third and fourth games are won by X on each diagonal, the fifth fills the board with no winner, and the sixth is a new game with no moves.

    Approach: store the board, switch the player, scan eight lines

    The board is an array of three rows, each an array of three strings, so this.board[r][c] is the cell in row r, column c. Using '.' for an empty cell keeps every cell a one-character string.

    A move has two jobs: refuse a taken cell, and otherwise write the mark and give the turn to the other player. Because the refusal returns before the turn changes, a rejected move leaves the same player to try again.

    A tic-tac-toe board has exactly eight winning lines: three rows, three columns and two diagonals. winner checks them one by one. A line wins when its first cell is not a dot and all three cells hold the same mark. The first-cell test matters: three empty cells are equal to each other too, but three dots are not a win. A loop over i from 0 to 2 covers row i and column i together, and the two diagonals follow it. If nothing matched, the method returns a dot.

    Step by step

    1. Declare the class TicTacToe and its closing brace. Each object created later is its own game with its own memory.
    2. Declare the board as board: string[][], built with Array.from({length: 3}, () => Array(3).fill('.')). Array.from calls the function once for each of the three slots, so each row is a fresh array. Array(3).fill('.') makes one row of three dots.
    3. Declare player: string = 'X', the mark whose turn it is.
    4. Start move(r, c) with two number parameters and the return type void.
    5. Guard against a taken cell: if this.board[r][c] is not '.', return at once.
    6. Place the mark: store this.player in that cell.
    7. Pass the turn with a conditional expression: if the player was 'X', it becomes 'O', otherwise 'X'.
    8. Start winner(), returning a string.
    9. Give the board a short name: const b: string[][] = this.board;. This is the same array, not a copy, so it only shortens the lines below.
    10. Loop i from 0 to 2. Each pass checks row i and column i.
    11. Check row i: the first cell isn't a dot, equals the second, and the second equals the third. If so, return that mark.
    12. Check column i the same way, with the two indexes swapped.
    13. After the loop, check the main diagonal: cells (0,0), (1,1), (2,2).
    14. Check the other diagonal: cells (0,2), (1,1), (2,0). The row goes up by one as the column goes down.
    15. Return '.' as the last line: every check failed, so nobody has won.

    The solution in TypeScript

    class TicTacToe {
        board: string[][] = Array.from({length: 3}, () => Array(3).fill('.'));
        player: string = 'X';
    
        move(r: number, c: number): void {
            if (this.board[r][c] !== '.') return;
            this.board[r][c] = this.player;
            this.player = this.player === 'X' ? 'O' : 'X';
        }
    
        winner(): string {
            const b: string[][] = this.board;
            for (let i = 0; i < 3; i++) {
                if (b[i][0] !== '.' && b[i][0] === b[i][1] && b[i][1] === b[i][2]) return b[i][0];
                if (b[0][i] !== '.' && b[0][i] === b[1][i] && b[1][i] === b[2][i]) return b[0][i];
            }
            if (b[0][0] !== '.' && b[0][0] === b[1][1] && b[1][1] === b[2][2]) return b[0][0];
            if (b[0][2] !== '.' && b[0][2] === b[1][1] && b[1][1] === b[2][0]) return b[0][2];
            return '.';
        }
    }
    
    let game: TicTacToe = new TicTacToe();
    game.move(0, 0);
    game.move(1, 0);
    game.move(0, 1);
    game.move(1, 1);
    game.move(0, 2);
    console.log(game.winner() + " wins!");
    game = new TicTacToe();
    game.move(0, 0);
    game.move(0, 1);
    game.move(0, 0);
    game.move(1, 0);
    game.move(1, 1);
    game.move(2, 2);
    game.move(2, 1);
    console.log(game.winner() + " wins!");
    game = new TicTacToe();
    game.move(0, 0);
    game.move(0, 1);
    game.move(1, 1);
    game.move(0, 2);
    game.move(2, 2);
    console.log(game.winner() + " wins!");
    game = new TicTacToe();
    game.move(0, 2);
    game.move(0, 0);
    game.move(1, 1);
    game.move(0, 1);
    game.move(2, 0);
    console.log(game.winner() + " wins!");
    game = new TicTacToe();
    game.move(0, 0);
    game.move(0, 1);
    game.move(0, 2);
    game.move(1, 1);
    game.move(1, 0);
    game.move(1, 2);
    game.move(2, 1);
    game.move(2, 0);
    game.move(2, 2);
    console.log("No winner: " + game.winner());
    game = new TicTacToe();
    console.log("No winner: " + game.winner());
    

    It prints:

    X wins!
    O wins!
    X wins!
    X wins!
    No winner: .
    No winner: .
    

    The games on the board

    Printing each row of board as a string shows where the marks end up. In the first game, X holds the top row and O has two marks below it:

    XXX
    OO.
    ...
    

    In the second game, after the repeated move(0, 0) was ignored and the other moves were played, O holds the middle column:

    XO.
    XO.
    .OX
    

    The third and fourth games end like this, with X on the main diagonal and then on the other one:

    XOO
    .X.
    ..X
    
    OOX
    .X.
    X..
    

    The fifth game fills every cell and nobody has three in a line:

    XOX
    XOO
    OXX
    

    TypeScript details worth knowing

    • Each row must be its own array. Array(3).fill(Array(3).fill('.')) puts one and the same row into all three slots. After bad[0][0] = 'X', the three rows print as X..|X..|X... With Array.from({length: 3}, () => Array(3).fill('.')) the same assignment gives X..|...|..., because the function runs again for every row.
    • Two-dimensional arrays. string[][] is an array of arrays. b[1][2] first takes row 1, then cell 2 of it.
    • !== and ===. They compare without converting types. For single-character strings they simply compare the characters.
    • && short-circuits. In each chain, the first comparison is the "not a dot" test, so the rest runs only for a marked first cell.
    • The conditional expression. test ? a : b gives a when the test is true and b otherwise. It is an expression, so its result can be assigned directly to this.player.
    • this.player is read before it changes. In move, the mark is written first and the player is switched second. Switching first would put the wrong mark on the board.
    • Types don't check the range. r and c are plain numbers, and the compiler can't tell 0 to 2 from 7. The lesson promises valid values.

    Complexity

    Time. move is O(1): one read, one write, one switch. winner looks at a fixed number of cells: three passes of the loop plus two diagonals, so it is O(1) for a 3 by 3 board. (For an n by n board the same scan would cost O(n²).) Space. The board holds nine cells and one player mark, which is O(1).

    Edge cases and common mistakes

    • Empty lines are not wins. Without the !== '.' test, a new game would report a winner, because three dots are equal: comparing a row of an empty board gives true. The sixth driver game covers this.
    • Passing the turn on a refused move. If the guard doesn't return before the turn changes, a player who picks a taken cell loses the turn. In the second game, the repeated move(0, 0) is X's attempt and must leave X to play next, so the following moves, X at (1, 0), O at (1, 1), X at (2, 2) and O at (2, 1), keep their order.
    • Overwriting a mark. Without the guard, a move onto a marked cell replaces the mark: if O played on a cell X holds, X's mark would be lost.
    • Sharing rows. Building the board with fill on an array of arrays makes all three rows the same row, as shown above.
    • Swapped indexes. b[r][c] is row then column. The column check uses b[0][i], b[1][i], b[2][i], which is the row check with the indexes swapped.
    • Checking only one diagonal, or putting the diagonals inside the loop. They don't depend on i, so they run once, after it.
    • Draws. A full board with no line returns '.', the same answer as a game still in progress. winner doesn't say whether the game is over.
    • Moves after a win. The class doesn't stop play. After X completes the top row, a further move(2, 2) by O is still accepted and winner() still says X.
    • Out-of-range indexes. move(3, 0) throws a TypeError (Cannot read properties of undefined), because there is no row 3. move(0, 3) is ignored silently, because the missing cell is not '.'. The lesson never calls either.

    Testing

    • A new game: winner() is '.'.
    • Moves (0,0), (1,0), (0,1), (1,1), (0,2): X has the top row, and winner() is 'X'.
    • Moves (0,0), (0,1), (0,0), (1,0), (1,1), (2,2), (2,1): the repeated (0,0) is ignored and winner() is 'O'.
    • Moves (0,0), (0,1), (1,1), (0,2), (2,2): X has the main diagonal, 'X'.
    • Moves (0,2), (0,0), (1,1), (0,1), (2,0): X has the other diagonal, 'X'.
    • The nine-move game from the driver ends with a full board and '.'.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free