我一直致力于Noughts and Crosses的项目。我曾经遇到一个恼人的问题。当只有一个按钮被占用并且到目前为止没有检测到获胜动作时,作为一名玩家,我点击按钮,游戏应该提示它是平局。将出现一个对话框,单击“确定”后,将再次出现相同的对话框。在我看来,有一个无限循环。提前致谢
// 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;
}
答案 0 :(得分:0)
你的内循环有什么意义?当然,您想要随机尝试移动,直到MadeMove
为真或检测到平局为止。您还希望在循环内移动随机数生成以减少重复。同样地将if和else中的draw的检查合并到一个检查中。这应该有效,除非随机移动获胜!
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;
}
}