【发布时间】:2017-08-12 11:55:32
【问题描述】:
我不明白为什么当我将 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 布尔变量应该赋值为 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
}
谢谢。
【问题讨论】:
-
第一个片段:只有最后一个分配很重要,第一个和第二个没有结果
-
这是您很容易发现的,但顺便说一下,在调试中单步执行代码。您会看到标志设置为 true,然后再次设置为 false。 F10 和 F11 是你的朋友!
标签: c# while-loop