Showing posts with label How to program games. Show all posts
Showing posts with label How to program games. Show all posts

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?

C++ game: Guess the number drawn random

In this tutorial, we will solve an exercise from our list of functions.

Game in C++: Guess the number drawn

Create a game where the computer draws a number from 1 to 100. Each time you guess a number, it should tell you whether you guessed below the real value, above or if you got it right. At the end, it tells you the number of attempts you had and whether or not you hit the record. Ah, at the end of each round, the program asks if you want to play again or not, displaying the current record.

Commented game code in C++

Well, come on, let's go calmly and carefully, today we're going to go over 100 lines of code.
But don't be alarmed, a big program is nothing more than several small programs divided, among other things, between functions that do specific things.

Initially, we declare the record variable, which will store the record number of attempts the user has made in a round. It starts at 0. Soon you will understand why.

Then, we create the clean() function, which will clean the screen with each round.

The gen() function causes the computer to generate a random number, from 1 to 100, and returns it.

The guess() function will be used to receive the user's guess. It receives an integer, the number of attempts the user has already made, to display: "attempt 1", "attempt 2", "attempt 3" ...

The check() function will compare the number you guessed with the number generated by the computer.
If you get it right, it returns 1, if you miss it it returns 0.

The hint() function will receive your guess and the number generated, and will give you the hint, if your guess was higher, lower or equal to that generated by the computer.

The ends() function displays the final game information.

It takes the number of attempts you made, and tells you whether you hit the record or not. Initially, if the record variable is equal to 0, this variable will take the number of attempts you took to get it right in your first game. Then, it evaluates if your attempts were less than the value of 'record', if it is, it says that you beat the record and this is the new value of the record variable. If not, show the record.

Finally, the continues() function asks if you want to play again or not.

Functions explained, let's go to the logic of the game, in main().
Initially, we declared 3 variables, the one that will store the number of attempts in each round, the one that will store the number generated in each round and the one that will store the user's hunches.

In the first DO WHILE, we will control the rounds that will be played. At the end of each iteration, we call the continues() function inside the WHILE, to see if we should start another round or not.

Within each round, we first clean the screen.
Then we reset the number of attempts, after all, it is a new round.

We display the current record, using the 'record' variable. And we say that we generated the number to be guessed.

Now, let's stay in a loop: ask a guess, say if you missed or hit, give the hint ... ask for another guess, tell if you hit or not, give a hint ... ask for another number ... until the person hits.

For this, we will use another DO WHILE loop. This one will run whenever the person misses. Wrong? Wheel again. The check() function controls this.

Within this internal DO WHILE, we first increase the number of attempts.
We take the user's guess, then give the tip (which also warns when it wins).

Finally, it goes to the check() function, which returns 1 if the person gets it right (looping ends) or 0 if they miss (it rotates again).

After this internal looping is over, we call the ends() function, which will tell you how many attempts you hit, whether you hit the record or not.

After that, go to the external while, which will ask if you want to play again or not.
Simple, isn't it?

Code game in C++

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int record=0;

void clean();
int gen();
int guess(int);
int check(int, int);
void hint(int, int);
void ends(int);
int continues();

int main()
{
    int attempts,
        generated,
        gues;

    do{
        clean();
        attempts=0;
        cout<<"Record until now: "<< record <<" attempts!"<<endl;
        generated = gen();
        cout<<"\Number was drawn! "<<endl;

        do{
            attempts++;
            gues = guess(attempts);
            hint(generated, gues);
        }while(check(generated, gues) != 1);

        ends(attempts);
    }while( continues() );
    return 0;
}
void clean()
{
    if(system("CLS")) system("clear");
}
int gen()
{
    unsigned seed = time(0);
    srand(seed);

    return 1+rand()%100;
}

int guess(int tryout)
{
    int gues;
    cout<<"\nTry to guesse the number, from 1 to 100."<<endl;
    cout<<"Tryout "<<tryout<<":"<<endl;
    cin >> gues;

    if(gues>0 && gues<=100)
        return gues;
    else
        cout<<"Only numbers from 1 to 100"<<endl;
}

int check(int generated, int gues)
{
    if(generated == gues)
        return 1;
    else
        return 0;
}

void hint(int generated, int gues)
{
    if(gues<generated)
        cout<<"WRONG! Your guess was LESS than the number drawn!"<<endl;
    else
        if(gues>generated)
            cout<<"WRONG! Your guess was HIGHER than the number drawn!"<<endl;
        else
            cout<<"Greeeat, dude!"<<endl;
}

void ends(int tryout)
{
    cout<<"\nYou got it right in "<<tryout<<" attempt(s)!"<<endl;

    if(record==0)
        record = tryout;

    if(tryout<=record){
        cout<<"Congratulations! The record it's yours!"<<endl;
        record = tryout;
    }
    else
        cout<<"The record still is "<<record<<" attempt(s)"<<endl;
}

int continues()
{
    int cont=1;

    cout<<"\nPlay again?"<<endl;
    cout<<"0. Exit"<<endl;
    cout<<"1. One more time!"<<endl;
    cin >> cont;

    return cont;
}