Showing posts with label Matrix. Show all posts
Showing posts with label Matrix. 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++ Array Exercises

Using your knowledge so far (basic, loops, conditional tests, functions and mainly arrays), solve the following exercises in C ++ and put your code in the comments.

C ++ Array exercises

01. Write a program that will receive and store 10 numbers in an array. Then, you must create two functions that will find the highest and lowest value of that array.

02. You were hired by a TV station to make C++ software to work with rain data in your city. Your 7-position array should store how much it rained each day. Then, you must say which day it rained more, the day it rained less, how much it rained the week and the average, to show on TV.

03. Create an array of 10 positions, to store the average grades of 10 students. Your program must then go to each grade and check if the student has passed (grade higher than 7), failed (grade less than 5) or will be left for recovery (grade between 5 and 7).

04. Create a lottery number generator program. That is, create an array of 6 positions and in each position draw a number from 1 to 60. Oh, your numbers cannot be repeated.


05. Make a program in which you will supply 10 numbers for an array, including repeated values. Your code must search this array to create a new array that does not have repeated numbers.


06. Program the tic-tac-toe, in C++. Two players on your computer must be able to play. Each player says a line and a number, on the 3x3 board, to play (can only play in free spots on the board). At the end of each game, it must say who won or drew, as well as the score of the game, and whether they want to play another game or close the program.
Tic-Tac-Toe in C++


07. On an NxN board (you choose N), the computer must draw N positions on that board, without the user knowing. These positions are the ships locations. Now you must make attempt (shots in the water) to try to hit the ships. With each shot you take, the program should tell you whether you hit or miss, and if you miss, it should tell you how many ships are there around that point.



More exercises, with solutions, on C ++ arrays:
https://www.w3resource.com/cpp-exercises/array/index.php

Matrix in Functions

In this tutorial from our C++ ebook, we will learn how to work with matrix and functions, learning to declare, invoke and use these two important topics together.

How to Pass a Matrix to a Function

In the study of arrays, we saw that there are some ways to declare the header of functions with arrays as parameters, as follows:
  • type func(tipo *array);
  • type func(tipo array[tamanho]);
  • type func(tipo array[]);

In other words, just pass the pointer (*array - we will study more ahead) or just with the pair of open brackets (array[]).

In the case of two-dimensional arrays, we need to specify the number of columns in the array we are sending:
  • void func(int arr[][COLUMN]);

You see, the number of rows is not mandatory (we can even pass), but the number of columns is.
Let's declare and initialize a 2x2 matrix and then send it to the show() function, which will simply display it as a table, see how our code looks:
#include <iostream>
using namespace std;

void show(int arr[][2], int row)
{
    for (int i=0 ; i<row ; i++){
        for(int j=0 ; j<2 ; j++)
            cout<<arr[i][j]<<"  ";
        cout<<endl;
    }
}

int main()
{
    int arr[][2]={ {1,2}, {3,4} };
    show(arr, 2);
    return 0;
}
Look some important things in the code above.

First, we pass the array arr[][2] to the function, with the number of columns.
But what about the number of lines? How will the function know how many lines to print the table?
It doesn't know, so we pass another parameter in the function, the integer 'row'.

C++ Matrix: Passing by Reference

All data passing to functions that involve arrays and matrix is by reference. Ever.
That is, passed an array to a function? It will directly access the array and its data, directly into memory. It is not a copy that goes to function, it is not a pass for value, ok?

That means one thing: watch out! Functions can modify the arrays, always remember that.
The code below introduces the 'init' function, which will receive an array and initialize each element of it, asking the user:
#include <iostream>
using namespace std;
const int COLS = 3;
const int ROWS = 3;

void init(int arr[][COLS], int ROWS)
{
    for(int i=0 ; i<ROWS ; i++)
        for(int j=0 ; j<COLS ; j++){
            cout << "matrix["<<i+1<<"]["<<j+1<<"]: ";
            cin  >> arr[i][j];
        }
}

void show(int arr[][COLS], int ROWS)
{
    for (int i=0 ; i<ROWS ; i++){
        for(int j=0 ; j<COLS ; j++)
            cout<<arr[i][j]<<"  ";
        cout<<endl;
    }
}

