Start learning free

LESSON 68 OF 68 · PROJECTS: OBJECT-ORIENTED

Tic Tac Toe in Java: 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 public TicTacToe() fills the private char[][] board (3 by 3) with '.' using two nested loops. The private field char player starts as 'X'. All nine cells are empty and X moves first.
  • public 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).
  • public 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 = new TicTacToe();
        game.move(0, 0);
        game.move(1, 0);
        game.move(0, 1);
        game.move(1, 1);
        game.move(0, 2);
        System.out.println(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);
        System.out.println(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);
        System.out.println(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);
        System.out.println(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);
        System.out.println("No winner: " + game.winner());
        game = new TicTacToe();
        System.out.println("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 {
    private char[][] board = new char[3][3];
    private char player = 'X';

    public TicTacToe() {
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                board[i][j] = '.';
    }

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

    public 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 18
    Ctrl + Enter to check

    JAVA · PROJECTS: OBJECT-ORIENTED

    Tic Tac Toe in Java, explained

    Problem overview

    The task is to build a TicTacToe class where one object is one game. It keeps a 3 by 3 char[][] board and a char player for whose turn it is. A cell holds 'X', 'O' or '.' for empty. Rows and columns are numbered 0 to 2, and cell (0, 0) is the top-left corner.

    • The constructor fills the board with '.' using two nested loops. X moves first.
    • move(int r, int c) ignores the call if the cell is taken, and the turn stays with the same player. Otherwise it puts the current player's mark in the cell and passes the turn.
    • winner() returns 'X' or 'O' when that player has three marks in a row, a column or a diagonal. It returns '.' when nobody has, which covers a game in progress, an empty board and a draw.

    The driver plays six games. X fills the top row. In the second game X tries a cell that is already taken, which is ignored, and O ends up winning the middle column. Then come two diagonal wins for X, a full board with no winner, and a brand-new game:

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

    Approach: state in the object, eight lines to check

    The board and the turn are the object's private state, so the only way to change them is move, which keeps them consistent. Using '.' for an empty cell makes the "is this cell free?" test a single comparison.

    A win is one of eight lines: three rows, three columns and two diagonals. A loop over i from 0 to 2 can check row i and column i in the same pass, and the two diagonals follow after the loop. Each check has the same shape: the first cell isn't '.', and the three cells are equal. The first-cell test matters, because three empty cells are also equal and must not count as a win.

    Step by step

    1. Declare the class TicTacToe.
    2. Add the private board: new char[3][3] makes three rows of three char cells, and board[r][c] is row r, column c.
    3. Add the private player as a char that starts as 'X'.
    4. Write the constructor, public TicTacToe(): the class's 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 '.', so all nine cells become empty.
    8. Declare move as public void move(int r, int c).
    9. Guard against a taken cell: if board[r][c] isn't '.', return. Neither the board nor the turn changes.
    10. Place the mark: put player in the cell.
    11. Pass the turn with a conditional expression: if player was 'X' it becomes 'O', otherwise 'X'.
    12. Declare winner as public char winner().
    13. Loop i over 0, 1 and 2, to check row i and column i together.
    14. Check row i: its first cell isn't '.', and the first equals the second and the second equals the third. If so, return that mark.
    15. Check column i the same way, with the two indexes swapped.
    16. Check the main diagonal (0,0), (1,1), (2,2) after the loop.
    17. Check the other diagonal (0,2), (1,1), (2,0).
    18. Return '.': if no line matched, nobody has won.

    The solution in Java

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

    Java details worth knowing:

    • Arrays of arrays. char[][] is an array whose elements are char arrays, and new char[3][3] allocates all of them. Until the constructor fills them, every cell holds the default char value '\u0000', not '.', so the constructor's loops are needed.
    • char uses single quotes. 'X' is a char and "X" is a String. Comparing with == and != is correct for char, a primitive, which is not true of strings.
    • The conditional operator. (player == 'X') ? 'O' : 'X' yields 'O' when the test is true and 'X' otherwise, and the result is assigned back to player.
    • Chained comparisons. Java has no a == b == c for three values, so the test is written as a == b && b == c. With && the checks stop at the first false one.
    • Printing a char result. The driver prints game.winner() + " wins!". Joining a char to a String gives text, so the output is X wins!. Adding two char values is different: with char x = 'X', o = 'O', the expression x + o is an int and prints 167, while "" + x + o prints XO.

    Complexity

    The board has a fixed size, so every method does a fixed amount of work: move is O(1), and winner makes at most eight line checks. The constructor fills nine cells. The extra space is the nine-cell board and one char, which is O(1).

    Edge cases and common mistakes

    • Changing the turn on an ignored move. In the second game, X tries (0, 0) a second time. If the turn passed anyway, the following marks would land on the wrong players and the games would end differently. The guard returns before the turn changes.
    • Skipping the empty-cell test in winner. On a new board, three '.' cells in a row are equal, so the method would return '.' at once from an empty first row, even when a later line holds a win. Keeping != '.' in every check avoids that.
    • Forgetting a line. The eight lines are three rows, three columns and two diagonals. The diagonal (0,2), (1,1), (2,0) is the one most often missed.
    • Moves after a win. move doesn't check for a winner, so it keeps accepting free cells. After X completes the top row, playing another cell doesn't change winner(), which still returns 'X'.
    • A draw. A full board with no line gives '.', the same answer as a game still in progress. The driver prints No winner: . for both.
    • Indexes outside 0 to 2. The lesson promises valid indexes. move(3, 0) would throw an ArrayIndexOutOfBoundsException.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free