Start learning free

LESSON 68 OF 69 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in C++: 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 constructor TicTacToe() fills the private char board[3][3] with '.' using two nested loops and sets player = 'X'. Keep the fields under private: and the constructor and methods under public:. All nine cells are empty and X moves first.
  • void move(int r, int 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).
  • char winner() returns the winner as a char: '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:

class Solution {
public:
    void mainFunction() {
        TicTacToe game;
        game.move(0, 0);
        game.move(1, 0);
        game.move(0, 1);
        game.move(1, 1);
        game.move(0, 2);
        cout << game.winner() << " wins!" << endl;
        game = 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);
        cout << game.winner() << " wins!" << endl;
        game = TicTacToe();
        game.move(0, 0);
        game.move(0, 1);
        game.move(1, 1);
        game.move(0, 2);
        game.move(2, 2);
        cout << game.winner() << " wins!" << endl;
        game = TicTacToe();
        game.move(0, 2);
        game.move(0, 0);
        game.move(1, 1);
        game.move(0, 1);
        game.move(2, 0);
        cout << game.winner() << " wins!" << endl;
        game = 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);
        cout << "No winner: " << game.winner() << endl;
        game = TicTacToe();
        cout << "No winner: " << game.winner() << endl;
    }
};

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 {
private:
    char board[3][3];
    char player;
public:
    TicTacToe() {
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                board[i][j] = '.';
        player = 'X';
    }

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

    char winner() {
        for (int i = 0; i < 3; i++) {
            if (board[i][0] != '.' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) return board[i][0];
            if (board[0][i] != '.' && board[0][i] == board[1][i] && board[1][i] == board[2][i]) return board[0][i];
        }
        if (board[0][0] != '.' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) return board[0][0];
        if (board[0][2] != '.' && board[0][2] == board[1][1] && board[1][1] == board[2][0]) return board[0][2];
        return '.';
    }
};

