Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Tic Tac Toe Game?
3.
Rules for the Game 
4.
How can a Player win the Game?
5.
Implementation of the Game
6.
Winning Strategy
7.
Pseudocode for the Game 
8.
Program in C and C++
8.1.
Code in C Language.
8.2.
Code in C++ Language 
9.
Explanation of the Code
10.
Output Discussions 
11.
Frequently Asked Questions
11.1.
What is the Tic Tac Toe game?
11.2.
How does a player win this game?
11.3.
How many players can play this game?
11.4.
How does the game get drawn? 
11.5.
How many positions are there on the game board?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

Implementation of Tic Tac Toe Game

Author Gunjan Batra
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Playing games is always fun. We all have played the Tic Tac Toe game at least once. The Tic tac toe game is a very popular coding game.

Tic Tac Toe Game

In this blog, we will learn about the Implementation of Tic Tac Toe Game. This blog will further cover the best approach to play, winning strategy, and last but not least, we will look at the output. 

Also See, Binary to Hex Converter and C Static Function.

What is a Tic Tac Toe Game?

In a 3*3 2D matrix, we play Tic Tac Toe Game. This is a very popular and easy-to-play game. Between two players, we play this game. 

What is Tic Tac Toe game?

The matrix is designed with empty boxes, and the user fills in their identity mark. The first player can be a computer, the other will be a user, or both players can be users. 

It is a game of X and O, referred to as crosses and circles. 

The user whose vertical, horizontal, and diagonal rows have the same marks wins the game.

If any row, column, or diagonal matches with the same mark, the game should announce the winner and restart another game.

The game will be drawn if all spots are filled and no row, column, or diagonal match the same identity. 

Let's further understand the rules of the game.

You can also read about dynamic array in c and Short int in C Programming

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Rules for the Game 

To play any game, we must know the rules to play that game. Below are the rules for playing the Tic Tac Toe game:

  1. Two users will play this game. Either one can be a computer, or both can be humans.
     
  2. The game will be played in a 3*3 grid only.
     
  3. Both of them should have their identity marks. One must have a cross and another circle.
     
  4. The game must say that the input is wrong when the spot is already filled.
     
  5. The computer must ask for input from the user. They must ask about the spot where they want the user to put their mark.
     
  6. When the row, column, or diagonal has the same marks, the game should display the winner and end it.

 

Click on the following link to read further: Features of C Language

How can a Player win the Game?

Winning a game is everyone's choice. To win the game, the player must ensure that their row, column, or grid, diagonal, must be filled with his identity. 

How can a player win the game?

The winning player is announced when the row or column or the diagonal of the matrix is filled with the same identity. 

Each player gets an equal chance to play their side. 

You must ensure that you place your mark correctly and in a way that the player gets confused about where to place his other identity. 

Implementation of the Game

Don't worry about the Implementation of Tic Tac Toe Game. Below we have discussed how you can implement this game in your coding language.

Game

Ask the user to input a random number; if the number is even, let the game start with X(cross). 

If the number is odd, the game will begin with a circle.

In our pseudo code below, the game is played by two users. 

One is an X(cross), and the other is a circle. 

You can also implement the game by taking one user as a computer and the other as a human.

Winning Strategy

We all want to win the game.

It doesn't matter who starts the game but at the end which finishes first.

The player must ensure he plays the game with full concentration and dedication to win the game.

If both players play with their full potential, the game will be drawn, but no one will lose. 

To win the game, the player must play the chance so that the next player gets tricked and confused with his move.

The player who wants to win the game must put his identity mark in the spot in a way that the next player any move makes him win.

His mark should be where either row, diagonal, or column matches his identity mark, irrespective of the next player's move. 

Pseudocode for the Game 

Irrespective of the coding language, let us understand the pseudocode for the game.

  1. Let the game begin by taking a random number from the user. If the number is even, the game will start with X. If the number is odd, the game will begin with a circle.
     
  2. Present a 3*3 grid to the user. 
     

