我是一名初學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輸出消息;確保它確實發生。 –