我不明白为什么当我将 bool 变量 (gameEnded) 分配给 true
时,我的 while 循环不会停止循环。
Board board = new Board();
bool gameEnded = false;
while (!gameEnded)
{
gameEnded = board.DrawCheck(board); //one of these three methods returns true
gameEnded = board.WinCheckO(board);
gameEnded = board.WinCheckX(board);
Render(board);
bool turnO = false;
Console.WriteLine("Player X's turn.");
//... here some code that gets executed right
}
因此,gameEnded bool 变量应该被赋值 true,循环因此中断。我检查了 Checksomething 方法是否返回 true。 修改后的版本工作得很好,即打破了循环。
Board board = new Board();
bool gameEnded = false;
while (!gameEnded)
{
if (board.WinCheckX(board))
{
Console.WriteLine("X player won!");
break;
}
else if (board.WinCheckO(board))
{
Console.WriteLine("O player won!");
break;
}
else if (board.DrawCheck(board))
{
Console.WriteLine("It's a tie!");
break;
}
Render(board);
bool turnO = false;
Console.WriteLine("Player X's turn.");
//... here some code that gets executed right
}
谢谢。
最佳答案
//one of these three methods returns true
因为有三个赋值,其中一个方法返回 true
是不够的:只有最后一个赋值有任何作用,所以除非 board.WinCheckX(board)
返回 true
,循环继续。
解决方法很简单:使用 ||
运算符将三个赋值合并为一个:
gameEnded = board.DrawCheck(board)
|| board.WinCheckO(board)
|| board.WinCheckX(board);
这种方法的另一个好处是,一旦这些方法之一返回 true
,就不会因为 ||
运算符的短路而进行额外的调用.
关于c# - while 循环不会在 bool C# 上中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45649967/