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 public TicTacToe() fills the private char[,] board (3 by 3, read as board[r, c]) 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() {
        var game = new TicTacToe();
        game.Move(0, 0);
        game.Move(1, 0);
        game.Move(0, 1);
        game.Move(1, 1);
        game.Move(0, 2);
        Console.WriteLine(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.WriteLine(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.WriteLine(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.WriteLine(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.WriteLine("No winner: " + game.Winner());
        game = new TicTacToe();
        Console.WriteLine("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

    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, and an empty cell holds '.'.

    • The constructor fills the private char[,] board with '.', and the private char player starts as 'X'.
    • Move(int r, int c) plays a turn. If the cell is taken, the call is ignored and it is still the same player's turn. Otherwise it places the current mark and hands the turn to the other player.
    • Winner() returns 'X' or 'O' when that player has three in a row, a column or a diagonal. It returns '.' otherwise, which covers a game in progress, an empty board and a draw.

    The driver plays six games. In the first, X fills the top row and wins. In the second, X tries to play on a taken cell: that move is ignored and O wins the middle column. The third and fourth games are X's two diagonals, the fifth is a full board with no line, and the sixth is a new game with no moves.

    Approach: eight lines to check

    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 together, and the two diagonals come after the loop.

    Each check has the same shape: the first cell is not '.', the first equals the second and the second equals the third. The first test matters. Three empty cells are equal to each other, but they are not a win.

    For Move, the guard comes first. Check whether the cell is taken and leave before touching the board or the turn. Only a successful move passes the turn on.

    Step by step

    1. Declare the class TicTacToe. Every object is a separate game with its own memory.
    2. Add the board as private char[,] board = new char[3, 3];. This is a rectangular 2D array, read as board[r, c] for row r, column c.
    3. Add private char player = 'X';. X moves first, so every new game starts with that mark.
    4. Write the constructor public TicTacToe(). It has the class's name and no return type, and runs on new TicTacToe().
    5. Loop over the rows with i.
    6. Nest a loop over the columns with j.
    7. Set board[i, j] = '.'. 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] != '.') return;. Nothing changes and the turn stays.
    10. Place the mark: board[r, c] = player;.
    11. Pass the turn with a conditional expression: player = (player == 'X') ? 'O' : 'X';.
    12. Declare Winner as public char Winner().
    13. Loop i over 0, 1 and 2; each pass looks at row i and column i.
    14. Check row i: first cell not a dot, and all three cells equal. Return that mark.
    15. Check column i the same way, with the two indexes swapped.
    16. After the loop, check the main diagonal: (0,0), (1,1), (2,2).
    17. Check the other diagonal: (0,2), (1,1), (2,0). The row goes up by one while the column goes down by one.
    18. Return '.'. Reaching the last line means every check failed.

    The solution in C#

    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() {
            var game = new TicTacToe();
            game.Move(0, 0);
            game.Move(1, 0);
            game.Move(0, 1);
            game.Move(1, 1);
            game.Move(0, 2);
            Console.WriteLine(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.WriteLine(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.WriteLine(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.WriteLine(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.WriteLine("No winner: " + game.Winner());
            game = new TicTacToe();
            Console.WriteLine("No winner: " + game.Winner());
        }
    }
    

    The program prints:

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

    C# details

    • char uses single quotes, 'X'. Double quotes make a string, and comparing a char to a string does not compile.
    • char[,] is one block of memory indexed with a comma, board[r, c]. A jagged char[][] would be indexed board[r][c] and would need each row created separately.
    • A new char[3, 3] is not full of dots. Its cells hold the character with code 0, so board[0, 0] == '.' is false on a fresh array. That is why the constructor fills the board.
    • Joining a char to text. game.Winner() + " wins!" works because the other operand is a string, and it prints X wins!. Adding a char to an int adds numbers instead: with w holding '.', w + 1 is the number 47, because the code of '.' is 46. Putting an empty string first, "" + w + 1, gives .1.
    • The nested for without braces. The constructor uses two for statements and one assignment as the body of the inner one. Braces make that easier to read.
    • The conditional expression test ? a : b gives a when the test is true and b otherwise.

    Complexity

    The board has a fixed size, so everything is constant time: Move does a few operations, Winner checks at most eight lines, and the board always holds nine cells.

    Edge cases and common mistakes

    • A taken cell. In the second game, X's second move on (0, 0) is ignored. If it also passed the turn, the marks would get out of order and X would lose a turn.
    • Empty lines. Without the != '.' test, three empty cells count as a line. If row 0 is empty and X fills row 1, the loop meets row 0 first and returns '.', so X's win is missed.
    • Draw. A full board with no line returns '.', the same as a game in progress.
    • Playing after a win. Move does not stop a finished game. If X completes the top row and the players keep going, Winner() still returns 'X', because the line is still there.
    • Swapped indexes. The column check is the row check with board[i, 0] turned into board[0, i]. Writing row-style indexes twice checks rows twice and never finds a column.
    • Wrong second diagonal. It runs through (0,2), (1,1), (2,0), not (0,2), (1,2), (2,2).

    Testing

    • Moves (0,2), (0,0), (1,1), (0,1), (2,0): X holds the anti-diagonal, so Winner() returns X.
    • Two moves only, (0,0) and (1,1): Winner() returns ..
    • A brand-new game: Winner() returns ..
    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