Tic Tac Toe Game in C

Tic Tac Toe is a game in which two players pick X’s or O’s alternately in a matrix cell formed by two vertical and horizontal lines crossing each other. Each player tries to place three of their marks in a horizontal, vertical, or diagonal row. The player who put in this form will succeed in the game. In this article, we’ll write a program to play tic tac toe game in C language.

Example:
Tic Tac Toe Example

Problem Description

Write a C program to play the Tic Tac Toe game.

Problem Solution

We have to use 2D array to store the player sign. The 2D array will be initially empty that means every cell contains space character. On every move of the player, the cell will be filled by its input position.

We will build this program using C programming langauge in which we use a 2D array to store the cell position and update on every move.

Program/Source Code

Here is source code of the C program to play the Tic Tac Toe game. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C Program to Play the Tic Tac Toe Game
 */
 
#include <stdio.h>
 
// Globally declared 2D-array
char board[3][3];
 
// Function to initialize the game board
void initializeBoard()
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            board[i][j] = ' ';
        }
    }
    int count = 1;
    printf("\n\n\t  ");
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            printf("%d", count++);
            if (j < 2)
            {
                printf("  |  ");
            }
        }
        if (i < 2)
        printf("\n\t----------------\n\t  ");
    }
    printf("\n\n\n");
}
 
// Function shows the game board
void showBoard(int x, int y)
{
    printf("\n\n\t  ");
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            printf("%c", board[i][j]);
            if (j < 2)
            {
                printf("  |  ");
            }
        }
        if (i < 2)
        printf("\n\t----------------\n\t  ");
    }
    printf("\n\n\n");
}
 
// Function to update the game board
int updateBoard(int cell, char playerSign)
{
    int row = (cell - 1) / 3;
    int col = (cell - 1) % 3;
    int isValid = 1;
 
    // accessing already played cell number
    if (board[row][col] != ' ')
    {
        printf("\nInvalid: Cell is already Filled!\n");
        isValid = 0;
    }
 
    // valid cell position
    else
    {
        board[row][col] = playerSign;
    }
    showBoard(row, col);
 
    return isValid;
}
 
// Function to check the winner of the game
int checkWinner(char sg)
{
    // check all rows
    if (board[0][0] == sg && board[0][1] == sg && board[0][2] == sg ||
      board[1][0] == sg && board[1][1] == sg && board[1][2] == sg ||
      board[2][0] == sg && board[2][1] == sg && board[2][2] == sg)
    {
        return 1;
      }
      // check all columns
    else if (board[0][0] == sg && board[1][0] == sg && board[2][0] == sg ||
           board[0][1] == sg && board[1][1] == sg && board[2][1] == sg ||
           board[0][2] == sg && board[1][2] == sg && board[2][2] == sg)
    {
        return 1;
    }
    // check both diagonals
    else if (board[0][0] == sg && board[1][1] == sg && board[2][2] == sg ||
           board[0][2] == sg && board[1][1] == sg && board[2][0] == sg)
    {
        return 1;
    }
 
    // There is no winner
    return 0;
}
 
// Start your game from here
void playTicTacToe()
{
    int gameResult = 0;
    int cell = 0;
    int playCount = 0;
    int updationResult = 1;
 
    char playerSign = ' ';
 
    // start playing the game
    while (!gameResult && playCount < 9)
    {
        if (playCount % 2 == 0)
        {
            // player 1
            printf("\nPlayer 1 [ X ] : ");
            playerSign = 'X';
        }
        else
        {
            // player 2
            printf("\nPlayer 2 [ O ] : ");
            playerSign = 'O';
        }
        scanf("%d", &cell);
        if (cell > 0 && cell < 10)
        {
            updationResult = updateBoard(cell, playerSign);
            // if updation is possible
            if (updationResult)
            {
                gameResult = checkWinner(playerSign);
                // print the winner of the game
                if (gameResult)
                {
                    printf("\t *** Player %d Won!! ***\n", playerSign == 'X' ? 1 : 2);
                }
                playCount++;
            }
        }
        else if (cell == -1)
        {
            printf("\n\tGame Terminated\n");
            return;
        }
        else
        {
            printf("\nPlease Enter a valid cell value\n");
        }
    }
 
    // no one won the game
    if (!gameResult && playCount == 9)
    {
        printf("\n\t *** Draw...  ***\n");
    }
    printf("\n\t --- Game Over --- \n");
}
 
