我似乎无法在循环中结束这一点而且我已经尝试了我知道的每一种方式,但它仍然无法正常工作。即使我已将其变为“假”,变量“contGame”也会一直变为“true”。你们能帮助我吗!注意这在一个类里面。这是我的代码:
while (contGame == true)
{
if (turn == 1)
{
cout << Board._player1Name <<"'s turn!!\n";
X = getMoveX();
Y = getMoveY();
Board.Board[X][Y] = player1Sign;
Board.printBoard();
turn = turn + 1;
Board.checkGame(contGame, player1Sign, player2Sign);
if (checkGame(contGame, player1Sign, player2Sign) == false)
{
bool contGame = false;
cout << contGame << endl;
}
}
cout << contGame << endl;
if(turn == 2)
{
cout << Board._player2Name <<"'s turn!!\n";
X = getMoveX();
Y = getMoveY();
Board.Board[X][Y] = player2Sign;
Board.printBoard();
turn = turn - 1;
Board.checkGame(contGame, player1Sign, player2Sign);
if (checkGame(contGame, player1Sign, player2Sign) == false)
{
int contGame = 1;
cout << contGame << endl;
}
}
}
这是checkGame:
bool contGameA = true;
for (int k = 0; k < 3; k++)
{
if (Board[k][0] == Board[k][1] && Board[k][1] == Board[k][2] && Board[k][2] == player1Sign)
{
cout << "\\\\" << _player1Name <<" wins!////\n";
contGameA = false;
}
else if (Board[k][0] == Board[k][1] && Board[k][1] == Board[k][2] && Board[k][2] == player2Sign)
{
cout << "\\\\" << _player2Name << " wins!////\n";
contGameA = false;
}
}
for (int r = 0; r < 3; r++)
{
if (Board[0][r] == Board[1][r] && Board[1][r] == Board[2][r] && Board[2][r] == player1Sign)
{
cout << "\\\\" << _player1Name << " wins!////\n";
contGameA = false;
}
else if (Board[0][r] == Board[1][r] && Board[1][r] == Board[2][r] && Board[2][r] == player2Sign)
{
cout << "\\\\" << _player2Name << " wins!////\n";
contGameA = false;
}
}
if (Board[0][0] == Board[1][1] && Board[1][1] == Board[2][2] && Board[2][2] == player1Sign)
{
cout << "\\\\" << _player1Name << " wins!////\n";
contGameA = false;
} else if (Board[0][0] == Board[1][1] && Board[1][1] == Board[2][2] && Board[2][2] == player2Sign)
{
cout << "\\\\" << _player2Name << " wins!////\n";
contGameA = false;
}
if (Board[0][2] == Board[1][1] && Board[1][1] == Board[2][0] && Board[2][0] == player1Sign)
{
cout << "\\\\" << _player1Name << " wins!////\n";
contGameA = false;
} else if (Board[0][2] == Board[1][1] && Board[1][1] == Board[2][0] && Board[2][0] == player2Sign)
{
cout << "\\\\" << _player2Name << " wins!////\n";
contGameA = false;
}
return contGameA;
答案 0 :(得分:2)
您实际上是在contGame
语句的嵌套范围内创建if
变量,这隐藏了在外部范围内声明的contGame
变量。
因此,您永远不会更改外部contGame
变量
e.g。
if (checkGame(contGame, player1Sign, player2Sign) == false)
{
// bool contGame = false; should be:
contGame = false;
cout << contGame << endl;
}
和
if (checkGame(contGame, player1Sign, player2Sign) == false)
{
// int contGame = 1; should be
contGame = true;
cout << contGame << endl;
}
答案 1 :(得分:1)
您继续在嵌套作用域中声明名为contGame
的新变量,并修改它们。这些是完全独立的变量,(在其范围内)隐藏外部变量contGame
。 外部 <{1}}循环所依赖的值
从以下行中删除while
和bool
:
int
让这些行影响外部bool contGame = false;
// and
int contGame = 1;
变量。另请注意,contGame
已转换为1
。
答案 2 :(得分:0)
当在任何循环内声明时,变量的范围仅在括号内。
移除bool
和int
,然后输入
if (checkGame(contGame, player1Sign, player2Sign) == false)
{
contGame = false;
}