我是一名初学java的学生,正在为我的班级编写一个gui tic-tac-toe程序。 (没有玩家,只是计算机生成)。为什么循环不会停止迭代?
我的程序中的一切都按预期工作,除了一件事;似乎我的方法调用checkWinner
的位置放置不正确,因为X和O的分配总是完成。为什么这个循环不会在获胜者结束后立即结束?
它会根据方法调用返回正确的获胜者,但for循环将继续迭代并填充其余部分(所以有时它看起来像x和o胜或两胜两次)。我一直在疯狂,认为这可能是我的checkWinner
方法调用和if语句的位置。当我设置winner = true;
不应该取消循环?我试图把它之间,内部和外部每个for-loop没有运气:(
我已标记的区域,我认为是问题//这里有什么问题?//关闭在右边分开的代码。谢谢你的任何输入!! :)
public void actionPerformed(ActionEvent e)
{
int total = 0, i = 0;
boolean winner = false;
//stop current game if a winner is found
do{
// Generate random # 0-1 for the labels and assign
// X for a 0 value and O for a 1 value
for (int row = 0; row < gameboard.length; row++) //rows
{
for (int col = 0; col < gameboard[row].length; col++) //columns
{
//Generate random number
gameboard[row][col] = (int)(Math.random() * 2);
//Assign proper values
if(gameboard[row][col] == 0)
{
labels[i].setText("X");
gameboard[row][col] = 10; //this will help check for the winner
}
else if(gameboard[row][col] == 1)
{
labels[i].setText("O");
gameboard[row][col] = 100; //this will help check for winner
}
/**Send the array a the method to find a winner
The x's are counted as 10s
The 0s are counted as 100s
if any row, column or diag = 30, X wins
if any row, column or diag = 300, Y wins
else it will be a tie
*/
total = checkWinner(gameboard); **//Is this okay here??//**
if(total == 30 || total == 300) //
winner = true; //Shouldn't this cancel the do-while?
i++; //next label
}
}//end for
}while(!winner);//end while
//DISPLAY WINNER
if(total == 30)
JOptionPane.showMessageDialog(null, "X is the Winner!");
else if(total == 300)
JOptionPane.showMessageDialog(null, "0 is the Winner!");
else
JOptionPane.showMessageDialog(null, "It was a tie!");
}
checkWinner代码? –
Sidenode:如果找不到赢家,会发生什么情况?游戏将重新开始(不中止),所以你的“领带”选项是不可能的。 – dognose
当您将'winner'标志设置为'true'时,尝试向System.out输出消息;确保它确实发生。 –