Make certain functions that perform the below actions:

  1. Ask for the spot where the player wants to put his mark. Take the input of the user where he wishes to place his identity. 
     
  2. Every player gets an equal chance to mark their spot. It goes one after the other.
     
  3. After every mark, follow some conditions to check the marks.
     
  4. Ensure that players only put their own identities.
     
  5. Ensure that the spots already filled are kept the same or modified.
     
  6. If the row, columns, or diagonal gets matched with the same identity, declare the winner.
     
  7. If all the spots are filled, and no match occurs, draw the game and restart the game.

Program in C and C++

Now let us code the game. Below, we have the Implementation of Tic Tac Toe Game in C and C++ programming languages. 

Code in C Language.

Below is the Implementation of Tic Tac Toe Game in C language. The explanation for the code is described later in the article. 

#include <stdio.h>
#include <conio.h>


char grid[10] = { 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' };


int findwinner();
void squareboard();


int main()
{
    int player = 1, check, wish;


    char spot;
    do
    {
        squareboard();
        player = (player % 2) ? 1 : 2;


        printf("Player %d, enter a digit:  ", player);
        scanf("%d", &wish);


        spot = (player == 1) ? 'X' : 'O';


        if (wish == 1 && grid[1] == '1')
            grid[1] = spot;
            
        else if (wish == 2 && grid[2] == '2')
            grid[2] = spot;
            
        else if (wish == 3 && grid[3] == '3')
            grid[3] = spot;
            
        else if (wish == 4 && grid[4] == '4')
            grid[4] = spot;
            
        else if (wish == 5 && grid[5] == '5')
            grid[5] = spot;
            
        else if (wish == 6 && grid[6] == '6')
            grid[6] = spot;
            
        else if (wish == 7 && grid[7] == '7')
            grid[7] = spot;
            
        else if (wish == 8 && grid[8] == '8')
            grid[8] = spot;
            
        else if (wish == 9 && grid[9] == '9')
            grid[9] = spot;
            
        else
        {
            printf("Invalid move by the player");


            player--;
            getch();
        }
        check = findwinner();


        player++;
    }while (check ==  - 1);
    
    squareboard();
    
    if (check == 1)
        printf("==>\aPlayer %d win. Congratulations!", --player);
    else
        printf("==>\aGame draw! Better luck next time!");


    getch();


    return 0;
}


/*********************************************
FUNCTION TO GIVE GAME STATUS
1 FOR THE GAME IS OVER WITH THE RESULT
-1 FOR THE GAME IS IN PROGRESS
O GAME IS OVER, AND NO RESULT
 **********************************************/


int findwinner()
{
    if (grid[1] == grid[2] && grid[2] == grid[3])
        return 1;
        
    else if (grid[4] == grid[5] && grid[5] == grid[6])
        return 1;
        
    else if (grid[7] == grid[8] && grid[8] == grid[9])
        return 1;
        
    else if (grid[1] == grid[4] && grid[4] == grid[7])
        return 1;
        
    else if (grid[2] == grid[5] && grid[5] == grid[8])
        return 1;
        
    else if (grid[3] == grid[6] && grid[6] == grid[9])
        return 1;
        
    else if (grid[1] == grid[5] && grid[5] == grid[9])
        return 1;
        
    else if (grid[3] == grid[5] && grid[5] == grid[7])
        return 1;
        
    else if (grid[1] != '1' && grid[2] != '2' && grid[3] != '3' &&
        grid[4] != '4' && grid[5] != '5' && grid[6] != '6' && grid[7] 
        != '7' && grid[8] != '8' && grid[9] != '9')


        return 0;
    else
        return  - 1;
}



/*******************************************************************
DRAW SQUAREBOARD OF TIC TAC TOE WITH PLAYERS' SPOT
 ********************************************************************/



void squareboard()
{
    // system("cls");
    printf("\n\t\tTic Tac Toe\n\n\n");


    printf("\tPlayer1 (X)  -  Player2 (O)\n\n");



    printf("       |       |     \n");
    printf("  %c    |  %c    |  %c \n", grid[1], grid[2], grid[3]);


    printf("_______|_______|_______\n");
    printf("       |       |     \n");


    printf("  %c    |  %c    |  %c \n", grid[4], grid[5], grid[6]);


    printf("_______|_______|_______\n");
    printf("       |       |     \n");


    printf("  %c    |  %c    |  %c \n", grid[7], grid[8], grid[9]);


    printf("       |       |     \n\n");
}


Code in C++ Language 

Below is the Implementation of Tic Tac Toe Game in C++ language. The explanation for the code is described later in the article.  

#include <iostream>
using namespace std;
 char grid[10] = { 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
 /*******************************************************************
DRAW SQUAREBOARD OF TIC TAC TOE WITH PLAYERS' SPOT
 ********************************************************************/
 void display(){
    
     cout<<"\n \t \t Tic Tac Toe \n \n \n";
     cout<<" \t Player1 (X)  -  Player2 (O) \n \n";



     cout<<"       |       |     \n";
    cout<<"  "<<grid[1]   <<"    |"<<"  "<<grid[2]  <<"    |"<<"  "<<grid[3]   <<"    \n";
    cout<<"_______|_______|_______\n";
    cout<<"       |       |     \n";
    cout<<"       |       |     \n";
    cout<<"  "<<grid[4]   <<"    |"<<"  "<<grid[5]  <<"    |"<<"  "<<grid[6]   <<"    \n";
    cout<<"_______|_______|_______\n";
    cout<<"       |       |     \n";
    cout<<"       |       |     \n";
    cout<<"  "<<grid[7]   <<"    |"<<"  "<<grid[8]  <<"    |"<<"  "<<grid[9]   <<"    \n";
    cout<<"       |       |     \n";
     }
     /*********************************************
FUNCTION TO GIVE GAME STATUS
1 FOR THE GAME IS OVER WITH THE RESULT
-1 FOR THE GAME IS IN PROGRESS
O GAME IS OVER, AND NO RESULT
 **********************************************/
     
 int findwinner(char grid[])
{
    if (grid[1] == grid[2] && grid[2] == grid[3])
        return 1;
        
    else if (grid[4] == grid[5] && grid[5] == grid[6])
        return 1;
        
    else if (grid[7] == grid[8] && grid[8] == grid[9])
        return 1;
        
    else if (grid[1] == grid[4] && grid[4] == grid[7])
        return 1;
        
    else if (grid[2] == grid[5] && grid[5] == grid[8])
        return 1;
        
    else if (grid[3] == grid[6] && grid[6] == grid[9])
        return 1;
        
    else if (grid[1] == grid[5] && grid[5] == grid[9])
        return 1;
        
    else if (grid[3] == grid[5] && grid[5] == grid[7])
        return 1;
        
    else if (grid[1] != '1' && grid[2] != '2' && grid[3] != '3' &&
        grid[4] != '4' && grid[5] != '5' && grid[6] != '6' && grid[7] 
        != '7' && grid[8] != '8' && grid[9] != '9')


        return 0;
    else
        return  - 1;
}


 int main(){


     int player = 1, check, wish;
     char spot;


    do
    {
        display();
        player = (player % 2) ? 1 : 2;


        cout<<" Player"<<player<<" enter a digit ";
        cin>>wish;


        spot = (player == 1) ? 'X' : 'O';


       if (wish == 1 && grid[1] == '1')
            grid[1] = spot;
            
        else if (wish == 2 && grid[2] == '2')
            grid[2] = spot;
            
        else if (wish == 3 && grid[3] == '3')
            grid[3] = spot;
            
        else if (wish == 4 && grid[4] == '4')
            grid[4] = spot;
            
        else if (wish == 5 && grid[5] == '5')
            grid[5] = spot;
            
        else if (wish == 6 && grid[6] == '6')
            grid[6] = spot;
            
        else if (wish == 7 && grid[7] == '7')
            grid[7] = spot;
            
        else if (wish == 8 && grid[8] == '8')
            grid[8] = spot;
            
        else if (wish == 9 && grid[9] == '9')
            grid[9] = spot;
            
        else
        {
            cout<<"Invalid move by the player";


            player--;
          
        }
        check = findwinner(grid);


        player++;
    }while (check ==  - 1);
    
    display();
    
    if (check == 1)
        cout<<"==>\aPlayer"<< -- player<<" win. Congratulations!";
    else
        cout<<"==>\aGame draw! Better luck next time!";
        
    return 0;
    
 }

Explanation of the Code

Now, let's understand the above code.

In the main function, we have tried to take input from the user through scanf. We assign that identity mark to the desired square board with the digit mentioned by the user. From the main function, we call our other functions.

We have two functions named squareboard and findwinner. 

squareboard

The function squareboard is used to create a 3*3 square. The digits that are filled in the square are from 1-9. 

findwinner 

This function uses the if-else statement to find and check the winner. We have created some conditions a player must satisfy to win the game.

The row, column, or diagonal must be filled with their identity mark to win the game.

Check out this problem - Optimal Strategy For A Game

Output Discussions 

  • Below are screenshots of how two players play this game. The first player is given the identity X, and player 2 with identity O.
     
  • Both players are asked to input a number and fill in their identity later. When a player tries to put an identity in the already filled spot, the code generates an error and asks the player to input a new spot to fill the grid. 
     
  • The game's output will be displayed when either of the players wins or the game is drawn. The game will be won when the row, column, or diagonal match the same identity. 
     
  • Let's start the game. Run the code, and the first output you receive is shown below:
Output
  • The first output is the game board of a 3*3 grid with the name of the game, i.e., Tic Tac Toe, which is shown to the user. Player 1 is assigned with the identity X, and player 2 is assigned with the identity O. 
     
  • The grid that is shown to the user consists of digits from 1 to 9. A player is asked to input a number, and that digit will be marked with their identity. 
     
  • In the image shown above, the first input is made by player 1, and after that, the grid is again shown to player 2 to give their input for marking their identity. 
     
  • The next is the input given by player 2. The number mentioned by player 2  is further marked with their identity.
Output
  • The game continues until we get the winner or the game is drawn. Next, the grid is shown to player 1 to take the input and mark that digit with their identity. After the input is received from the user, the input is marked. 
     
  • After receiving the input, the grid is further checked for two conditions, i.e., winner or drawn.  When no above condition is satisfied, the grid is presented to player 2.
Output
  • Player 2 is shown the grid after the digit is marked with the identity of player 1 in the previous section. Now player 2 provides a number to mark their identity. The exact process happens. The grid is checked for the winner or whether the game is drawn. 
     
  • When no condition is true, the grid is presented to player1. 
     
  • Player 1 gives a number that is already filled. The game shows an error, i.e., an  Invalid move, by the player and asks them to input a new number.
Output
  • Player 1 is asked to input a number, and then the grid is checked for two conditions, i.e., the winner or drawn.
     
  • The grid is shown to player 2 for entering the number when no such condition gets satisfied. 
Output
  • Player 2 provides their number, and the grid is checked for two conditions, i.e., winner or drawn. 
     
  • To declare a player as the winner, the row, column, or diagonal must be filled with the same identity.  The winner is declared when either row, column, or diagonal gets matched.
     
  • The game gets ends, and the winner is displayed.
     

You can practice by yourself with the help of online c compiler.

Frequently Asked Questions

What is the Tic Tac Toe game?

It is a 3*3 2D matrix. This game is played between two players. You can either play with a computer or with two users. 

How does a player win this game?

The game will be won when the row, column, or diagonal match the same identity. The player whose identity gets matched will win this game. 

How many players can play this game?

Two players will play the game. It can also be played by a computer and a user or two users, but the player count should be only 2. 

How does the game get drawn? 

The game is drawn when all the grid spots get filled up by the identity marks, and no row or column or diagonally gets matched with the same identity.

How many positions are there on the game board?

The user can mark his identity in nine positions(3*3). The user gets the option to choose his identity spot.  

Conclusion

In this article, we have discussed the implementation of Tic Tac Toe game. Further, the blog looked at the winning strategy and how a player can win this game.

To learn more about the game, refer to the blogs mentioned below: 

Tic Tac Toe Puzzle 

Tic Tac Toe GUI In Python using PyGame

Tic Tac Toe Game in Swing

Tic Tac Toe Board using Turtle

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our coursesrefer to the mock test and problems look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Previous article
Star Patterns Program in C
Next article
Number pattern programs in C
Live masterclass