Tic Tac Toe C++

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Overview

The tic tac toe game is a strategic game played with two players. The tic tac toe game can also be played on a computer by implementing the game using the C++ programming language. The implementation of the tic tac toe game in C++ will be a great project to understand the concepts of C++ and apply them in real-life scenarios.

What are We Building?

We will be building a tic tac toe C++ game that can be played by a single player and a computer or with two players from the terminal. The C++ programming language is used to build the game.

How to Play this Game?

The tic tac toe proceeds by the following rules of the game,

  • There are two players in the game. The game board is a table with an equal number of rows and columns. The most used game board will be of the 3 X 3 dimension.

3X3 Game Board

  • A player can select either an X symbol or an O symbol to play the game.
  • A player starts his play by marking his symbol in any of the cells on the table. Then another player performs the same with another cell in the table. A cell that is marked with a symbol can't be changed throughout the game.
  • The winner of the game is declared when three cells in the horizontal, vertical, or diagonal directions have been consecutively marked by the same symbol.

3X3 Game Board Win

  • The game continues with alternative turns till all the cells are filled which indicates a draw or a winner is reached.

Pre-Requisites

The following concepts should be known to implement tic tac toe in C++,

  • Functions are used to break down the code to make the code more user-readable and reusable. Learn more about functions in C++.
  • Different data types are used to store the values used throughout the project. Learn more about data types in C++.
  • Conditional statements are used to take different actions based on the response made by the user. Learn more about conditional statements in C++.
  • Jump Statements are used in the last part of the program to prevent errors. Jump statements are used to jump over a piece of code. Learn more about Jump statements in C++.
  • Loops are used to repeat the same action until a winner or a draw is reached. Learn more about Loops in C++.
  • The concept of Object Oriented programming is implied to create objects for the player and game. Learn more on OOPS in C++.

How are We Going to Build the Tic Tac Toe Game Using C++?

The following steps are followed to build the tic tac toe game in C++,

  • Creating two classes for the player and the game board.
  • Creating functions to create the game board and display the game board.
  • Implementing functions to select the mode of the game, either single or two players.
  • Creating functions to get input from the player to mark the symbol of the player on the cell.
  • Implementing the logic to make the move by computer.
  • Creating functions to check if there is a winner in the game.
  • Allowing multiple iterations until the game ends in a draw or a winner is reached.

Final Output

The output of the program is displayed below,

Wondering why the sentence 'Turn of Machine' is printed three times? To understand that this is not an error, read the implementation of the program.

Requirements

The iostream library has declarations of the objects such as cin, and cout and is used to get input and deliver output to the user.

The cmath library has to be included to use functions such as ceil() or floor() and perform mathematical operations like sin(), cos() etc..

The string library is used to handle strings in C++ and has many useful functions to perform string operations like separating, concatenating, and comparing strings in C++.

The std namespace or the standard namespace is like a space inside which all the libraries are declared. So we must use the namespace using the using namespace std syntax or we can use the scope operator(::) around functions like cin and cout(std::cout) to indicate the function belongs to the std namespace.

Some of the functions used in the program are,

  • The rand() function is used to return a random number between 0 and RAND_MAX. The value of RAND_MAX is variable but will be at least 32767.
  • The ceil() function takes a float or double number as a parameter and returns a number rounded to the upper limit. For example, the function ceil(2.4) returns 3 and the function ceil(1.8) returns 2.

Building Tic Tac Toe Game Using C++

The first step in building the tic tac toe C++ game is to include all the required libraries and define the macros useful in the project.

The #define pre-process derivative is used to define a macro in the program. A macro is a constant variable or segment of code that will be replaced with the specified value during the compilation of the program. The macro #define Dimension 3 depicts the macro named Dimension with value 3. These macros are used to increase the performance of the program as macros are replaced with their values during the initial process of compilation. Learn more about macros and pre-process directives.

The next step involves declaring the player and the game class of the tic tac tow in C++. The player class has details about the player and the game class has details about the game and the interactions of the player and game.

