c# - while 循环不会在 bool C# 上中断

标签 c# while-loop

我不明白为什么当我将 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/

相关文章:

c - 这是对 fgetc 的有效使用吗?

python - 无法让我的 else 语句在 while 循环中打印

r - 在 R 中模拟 - 我怎样才能让它更快?

c# - 是使用 TempData、Session 还是静态变量在同一 Controller 中的 ActionResults 之间共享相同的值更好?

c# - 更改实现具有对象类型属性的接口(interface)的类中的属性类型

c# - 在声明环境中正确验证 WCF 服务

c# - 将图 A 更改为图 B

c - 使用 C 打印学生综合成绩的平均值

c# - 如何使用 LINQ 从 List<string> 中删除重复组合

c - 停留在 while 循环中