【发布时间】:2014-03-25 21:13:34
【问题描述】:
我是一名 Java 初学者,正在为我的班级编写一个 gui tic-tac-toe 程序。 (没有玩家,只有电脑生成)。
我的程序中的一切都按预期工作,除了一件事;似乎我对checkWinner 的方法调用的放置位置不正确,因为 X 和 O 的分配总是完成。为什么一有赢家就不会结束循环?
它将根据方法调用返回正确的获胜者,但 for 循环将继续迭代并填充其余部分(因此有时看起来 x 和 o 都赢了,或者一个赢了两次)。我一直在发疯,认为这可能是我的 checkWinner 方法调用和 if 语句的位置。当我设置winner = true; 时不应该取消循环吗?我试过把它放在每个 for 循环的内部和外部,但没有运气:(
我已经在代码右侧标记了我认为是问题的区域//这里有什么问题?//。感谢您的任何意见! :)
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!");
}
【问题讨论】:
-
Sidenode:如果没有找到获胜者会怎样?游戏将重新启动(但未中止),因此您的“领带”选项永远不可能。
-
尝试在将
winner标志设置为true时向System.out 打印一条消息;确保它确实在发生。 -
您不需要将
total初始化为零,因为它会被checkWinner结果覆盖。但是,您需要将i初始化为零,并且您应该在do循环中在for(row)之前执行此操作。 -
@JasonC 我做了你所说的使用 JOption 并且发生的事情是一旦有人获胜它就会弹出,但是,在我按下确定后,相同的消息会继续弹出直到结束循环。
-
@dognose 如果他们是平手,它确实有效。如果我可以编辑我的代码帖子,如果有人想查看它,我将添加 checkWinner 方法。但是,我认为这与我当前的问题无关。
标签: java loops do-while tic-tac-toe