STEP 1 OF 19
    Ctrl + Enter to check

    C++ · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in C++, explained

    Problem overview

    You 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. Rows and columns are numbered 0 to 2, with cell (0, 0) at the top left. A cell holds 'X', 'O', or '.' when it is empty.

    • The constructor TicTacToe() fills the private char board[3][3] with dots and sets player = 'X', so X moves first.
    • void move(int r, int c) plays a turn. If the cell is taken, the call changes nothing 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. The coordinates are always 0 to 2, so no range check is needed.
    • char winner() returns 'X' or 'O' when that player has three in a row, in a column or on one of the two diagonals, and '.' otherwise. That covers a game in progress, an empty board and a draw.

    The code at the bottom of the starter plays six games. In the first, X takes the whole top row. In the second, X tries to play on cell (0, 0) a second time. The call is ignored and it is still X's turn, so X plays (1, 0), and O goes on to complete the middle column. The third and fourth games finish on the two diagonals for X. The fifth fills the board with no line, and the sixth is a fresh game. The output:

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

    Approach: eight lines, one test

    A game is won by one of eight lines: three rows, three columns and two diagonals. Every line has the same test: its three cells are equal and not empty. The second part of the test matters because three dots are equal to each other too, but they are not a win.

    A loop with i from 0 to 2 can check row i and column i together: the row's cells are board[i][0], board[i][1] and board[i][2], and the column's are the same indexes swapped. The two diagonals don't depend on i, so they are checked once after the loop. The method returns the mark of the first complete line it finds, and a dot if none is complete.

    For move, the order of the operations matters. First check whether the cell is taken and leave if it is, before touching the board or the turn. Only a successful move passes the turn on. This is what keeps the player the same after a rejected move.

    Step by step

    1. Declare TicTacToe with private: and public: labels and the closing };.
    2. Add the board under private: as char board[3][3];. board[r][c] is the cell in row r, column c.
    3. Add char player; for whose turn it is.
    4. Write the constructor under public:: the class name, no return type.
    5. Loop over the rows with i.
    6. Nest a loop over the columns with j.
    7. Set board[i][j] to '.'. The nested loops visit all nine cells.
    8. Set player to 'X' below the loops, so every new game starts with X.
    9. Start move as a void method with parameters r and c.
    10. Guard a taken cell. If board[r][c] isn't '.', return at once: nothing changes and the turn stays.
    11. Place the mark: board[r][c] = player;.
    12. Pass the turn with a conditional expression: if the player was 'X' it becomes 'O', otherwise 'X'.
    13. Start winner as a method returning char.
    14. Loop i over 0, 1 and 2, each pass checking row i and column i.
    15. Check row i: the first cell isn't a dot and equals the second, and the second equals the third. Then return that mark.
    16. Check column i the same way, with the two indexes swapped.
    17. Check the main diagonal, cells (0,0), (1,1) and (2,2), after the loop.
    18. Check the other diagonal, cells (0,2), (1,1) and (2,0): the row goes up by one as the column goes down by one.
    19. Return '.' as the last line: every check failed, so nobody has won.

    The solution in C++

    class TicTacToe {
    private:
        char board[3][3];
        char player;
    public:
        TicTacToe() {
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                    board[i][j] = '.';
            player = 'X';
        }
    
        void move(int r, int c) {
            if (board[r][c] != '.') return;
            board[r][c] = player;
            player = (player == 'X') ? 'O' : 'X';
        }
    
        char winner() {
            for (int i = 0; i < 3; i++) {
                if (board[i][0] != '.' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) return board[i][0];
                if (board[0][i] != '.' && board[0][i] == board[1][i] && board[1][i] == board[2][i]) return board[0][i];
            }
            if (board[0][0] != '.' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) return board[0][0];
            if (board[0][2] != '.' && board[0][2] == board[1][1] && board[1][1] == board[2][0]) return board[0][2];
            return '.';
        }
    };
    
    class Solution {
    public:
        void mainFunction() {
            TicTacToe game;
            game.move(0, 0);
            game.move(1, 0);
            game.move(0, 1);
            game.move(1, 1);
            game.move(0, 2);
            cout << game.winner() << " wins!" << endl;
            game = 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);
            cout << game.winner() << " wins!" << endl;
            game = TicTacToe();
            game.move(0, 0);
            game.move(0, 1);
            game.move(1, 1);
            game.move(0, 2);
            game.move(2, 2);
            cout << game.winner() << " wins!" << endl;
            game = TicTacToe();
            game.move(0, 2);
            game.move(0, 0);
            game.move(1, 1);
            game.move(0, 1);
            game.move(2, 0);
            cout << game.winner() << " wins!" << endl;
            game = 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);
            cout << "No winner: " << game.winner() << endl;
            game = TicTacToe();
            cout << "No winner: " << game.winner() << endl;
        }
    };
    

    C++ details worth knowing

    • The constructor must fill the board. A char array that is a class member isn't set to anything automatically. Without the loops, the cells would hold unpredictable values, and the test for an empty cell would fail.
    • Characters use single quotes. 'X' is one char; "X" is a string and can't be assigned to a char.
    • Printing a char. cout << game.winner() prints the character itself, which is why the output reads X wins!.
    • The conditional expression. test ? a : b gives a when the test is true and b otherwise, which makes the turn change a single line.
    • Resetting a game. game = TicTacToe(); builds a new object, so the constructor runs again, and copies it over the old one. Every cell is a dot again and X is back on move.
    • The row-then-column check. Each check uses &&, which stops at the first false part, so the equality tests only run for a non-empty first cell.

    Complexity

    The board has a fixed size, so everything takes constant time. The constructor visits nine cells, move writes one, and winner checks eight lines of three cells each. The class stores nine characters and one more for the player.

    Edge cases and common mistakes

    • Letting a taken cell be overwritten. Without the guard, the second move(0, 0) in the second game would replace X's mark and hand the turn to O. The board would differ from the expected game.
    • Passing the turn on a rejected move. Putting the turn change before the guard would give O the turn after X's refused move, which breaks the sequence.
    • Skipping the "not a dot" test. Three empty cells are equal to each other, so an empty row would be reported as a win for '.'. The method would return at that line and never reach a real winning line further down the board. Always check that the first cell holds a mark.
    • Mixing up the diagonals. The second diagonal is (0,2), (1,1), (2,0), not (0,2), (1,1), (2,2).
    • A missing final return. A char method that can reach its end without returning is undefined behaviour. The line return '.'; covers games in progress and draws.

    Testing

    For the second game, after the moves (0,0), (0,1), (0,0), (1,0), (1,1), (2,2) and (2,1), the repeated (0,0) was ignored, so X is still to move. The board looks like this, and column 1 holds three O marks:

    XO.
    XO.
    .OX
    turn: X

    Other cases to try are a new game (the winner is '.') and a game with two marks each (still '.'). The drawn board in the fifth game also returns '.'.

    Key takeaways

    • One object is one game: the board and the current player are its private state.
    • Guard first in move, then place the mark, then pass the turn.
    • A win is one of eight lines; test that the first cell isn't empty and that the three cells match.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free