int main()
{
    int arr[ROWS][COLS];
    init(arr, ROWS);
    show(arr, ROWS);
    return 0;
}
To improve the organization, we have already defined the rows (ROWS) and columns (ROLS) as global variables of the constant type, so that there is no danger of anyone, anywhere in the code, changing their values. This makes the code clearer and safer for maintenance.

Array of arrays in C++

Matrix Exercise in C ++

Create a 4x4 matrix, where each row represents a student's grades, and each column is a different subject. You must create a function that will fill in the students' grades, one by one, indicating which is the subject and which is the student.

Then, your program should display, in an organized manner, the grades of each student, as well as the average of each, the class average for each subject, and the general average, of all students of all grades.

Post your solution in the comments.

Matrix in C++: Array of Arrays

In this tutorial from our C++ Course, we will learn the important concept of matrix in C++.

Array of Arrays - What is it? What is it for?

So far, in our arrays section, we have created arrays of integers, float, doubles, char etc.
That is, we create arrays that store numbers or characters.
However, it is also possible to store other things in arrays.

A curious thing to store in arrays are other arrays.

For example, imagine that you were hired by a school to do a C++ program that will, among other things, store students' grades. Each student has, for example, 5 different grades.

You can, first of all, reason like this: create an array to store students.
For example: students[10]

However, each student has 5 grades. So each student will have an array of grades:
notes[5]

You see: we have an array of students, each block represents a student. And within each block, that is, each student, there is a kind of internal array, with the grades of each student. Each student has his own array of grades, and each student is part of the student array.

Shall we formalize this?

How to declare an Array in C++

We call it a matrix, an array of arrays, or multidimensional arrays.
So far, we only work with arrays of one dimension, just a 'line' of blocks, which form an array.

To increase the number of dimensions of an array, just add pairs of square brackets, for example:

  • To declare an array of one dimension, we do: float grade[5];
  • To declare an array of two dimensions, we do: float students[10][5];


Come on. When we do 'float grade[5]' we mean: 5 float blocks.
When we do: 'float students[10][5]', we mean: 10 blocks, where each block has an array inside, of 5 floats.

We say that this is a 10x5 matrix (10 rows and 5 columns, where each row represents a student, and each column represents a different grade).

To make it easier, let's imagine a 3x3 matrix, we declare it like this:

  • int matrix[3][3];


The expression 'matrix[3]' means: an array of 3 elements.
What does each element contain? An integer? A float? A char? No, each element is another array, of size [3].

See the representation of this matrix:
Matrix in C++

The first element of our matrix is: matrix[0]
It is an array, of 3 elements, which are represented by:
First element: matrix[0][0]
Second element: matrix[0][1]
Third element: matrix[0][2]


The second element of our matrix is: matrix[1]
It is an array, of 3 elements, which are represented by:
First element: matrix[1][0]
Second element: matrix[1][1]
Third element: matrix[1][2]

The third element of our matrix is: matrix[2]
It is an array, of 3 elements, which are represented by:
First element: matrix[2][0]
Second element: matrix[2][1]
Third element: matrix[2][2]

That is, to declare an array of 'i' rows and 'j' columns, we do:

  • type matrix[i][j];


If you have studied matrix and determinants at school, you should remember how to use a matrix, how to flag each element, etc. The only difference here is that the count starts from index 0, instead of 1.

How to initialize a Matrix in C++

We will create a matrix to store the grades of 3 students, where each student has two grades.
That is, we will have a matrix of 3 rows (one for each student) and 2 columns (each column represents a grade). We declare this matrix, then:

  • grade float[3][2];


We will now initialize a 3x3 matrix, for example, with the notes:
float grade[3][3] = {{9.5, 9.1},
                                {8.8, 8.4},
                                {10.0, 10.0}};


The first student's grade array is: {9.5, 9.1}
The second student's grade array is: {8.8, 8.4}
The third student's grade array is: {10.0, 10.0}

For example, what is the second student's first grade? Second student is student 1, first grade is index 0, so that grade is stored in: grade[1][0] = 8.8
The second grade of the second student is: grade[1][1] = 8.4

Simple, isn't it?