Tic-Tac-Toe in C++: How to Program


Tic-tac-toe game full code in C++In this tutorial, we will teach you the most absolute zero, how to program the tic-tac-toe game in C++, a super cool game that you can use to play with a friend.

C++ Tic-Tac- Toe logic

We will use a matrix, 3x3, of integers, to represent the moves.
If the block has the number 0, it is empty. If it have number 1 it is because player 1 played there, and if you have -1, it is because player 2 played in that position.

We will explain, in parts, the functions.

The init() function initializes the board, placing 0 in every block.


The show() function will display the board, print the cute board, with bars, underlines, correct spacing and, if there are X or 0 in each square. This last part does the printBlock() function.

The printBlock() function goes on each block of the board, if it has 0 there, it returns an empty space ''. If there is 1 there, it prints X. If there is -1 there, it is because player 2 played in that house, and there will be an O.

The playMove() function performs a move, that is, it asks for the row and column that the player will play.
Remembering that it will enter values ​​from 1 to 3, and the array goes from 0 to 2, so we have to subtract one unit from the data entered by the user (row-- and col--). We should also check if it is occupied (board[row] [col]), and if the user has entered correct values ​​(between 1 and 3). If everything is ok, it fills the square chosen by the player with 1 or -1.

The checkContinue() function will check if there is still white space, that is, if it is still possible to make a move. If there is blank space, returns 1, if not, returns 0.

The checkWin() function will check if anyone has won. To do this, just add each row, each column and each diagonal, if any of these rows has a sum of 3, player 1 won and we return 1. If the sum is -3, player 2 won, and we return -1. If no one has won, by that time, we return 0.

Now let's go to the main() function. It creates the 3x3 board, the cont variable (which will ask whether the player will want to play again or not, the player1 and player2 variables, which will store the scoreboard), and the result variable, which stores the information of who won the game.


The game will take place within a DO WHILE.
First, we initialize the board with values ​​0.
Now let's make a match, for that, we call the game() function.

The game() function is where the magic happens, the game unfolds.
First, we declare the turn variable, which will tell whether it is player 1 or 2 who will play. With each move, we must increase it by one (turn ++), to change the turn for the next player.

After saying whose turn it is, let's make the move, through the playMove() function. Note that we pass the information on who the player is, using the expression turn%2. If it gives 0, it's player 1's turn (and puts the number 1, represented by X on the board), if it gives 1, it's the player's 2 turn (and we fill the matrix with the number -1, which will be represented by character O on the board).

Then, we should check if the board still has empty positions, to play. If so, we store the number 1 in the cont variable, otherwise we store the value 0.

We should also check if someone has won after this play. If player 1 has won, we store 1 in the win variable. If player 2 has won, we store the value -1. If no one has won, we store the value 0.

Ready. A play is over. Will you have a next move? That depends.

If there is still empty space (cont = 1) and no one has won (win = 0, same as !win), there will be another move.

If there is no more empty space (cont = 0) or someone has won (win = 1 or win = -1), there will be no next move, and exit the DO WHILE loop.

After the loop, let's check what happened. If win = 1, player 1 won and the game function returns 1.
If win = -1, player 2 won and we returned 2. If none of them won, it is because the board is full (cont = 0) and we haw a draw, then we return 0.

This return goes to the main() function, in the result variable. He takes the result, and sends it to the scoreboard() function, along with the values ​​of player1 and player2, she is responsible for controlling the score.

After the scoreboard is displayed, we ask if you want to play the game again or leave.
If you type 1 (continue), the cont variable has a value of 1, the WHILE loop is true, and another game will start. Otherwise, if it is 0, the loop ends with the game.

Nice, isn't it?


Guys, the code below has almost 200 lines. There can be errors, no doubt.
If you find any, or any improvement, please write in the comments, ok?

Tic-Tac-Toe full code Game in C++

#include <iostream>
using namespace std;

