Search code examples
c++randomtic-tac-toe

C++: Tic Tac Toe Computer Random Moves


I need help with my tic tac toe, because I am stuck at this one. The random moves that the computer makes will overwrite the old ones, and I am not sure how to fix this.

if (computer == 1)  //computer = 1, means it's computer's turn
{
    i = rand() % 3;
    j = rand() % 3;
    if(board[i][j] !='X' && board[i][j] != '0')
    {
        board[i][j] = '0';
        computer--;  // computer = 0, means it's the player's turn
    }   
}

My 2D array is this one:

char board[3][3] = 
{{'1', '2', '3'}, 
{'4', '5', '6'}, 
{'7', '8', '9'}};

Solution

  • This works:

        if (computer == 1)  //computer = 1, means it's computer's turn
            {
                bool found = false;
                while (found == false)
                {
                i = rand() % 3;
                j = rand() % 3;
                if(board[i][j] !='X' && board[i][j] != '0')
                {
    
                board[i][j] = '0';
                found = true;
                computer--;  // computer = 0, means it's the player's turn
                }
    
                }