How to create a basic Tic Tac Toe game in C#

We all have played it sometime in our life. What I used to do during classes was making crosses or O’s on the copy. It’s a simple two player game composed of 3x3 matrix. And both the player draws either X or O on any free cell of the matrix. The first player marks X and the second player marks O alternatively. The one who have three respective matches horizontally or vertically or diagonally wins.
Implementing a two player game doesn't need complex algorithm or advanced programming knowledge. We can implement it with general programming practices. Let’s implement this game programmatically.

Implement it:

For implementing this game we need a 3x3 matrix. Hence declare a 3x3 character matrix.
private char[,] Board;
The reason for selecting char data type is not a rocket science just because it relates to the real game where we store single character in each cell.
We would also like to track whose chance is next. For that we have declared an integer variable.
private int CurrentPlayer;

So that much we need to store at the root level. Now we need some functions to make our game work properly. Hence I have defined four functions. Each has been described below.

NewGame()

public void NewGame()
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            Board[i, j] = '-';
        }
    }

CurrentPlayer = 1;
}
The primary work of this function is to start a new game. It just assigns ‘-‘ to each cells of matrix which I have used in substitute of blank space. It specifies that the current cell is empty. In this function we are also setting the first player as current player.

Move()

public void Move(int Row, int Col)
{
    //Check for a valid row and column number. (1-3)
    if (Row >= 1 && Row <= 3 && Col >= 1 && Col <= 3)
    {
        //Check if the current position is empty or not.
        if (Board[Row - 1, Col - 1] == '-')
        {
            //If the current player is 1 then assign X to the current position of board. 
            //Else assign 0. Also change the current player.
            if (CurrentPlayer == 1)
            {
                Board[Row - 1, Col - 1] = 'X';
                CurrentPlayer = 2;
            }
            else
            {
                Board[Row - 1, Col - 1] = 'O';
                CurrentPlayer = 1;
            }
        }
        else
        {
            Console.WriteLine("The current position is not free. Try again.");
        }
    } 
    else
    {
        Console.WriteLine("Row or column number out of range. Try again.");
    }
}
Move function allow us to perform a valid move. It accepts two integer values row and column of the matrix where we want to perform a move. If the row and column is between 1 and 3 (inclusive) then only we can perform any move else prints “Row or column number out of range” error message. If it’s in range check for an empty cell and then assign X or O to the matrix[row,col] according to the current player. Also change the current player on successful move. Display a message for non-empty cell.

Check()

public char Check()
{
    char Result = '=';

    //Checks if the game will continue or not.
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            if (Board[i, j] == '-')
            {
                Result = '-';
            }
        }
    }

    //Checks horizontally for any match. First checks the first row, then second and then third.
    if (Board[0, 0] == Board[0, 1] && Board[0, 0] == Board[0, 2])
        Result = Board[0, 0];
    else if (Board[1, 0] == Board[1, 1] && Board[1, 0] == Board[1, 2])
        Result = Board[1, 0];
    else if (Board[2, 0] == Board[2, 1] && Board[2, 0] == Board[2, 2])
        Result = Board[2, 0];

    //Checks vertically for any match. First checks the first column, then second and at last the third one.
    if (Board[0, 0] == Board[1, 0] && Board[0, 0] == Board[2, 0])
        Result = Board[0, 0];
    else if (Board[0, 1] == Board[1, 1] && Board[0, 1] == Board[2, 1])
        Result = Board[0, 1];
    else if (Board[0, 2] == Board[1, 2] && Board[0, 2] == Board[2, 2])
        Result = Board[0, 2];

    //Checks diagonally for any match.
    if (Board[0, 0] == Board[1, 1] && Board[0, 0] == Board[2, 2])
        Result = Board[0, 0];
    else if (Board[0, 2] == Board[1, 1] && Board[0, 2] == Board[2, 0])
        Result = Board[0, 2];

    return Result;
}

This function checks for any win, lose or draw. In tic-tac-toe a player wins if he succeeds to draw three consecutive X or O horizontally, vertically or diagonally. I haven’t used anything complex here just simple if-else for checking all cells. It returns one of the following character which means:
‘-‘ The game will continue more as none has won or drawn.
‘=’ The game ends in a draw.
‘X’ First player wins.
‘O’ Second player wins.

PrintBoard()

public void PrintBoard()
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            Console.Write(Board[i, j] + " ");
        }
        Console.WriteLine();
    }
}
The simplest function of all. Just prints the matrix on to the screen.

Now let’s just combine it all together. For that we need a main function that will implement all. Here it’s all together.

Program:

using System;

namespace CodeForWin
{
    /// 
    /// TicTacToe being an interesting game. Everybody has played in his childhood.
    /// This class can be used to play a tic tac toe game on the console. 
    /// This class implements two player game.
    /// 
    class TicTacToe
    {
        //3x3 tic tac toe game board.
        private char[,] Board;

