我一直在做一个关于零和十字的项目。我曾经遇到一个令人恼火的问题。当只剩下一个按钮可用,并且到目前为止还没有检测到获胜的走法时,作为一个玩家,我点击这个按钮,游戏应该会提示这是一个平局。出现一个对话框,当我单击“确定”时,同样的对话框再次出现。在我看来,这是一个无限循环。提前感谢
// make random move if above rules dont apply
Random rand1 = new Random();
Random rand2 = new Random();
int max = 2;
int min = 0;
int randnum1 = rand1.nextInt((max - min) + 1) + min ;
int randnum2 = rand2.nextInt((max - min) + 1) + min ;
while( MadeMove == false) {
while( true ) {
if( !SecondTest.cells[randnum1][randnum2].getText().equals(SecondTest.ComputerMark) && !SecondTest.cells[randnum1][randnum2].getText().equals(SecondTest.PlayerMark))
{
SecondTest.cells[randnum1][randnum2].setText(SecondTest.ComputerMark);
MadeMove = true;
if ( SecondTest.CheckDraw()) {
break;
}
break;
} else {
System.out.println("occupied");
randnum1 = rand1.nextInt((max - min) + 1) + min ;
randnum2 = rand2.nextInt((max - min) + 1) + min ;
if (SecondTest.CheckDraw()) {
break;
}
}
}
}
public static boolean CheckDraw()
{
boolean GameDraw = true;
for ( int i = 0; i<3; i++) {
for ( int j = 0; j<3; j++) {
if (cells[i][j].getText().equals(".")) {
GameDraw = false;
}
}
}
if ( GameDraw == true ) {
DrawCounts++;
JOptionPane.showMessageDialog (null, "Oh no, it's a draw! " +
" Total Player Wins : " + PlayerCounts + " " +
" Total Computer Wins : " + ComputerCounts + " " +
" Total Draw Counts : " + DrawCounts + " "
, "Oh no, it's a draw!", JOptionPane.INFORMATION_MESSAGE);
jTextArea2.setText("It is a draw!\n To start a new game,please press Reset\n");
gameOver = true;
PlayerGame = false;
AIGame = false;
return true;
}
return false;
}发布于 2015-03-20 20:53:32
你的内部循环的意义是什么?当然,您希望随机尝试移动,直到MadeMove为真或检测到抽签。您还希望将随机数生成移动到循环中,以减少重复。类似地,将draw in if和else的检查合并为一个检查。这应该是有效的,除非随机移动获胜!
while( MadeMove == false) {
randnum1 = rand1.nextInt((max - min) + 1) + min ;
randnum2 = rand2.nextInt((max - min) + 1) + min ;
if( !SecondTest.cells[randnum1][randnum2].getText().equals(SecondTest.ComputerMark) && !SecondTest.cells[randnum1][randnum2].getText().equals(SecondTest.PlayerMark)) {
SecondTest.cells[randnum1][randnum2].setText(SecondTest.ComputerMark);
MadeMove = true;
} else {
System.out.println("occupied");
}
if (SecondTest.CheckDraw()) {
break;
}
}https://stackoverflow.com/questions/29166373
复制相似问题