The private variable name is only accessible within the class Player. The function PlayerName() is called a Getter function and is used to allow other classes to access the private variable of the class. The this variable makes the variable name belongs to the class to which the function belongs.

The Player(string n) is called the Constructor of the class and is called when an object of the class Player is created. It is used to initialize the name of the player on creating an object or instance of the Player class. Learn more about constructors in C++.

The Game class has a 2-dimensional character array that will store the process of the tic tac toe C++ game and act as the game board. The count variable keeps track of the number of cells that are filled in the 2D array to find whether the match ends in a draw. This will be discussed in the later part of the article.

Many functions are included in the public section of the Game class. The functions are explained consecutively with code.

The first step in creating the game board is initializing the 2D array with empty values. The CreateBoard() functions illustrates this,

  • Two for loops are used to iterate over the 2D array. The first for loop iterates over the rows of the array and the second for loop iterates over the column of the row.
  • These two loops are used to initialize all cells in the array with empty characters.

The showBoard() function is used to display the contents of the game board of the tic tac toe C++ game to the players. The implementation of the function is given below,

The showBoard() function uses two loops to display the contents of the 2-dimensional gameboard array to the player.

The \t is the tab character that is used when a space about the space left by the tab key is required. The \n is the new line character and marks the start of a new line.

The PlayerTurn() function is used to get the choice of the cell to be marked by the player and mark the location with the player symbol.

  • The position variable is used to store the position received from the player. For a 3X3 array, the position in the array will be similar to the following image,

Positions in a 3x2

  • The row at which the position is present is found by dividing the position by the Dimension and using the ceil() function to get the upper limit of the decimal.
  • The column at which the position appears has been found by finding the remainder of the division between the (position-1) and the Dimension. The position is subtracted by 1 because the array starts with the index 0 whereas the position starts with index 1.
  • All the positions are initially initialized with an empty character and this is utilized to check if there are any elements in the position given by the user.
  • If the position is free, the name of the player is compared with Player 1 and if the name of the current player was player 1, an X is marked, else an O is marked at the position. Here row-1 is used as the array index starts with 0.
  • Finally count is incremented to state that a cell has been filled with a symbol and the game board is displayed using the showBoard() function of tic tac toe in C++.

The compare() function is used to compare two strings for equality. The syntax for compare() function is as follows,

The function returns 0 if both the strings are equal and a value less than 0 if the string1 is smaller than 0 and a value greater than 0 if the string1 is greater than string2.

In the above piece of code, conditional operators are used to evaluate the condition provided by the compare() function. Learn more about conditional or ternary operator.

The MachineTurn() function is used to make a random move automatically and is used to play with machines in a single-player game.

The random position is generated by using the rand() function and is made under the limits of the matrix by finding the remainder between the random number and the (maximum position+1) in the matrix. Then all the steps following are similar to the previous function.

The CheckWin() function is used to if there is a winner in the tic tac toe C++ game or if the game has ended up as a draw. If there is a winner in the game, the function will return the name of the winner or in the case of a draw, the function will return the string Draw and in other cases, an empty string will be returned.

  • A draw occurs when the count has reached the maximum position on the game board and there is still no winner in the tic tac toe game in C++.

  • There are 6 variables r1,r2,c1,c2,d1,d2 that are used to check if a player has his symbol in three consequentive positions either in vertical, horizontal, or diagonal directions.

  • For vertical direction, the variable r1,r2 are used. The variable r1 represents player 1 and r2 represents player 2. The position is checked for the symbol in the inner loop and the variable is incremented respectively. A player is declared the winner if the number of times the variable is incremented becomes equal to the Dimension.

  • For horizontal direction, instead of checking consequent rows, columns are checked and variables c1,c2 are incremented.

  • For diagonal direction, only the diagonal positions are checked and the variables d1,d2 are incremented.

  • The name of the player that won the game is found by finding which variable among the 2 has the value the same as Dimension.

