Coders Packet

C++ programe for Tic-Tac-Toe

By Srishti Dhaval Patkar

This is a C++ code for the popular game Tic-Tac-Toe. It is a two-player game. After the game is finished you can choose to start a new game or exit.

void board() :

This function is called to draw the tic-tac-toe grid where we can play the game.

void board()
{
    system("cls");
    cout << "\t\tTic Tac Toe\n\n";

    cout << "Player 1 (X)  V/S  Player 2 (O)" << endl << endl;
    cout << endl;

    cout << "     |     |     " << endl;
    cout << "  " << square[1] << "  |  " << square[2] << "  |  " << square[3] << endl;

    cout << "_____|_____|_____" << endl;
    cout << "     |     |     " << endl;

    cout << "  " << square[4] << "  |  " << square[5] << "  |  " << square[6] << endl;

    cout << "_____|_____|_____" << endl;
    cout << "     |     |     " << endl;

    cout << "  " << square[7] << "  |  " << square[8] << "  |  " << square[9] << endl;

    cout << "     |     |     " << endl << endl;
}

 

int checkwin():

This function is to check the current status of the game. 

It returns 1 if player 1 or player 2 wins the game.

It returns 0 if it is a draw.

It returns -1 if the game is still not over.

 

int checkwin()
{
    if (square[1] == square[2] && square[2] == square[3])

        return 1;
    else if (square[4] == square[5] && square[5] == square[6])

        return 1;
    else if (square[7] == square[8] && square[8] == square[9])

        return 1;
    else if (square[1] == square[4] && square[4] == square[7])

        return 1;
    else if (square[2] == square[5] && square[5] == square[8])

        return 1;
    else if (square[3] == square[6] && square[6] == square[9])

        return 1;
    else if (square[1] == square[5] && square[5] == square[9])

        return 1;
    else if (square[3] == square[5] && square[5] == square[7])

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

        return 0;
    else
        return -1;
}

 

 

void newgame() :

This function clears the previous game and makes the grid ready for a new game.

 

void newgame()
{
    square[1]='1';
    square[2]='2';
    square[3]='3';
    square[4]='4';
    square[5]='5';
    square[6]='6';
    square[7]='7';
    square[8]='8';
    square[9]='9';
    
}

 

Download project

Reviews Report

Submitted by Srishti Dhaval Patkar (srishtipatkar15)

Download packets of source code on Coders Packet