void init(int board[][3]);          // Initializes the board with 0's
char printBlock(int block);         // Prints each square of the board
void show(int board[][3]);          // Show the board
void playMove(int board[][3], int); // Play one move
int checkContinue(int *board[3]);   // Check if there is still white space
int checkWin(int *board[3]);        // Check if anyone won
int game(int board[][3]);           // PLay an entire game
void scoreboard(int, int &, int &); // Show the scoreboard

int main()
{
    int board[3][3];

    int cont=0, player1=0, player2=0, result;
    do{
        init(board);
        result = game(board);
        show(board);
        scoreboard(result, player1, player2);

        cout<<"\n Again?"<<endl;
        cout<<"0. Exit"<<endl;
        cout<<"1. Play again"<<endl;
        cin >> cont;
    }while(cont);

    return 0;
}

void init(int board[][3])
{
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            board[i][j]=0;

}

char printBlock(int block)
{
    if(block==0)
        return ' ';
    else if(block==1)
        return 'X';
    else
        return 'O';
}

void show(int board[][3])
{
    cout<<endl;
    for(int row=0 ; row<3 ; row++){
        cout<<" "<< printBlock(board[row][0]) <<" |";
        cout<<" "<< printBlock(board[row][1]) <<" |";
        cout<<" "<< printBlock(board[row][2]) <<endl;

        if(row!=2){
            cout<<"___ ___ ___\n"<<endl;
        }
    }
}

void playMove(int board[][3], int player)
{
    int row, col, check;
    do{
        cout<<"Row: ";
        cin >>row;
        cout<<"Column: ";
        cin >> col;
        row--; col--;

        check = board[row][col] || row<0 || row>2 || col<0 || col>2;
        if(check)
            cout<<"This spot isn't empty or out of 3x3 board"<<endl;

    }while(check);

    if(player==0)
        board[row][col]=1;
    else
        board[row][col]=-1;
}

int checkContinue(int board[][3])
{
    for(int i=0 ; i<3 ; i++)
        for(int j=0 ; j<3 ; j++)
            if(board[i][j]==0)
                return 1;
    return 0;
}

int checkWin(int board[][3])
{
    int row, col, sum;

    // Adding the lines
    for(row=0 ; row<3 ; row++){
        sum=0;

        for(col=0 ; col<3 ; col++)
            sum += board[row][col];

        if(sum==3)
            return 1;
        if(sum==-3)
            return -1;
    }

    // Adding the columns
    for(col=0 ; col<3 ; col++){
        sum=0;

        for(row=0 ; row<3 ; row++)
            sum += board[row][col];

        if(sum==3)
            return 1;
        if(sum==-3)
            return -1;
    }

    // Adding the diagonals
    sum=0;
    for(row=0 ; row<3 ; row++)
        sum += board[row][row];
    if(sum==3)
        return 1;
    if(sum==-3)
        return -1;

    sum=board[0][2]+board[1][1]+board[2][0];
    if(sum==3)
        return 1;
    if(sum==-3)
        return -1;

    return 0;
}

int game(int board[][3])
{
    int turn=0, cont, win;

    do{
        show(board);
        cout<<"Player "<<1+turn%2<<endl;
        playMove(board, turn%2);
        turn++;

        cont=checkContinue(board);
        win = checkWin(board);
    }while(cont && !win);

    if(win==1){
        cout<<"Player 1 won!\n"<<endl;
        return 1;
    }else
        if(win==-1){
            cout<<"Player 2 won!\n"<<endl;
            return 2;
    }else
        cout<<"Draw\n"<<endl;
    return 0;
}

void scoreboard(int result, int &player1, int &player2)
{
    if(result==1)
        player1++;
    if(result==2)
        player2++;

    cout<<"\nScoreboard: "<<endl;
    cout<<player1<<" x "<<player2<<endl;
}

C++ game challenge

Create a modified version of this game, which asks the user whether he wants to play with a friend or against the computer. If he chooses to play against the machine, make sure his code chooses a random block when it is the machine's turn.

Would someone be able to make and post in the comments, the result?

No comments:

Post a Comment