Finally, we have the main function in which the objects of the classes are created and the functions are called.

  • First, a Game object is created and the game board is created in the tic tac toe C++ game.
  • In the case of a single player, a Player object is created and the PlayerTurn(Player) and MachineTurn() functions are called alternatively. For a double-player game, two Player objects are created, and the PlayerTurn() function is called twice.
  • The CheckWin() function is called two times in each case since there are possibilities for a player to win after each of his moves. The goto statement is used when the result is already found and there is no need for the next player to play.

What More Could Be Done in the Program?

  • The MachineTurn() function can be optimized using the MinMax Algorithm of game theory to predict the next movement of the opponent and place the symbol in accord with the prediction.

  • Colors can be added to display the X in red color and O in another color. Background color can also be added to differentiate the game board from the surrounding.

A background and foreground color can be added by using the system() function. The system() function to give color to the terminal has the following syntax

All the colors are represented as numbers and range from 0 to F. For example, the color 0 depicts black and the color 1 depicts Blue and the color F depicts Bright white.

To have a background of white and text or foreground in Blue we can use the following code,

Then to color a separate letter such as coloring the letter X as red and the letter O as Green, we can use the textcolor(int color) function. The function takes the number that represents the color as the parameter. Unlink, the system function the numbers range from 0 to 15 whereas 15 represents white and 0 represents black.

The textcolor() function is present in the conio.h library in the Borland C standards and is not present in modern C or C++ libraries, but we can include the source code of the function in our program to use the function. Please note that the following code will work only in windows and the windows.h header must be included in the program.

The source code of the textcolor() function with its implementation to draw a game board with red colored X and green colored Y is given as follows,

The above program will output red colored X and green colored Y. This can be used to create a colorful tic tac toe C++ game. The output of the above example is as follows,

Colored 3x2 Game Board

Testing

The code can be tested for many cases such as the following,

  • If a cell is occupied by a symbol and the user tries to select the cell. In such a case, an output indicating the cell is already selected will be displayed. The sample output for this case is,
  • If the cell doesn't exist on the gameboard. In such a case, a message depicting that the choice is invalid is displayed. The sample output depicting this case is,
  • There are two modes in the game indicated by numbers 1 and 2. If the player presses any other numbers, the program will exit itself with the exit(0) function.

Whatโ€™s Next?

A more challenging task can be creating a more interactive tic tac toe game in C++. The game can allow the user to select the cells by clicking on the cells using the cursor. We will now dive into the basics of creating such a tic tac toe C++ game.

The primary requirement for such a game will be as follows,

  • To detect the click of the cursor during the execution of the program.
  • To get the coordinates of the cursor click and map the coordinates with the coordinates of the gameboard to mark the symbol of the player.

The following code can be used to detect the click of the cursor during the execution of the program and get the coordinates of the click.

  • The keypressed() function has the parameter VK_LBUTTON which depicts the left button on the mouse with a hexadecimal value of 0x01. This value is computed with the AND operation to find if the user is clicking the button.
  • The GetCursorPos(POINT) function gets the current position of the cursor and stores the value in the point object.
  • The coordinates in the point object can be accessed by the x and y data members.

The sample output is,

Following this, a gameboard can be created and the coordinates of each cell in the board can be found a program that will fill the cells with symbols of players based on those coordinates can be developed. Implementing this will be more fun and can be useful to learn a lot more C++ concepts.

Supercharge your coding proficiency with our hands-on Machine Coding Tic Tac Toe - LLD Case Study Course. Don't miss this opportunity!

Conclusion

  • The project on building a tic tac toe C++ game uses the concepts of Object Oriented programming.
  • Functions are used to simplify the code into multiple modules and make the code easily understandable and reusable.
  • Condition statements like if, if else and jump statements like goto are used to control the flow of program execution based on user inputs.
  • Loops were used to iterate over the 2-dimensional array and perform repetitive tasks like playing the game.
  • The edge cases of the program have been explained along with solutions to edge cases in the testing section.
  • Far more concepts like giving color to text and background along with the min-max algorithm of game theory were introduced.
  • A basis of an innovative idea to create an interactive tic tac toe in C++ was introduced.