int main()
{
    printf("--------- Tic Tac Toe ----------\n\n");
 
    printf("\n* Instructions \n\n");
    printf("\tPlayer 1 sign = X\n");
    printf("\tPlayer 2 sign = O");
    printf("\n\tTo exit from game, Enter -1\n");
 
    printf("\n\n* Cell Numbers on Board\n");
    initializeBoard();
 
    char start = ' ';
    printf("\n> Press Enter to start...");
 
    scanf("%c", &start);
 
    if (start)
    {
        int userChoice = 1;
        // restart the game
        while (userChoice)
        {
            playTicTacToe();
            printf("\n* Menu\n");
            printf("\nPress 1 to Restart");
            printf("\nPress 0 for Exit");
            printf("\n\nChoice: ");
            scanf("%d", &userChoice);
            if (userChoice)
            {
                initializeBoard();
            }
            printf("\n");
        }
    }
    printf("\n :: Thanks for playing Tic Tac Toe game! :: \n");
    return 0;
}
Program Explanation

The program has the following functions which are performing small tasks.

advertisement
advertisement

initializeBoard() Function
This method is used to initialize the tic tac toe game board. The initialized board is given below.

 
         |     |   
    ----------------
         |     |   
    ----------------
         |     |

showBoard() Function
showBoard() method is used to print the game board after every play of each player.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
 
      O  |     |                    O  |     |    
    ----------------              ----------------
         |     |                       |  X  |   
    ----------------              ----------------
         |     |                       |     |   
 
      Player 1 Move                Player 2 Moves

updateBoard() Function
updateBoard() method is used to update the cell positions. If the position is not valid it shows a warning message.

Example: Update position 3 in the given board on player 2 move.

 
         |     |                       |  O  |    
    ----------------              ----------------
         |  X  |                       |  X  |   
    ----------------              ----------------
         |     |                       |     |   
 
      Player 1 Move                Player 2 move, update
                                   the position 2 with O

checkWinner()
checkWinner() method used to find the winner of the game. It checks on each row, column, and diagonal. If the same sign is present in any one of these places then print the winner

advertisement
 
      X  |  O  |   
    ----------------
         |  X  |   
    ----------------
      O  |     | X
 
     Player 1 won!

Time Complexity: O(1)
Time complexity of tic tac toe game is O(1). It takes a constant amount of time to print the game board, update the position of the game board and to check the winner of the game.

Space Complexity: O(1)
There is only temporary variables are used so the space complexity is constant i.e O(1).

advertisement
Program Output:

Here is the runtime test case of tic tac toe game.

--------- Tic Tac Toe ----------
 
 
* Instructions 
 
    Player 1 sign = X
    Player 2 sign = O
    To exit from the game, Enter -1
 
 
* Cell Numbers on Board
 
 
      1  |  2  |  3
    ----------------
      4  |  5  |  6
    ----------------
      7  |  8  |  9
 
 
 
> Press Enter to start...
 
Player 1 [ X ] : 1
 
 
      X  |     |   
    ----------------
         |     |   
    ----------------
         |     |   
 
 
 
Player 2 [ O ] : 2
 
 
      X  |  O  |   
    ----------------
         |     |   
    ----------------
         |     |   
 
 
 
Player 1 [ X ] : 5
 
 
      X  |  O  |   
    ----------------
         |  X  |   
    ----------------
         |     |   
 
 
 
Player 2 [ O ] : 6
 
 
      X  |  O  |   
    ----------------
         |  X  |  O
    ----------------
         |     |   
 
 
 
Player 1 [ X ] : 9
 
 
      X  |  O  |   
    ----------------
         |  X  |  O
    ----------------
         |     |  X
 
 
     *** Player 1 Won!! ***
 
     --- Game Over --- 
 
* Menu
 
Press 1 to Restart
Press 0 for Exit
 
Choice: 0
 
 
 :: Thanks for playing Tic Tac Toe game! ::

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.