Start learning free

LESSON 666 OF 671 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in JavaScript: 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 fields, set up when the object is created: board, an array of three rows (each an array of three '.'), and player = '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, c) 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() 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 = 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 = Array.from({length: 3}, () => Array(3).fill('.'));
    player = 'X';

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

    winner() {
        const b = 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

    JAVASCRIPT · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in JavaScript, explained

    Problem overview

    The lesson builds 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 reports who has won.

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

    • two fields set when the object is created: board, an array of three rows of three '.', and player, which starts as 'X';
    • move(r, c), which plays one turn. If the cell is taken, nothing changes and it is still the same player's turn. Otherwise the current player's mark goes in the cell and the turn passes to the other player;
    • winner(), which returns 'X', 'O' or '.'. A player wins with the same mark in a whole row, column or diagonal. A game in progress, an empty board and a draw all return '.'.

    The driver plays six games. The expected output is:

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

    In the second game X tries to play on a cell that is already taken. That move is ignored, so it is still X's turn and the next move is X's.

    Approach: state, a guarded move and eight lines

    The state is the board plus the current player. move changes both, but only when the move is legal, so the check for a taken cell comes first and leaves the method before touching anything.

    For winner, there are only eight lines that can win: three rows, three columns and two diagonals. Instead of a general search, the code tests each of them directly. One loop over i from 0 to 2 can check row i and column i together, and the two diagonals come after the loop. Every test also requires the first cell to be non-empty, since three empty cells are equal to each other but are not a win.

    The driver's games end on these boards, which the class produces:

    GameBoard, rows top to bottomWinner
    1XXX / OO. / ...X (top row)
    2XO. / XO. / .OXO (middle column)
    3XOO / .X. / ..XX (main diagonal)
    4OOX / .X. / X..X (other diagonal)
    5XOX / XOO / OXXnobody (draw)

    Game 6 is a fresh board of dots with no winner.

    Step by step

    1. Declare the class TicTacToe. Each object created from it is one game with its own memory.
    2. Add the board field: Array.from({length: 3}, () => Array(3).fill('.')). Array.from calls the function once for each of the three items, so every row is a fresh array. Array(3).fill('.') makes one row of three dots. Then this.board[r][c] is row r, column c.
    3. Add the player field as 'X': X moves first, so every new game starts the same way.
    4. Start move(r, c).
    5. Guard against a taken cell: if this.board[r][c] is not '.', return right away. Nothing changes.
    6. Place the mark: store this.player in that cell.
    7. Pass the turn with a conditional expression: the player becomes 'O' if it was 'X', otherwise 'X'.
    8. Start winner(). It returns a mark or a dot.
    9. Name the board: const b = this.board; is the same board, not a copy, and it keeps the lines short.
    10. Loop i over 0, 1 and 2, checking row i and column i in each pass.
    11. Check row i: the first cell is not a dot and 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) and (2,2).
    14. Check the other diagonal: cells (0,2), (1,1) and (2,0). The row goes up by one while the column goes down by one.
    15. Return '.' as the last line: every check failed, so nobody has won.

    The solution in JavaScript

    class TicTacToe {
        board = Array.from({length: 3}, () => Array(3).fill('.'));
        player = 'X';
        move(r, c) {
            if (this.board[r][c] !== '.') return;
            this.board[r][c] = this.player;
            this.player = this.player === 'X' ? 'O' : 'X';
        }
        winner() {
            const b = 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 = 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());
    

    The JavaScript details worth knowing:

    • Why Array.from and not a repeated row. Array(3).fill(Array(3).fill('.')) fills the outer array with three references to one row. Setting cell (0, 0) to 'X' then shows up in every row: the board prints as X.. / X.. / X... With Array.from and a function, each row is separate, and the same assignment gives X.. / ... / ....
    • Fields run per object. The field initialisers run each time new TicTacToe() is called, so every game gets its own board. Reassigning game = new TicTacToe() in the driver starts from a clean board.
    • !== and ===. They compare without type conversion, which is the right choice for one-character strings.
    • The conditional expression. test ? a : b gives a when the test is true and b otherwise. Here it picks the next mark.
    • Early return in move. A bare return; leaves the method before the next two lines run, so a refused move changes neither the board nor the turn.
    • Returning inside the loop. The first line found ends winner() at once. Two completed lines for different players can't appear in a legal game, so the order of the checks doesn't matter for valid play.

    Complexity

    The board has a fixed size, so both methods take constant time: move reads and writes one cell, and winner checks at most eight lines of three cells. Each game stores nine cells and one mark, which is constant space too.

    Edge cases and common mistakes

    • Playing a taken cell. In game 2, the second move(0, 0) is ignored. If the guard were missing, O's mark would be overwritten by X's and the turn order would shift.
    • Passing the turn before the guard. If the turn changed even for a refused move, the wrong player would mark the next cell.
    • Skipping the empty-cell test in winner. Three dots in a line are equal, so without the test an empty line would count as a win for '.' and winner() would return '.' at once. A board with an empty top row and a winning middle row would then give the wrong answer, because the loop reaches the empty row first.
    • Row and column swapped. The column check uses b[0][i], b[1][i], b[2][i]: the row index changes, not the column.
    • A wrong second diagonal. It is (0,2), (1,1), (2,0), not (0,2), (1,1), (2,2).
    • A draw is not a special case. A full board with no line returns '.', as in game 5.
    • Moves after a win. The class doesn't stop the game: move still accepts empty cells after someone has three in a row, and winner() keeps returning that player. The lesson doesn't ask for more.

    Testing

    • A new game: player is 'X', and after move(1, 1) it is 'O'. A second move(1, 1) leaves it 'O' and the board as ... / .X. / ....
    • The moves (0,0), (1,0), (0,1), (1,1), (0,2) give 'X' and the board XXX / OO. / ....
    • A board where X has (0,0), (1,0) and (2,0) while O has (0,1) and (1,1) gives 'X'.
    • Two separate games: after move(0, 0) on the first, the second game's cell (0, 0) is still '.'.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free