        //Specifies the current player.
        private int CurrentPlayer;

        /// 
        /// Allocates a new object and initlizes the board to its initlial state.
        /// 
        public TicTacToe()
        {
            Board = new char[3, 3];
            NewGame();
        }

        /// 
        /// Starts a new game and initializes the game board to its initial state.
        /// - means the position is empty.
        /// x means the position is occupied by first player.
        /// 0 measn the position is occupied by second player.
        /// 
        public void NewGame()
        {
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Board[i, j] = '-';
                }
            }

            CurrentPlayer = 1;
        }

        /// 
        /// Performs a move to the specified position and occupies the position by the current player.
        /// 
        /// Position on the board. Row and column no(1-3) of the tic tac toe board.
        public void Move(int Row, int Col)
        {
            //Check for a valid row and column number. (1-3)
            if (Row >= 1 && Row <= 3 && Col >= 1 && Col <= 3)
            {
                //Check if the current position is empty or not.
                if (Board[Row - 1, Col - 1] == '-')
                {
                    //If the current player is 1 then assign X to the current position of board. 
                    //Else assign 0. Also change the current player.
                    if (CurrentPlayer == 1)
                    {
                        Board[Row - 1, Col - 1] = 'X';
                        CurrentPlayer = 2;
                    }
                    else
                    {
                        Board[Row - 1, Col - 1] = '0';
                        CurrentPlayer = 1;
                    }
                }
                else
                {
                    Console.WriteLine("The current position is not free. Try again.");
                }
            } 
            else
            {
                Console.WriteLine("Row or column number out of range. Try again.");
            }
        }

        /// 
        /// Checks the current board status. Whether any player has won the game or the game is draw or the game will continue more.
        /// 
        /// 
        /// Returns a character. 
        /// Returns X if first player has won.
        /// Returns 0 if the second player has won.
        /// Returns = if the game is draw.
        /// Returns - if the game will continue more.
        /// 
        public char Check()
        {
            char Result = '=';

            //Checks if the game will continue or not.
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    if (Board[i, j] == '-')
                    {
                        Result = '-';
                    }
                }
            }

            //Checks horizontally for any match. First checks the first row, then second and then third.
            if (Board[0, 0] == Board[0, 1] && Board[0, 0] == Board[0, 2])
                Result = Board[0, 0];
            else if (Board[1, 0] == Board[1, 1] && Board[1, 0] == Board[1, 2])
                Result = Board[1, 0];
            else if (Board[2, 0] == Board[2, 1] && Board[2, 0] == Board[2, 2])
                Result = Board[2, 0];

            //Checks vertically for any match. First checks the first column, then second and at last the third one.
            if (Board[0, 0] == Board[1, 0] && Board[0, 0] == Board[2, 0])
                Result = Board[0, 0];
            else if (Board[0, 1] == Board[1, 1] && Board[0, 1] == Board[2, 1])
                Result = Board[0, 1];
            else if (Board[0, 2] == Board[1, 2] && Board[0, 2] == Board[2, 2])
                Result = Board[0, 2];

            //Checks diagonally for any match.
            if (Board[0, 0] == Board[1, 1] && Board[0, 0] == Board[2, 2])
                Result = Board[0, 0];
            else if (Board[0, 2] == Board[1, 1] && Board[0, 2] == Board[2, 0])
                Result = Board[0, 2];

            return Result;
        }

        /// 
        /// Prints the current status of the game board.
        /// 
        public void PrintBoard()
        {
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(Board[i, j] + " ");
                }
                Console.WriteLine();
            }
        }

        static void Main(string[] args)
        {
            TicTacToe t = new TicTacToe();
            int r, c;
            string temp;

            while (true)
            {
                t.PrintBoard();
                Console.WriteLine("\nEnter the space separated row and column : ");
                temp = Console.ReadLine();
                r = Convert.ToInt32(temp.Split(' ')[0]);
                c = Convert.ToInt32(temp.Split(' ')[1]);
                t.Move(r, c);

                char ch = t.Check();
                switch (ch)
                {
                    case '=': Console.WriteLine("MATCH DRAW");
                        break;
                    case 'X': Console.WriteLine("PLAYER 1 WINS");
                        break;
                    case '0': Console.WriteLine("PLAYER 2 WINS");
                        break;
                }

                if (ch != '-')
                    break;
            }

            Console.ReadKey();
        }
    }
}

In the main function we have created an object of our class TicTacToe. In the loop what we are doing is
  1. Print the matrix.
  2. Take two integer values row and column.
  3. Call the Move() function with the row and column as parameter.
  4. Call the Check() function and store the character returned by the function name it ch.
  5. Check the value of ch for ‘-‘ ‘=’ ‘X’ ‘O’ and ‘-‘. And print the required message.
  6. Repeat in the loop until any player hasn't won or the game is not draw.
And we are done now.
Happy coding ;)
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment