user3477165
user3477165

Reputation: 3

How to change a value in an array C++

This function is for code to play a game of tic tac toe:

//--------------------FUNCTION--------------------

bool playCell(int player, int position, int gameBoard[]) {

    if (gameBoard[position] == 10 || gameBoard[position] == 11) {
        return false;   
    } else {
        return true;
        if (player == 0){
            gameBoard[position] = 10;
        } else {
            gameBoard[position] = 11;
        } // end if
    }
} // end function 

playCell takes a player (0 for "O", 1 for "X"), a position (1 to 9), and the nine element gameBoard, and returns true if the move is legal (i.e. that spot is not yet taken), and false otherwise. If the move is legal it changes the position to that players number (10 for "O", 11 for "X"). If the player or position input is invalid, it returns false.

I'm trying to figure out how to get the array to change its value to either a 10 or 11 depending on the player, and saving to the position they entered to play in.

Upvotes: 0

Views: 32116

Answers (2)

Mauren
Mauren

Reputation: 1975

You have a return statement prior to your array assignment here:

    return true; // HERE
    if (player == 0){
        gameBoard[position] = 10;
    } else {
        gameBoard[position] = 11;
    } // end if

this causes your code not to be executed. Remove this line from there and put in the correct place.

Upvotes: 0

Raging Bull
Raging Bull

Reputation: 18747

The return keyword redirect the program flow back to the main program. So the code after return will not be executed. Change the position of return:

//--------------------FUNCTION--------------------

bool playCell(int player, int position, int gameBoard[]) 
{
    if (gameBoard[position] == 10 || gameBoard[position] == 11) 
    {
        return false;   
    } 
    else 
    {
        if (player == 0)
        {
            gameBoard[position] = 10;
        }
        else 
        {
            gameBoard[position] = 11;
        } // end if   
        return true;
    }
} // end function 

Upvotes: 1

Related Questions