简体   繁体   English

如何在数组C ++中更改值

[英]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 (ie that spot is not yet taken), and false otherwise. playCell接受一个玩家(0表示“ O”,1表示“ X”),一个位置(1到9)和9个元素的gameBoard,如果移动是合法的(即该位置尚未被占用),则返回true,否则为假。 If the move is legal it changes the position to that players number (10 for "O", 11 for "X"). 如果此举是合法的,则将位置更改为该玩家编号(“ O”为10,“ X”为11)。 If the player or position input is invalid, it returns false. 如果玩家或位置输入无效,则返回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. 我试图弄清楚如何使数组根据玩家的不同将其值更改为10或11,并保存到他们输入的位置以进行播放。

The return keyword redirect the program flow back to the main program. return关键字将程序流重定向回主程序。 So the code after return will not be executed. 因此返回后的代码将不会执行。 Change the position of return : 更改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 

You have a return statement prior to your array assignment here: 您在这里进行数组分配之前有一个return语句:

    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. 从此处删除该行,并将其放置在正确的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM