【发布时间】:2015-12-17 21:49:17
【问题描述】:
我正在制作一个 AI 来与人类对战。游戏设置为一系列按钮,用户和 AI 轮流关闭对棋盘进行更改(按钮上的图标更改)。用户显然必须点击一个按钮,动作监听器会拾取它并调用适当的方法。然后它调用 AI,AI 调用方法来处理它的动作。
问题在于,在用户移动后,AI 移动得太快了,以至于我们看不到用户的移动(如果 AI 的移动与用户更改了相同的按钮)。 Thread.sleep 不起作用,因为它也使 GUI 线程进入睡眠状态,但是我必须让计时器工作的当前代码没有做任何事情(在方法的最后一个 else 中)!我该怎么办?
//When a button is clicked, this method is called
public void actionPerformed(ActionEvent e)
{
String btName = e.getActionCommand(); //finds out the name of the button that was clicked
if (btName == "HOW TO PLAY") //if the button "How to Play" is clicked, it does the following
{
howTo.txtPnl(); //(method found below)
}
else if(who%2 == 0){//it is the AI's turn
return;
}
else{
//gets the row and column of the button clicked if it is part of the game grid
int col = 0;
int row = 0;
String s = "";
String c = "";
JButton btn = (JButton) e.getSource();
s += btn.getClientProperty("rval");
row = Integer.parseInt(s);
s = "";
s += btn.getClientProperty("cval");
col = Integer.parseInt(s);
c += btn.getClientProperty("clr");
if(c.equals("") || c.equals("R"))
{
changeSquareAndRipple("R", row, col);//set the icons of the board
countField.setText("BLUE PLAYER'S TURN # OF BLUE ATOMS: " + countBlue() + " # OF RED ATOMS: " + countRed()); //updates gameboard
who++;
if(disableBoardOnSuccess()){//end of game
return;
}
else{//allow GUI to make changes before going to AI
Timer timer = new Timer(1000, this);
timer.start();
actionAI();
}
}
}
}
【问题讨论】:
-
附带建议,不要这样做:
if (btName == "HOW TO PLAY")。了解==和!=检查 reference 是否相等,这不是您想要的。您需要equals(...)和equalsIgnoreCase(...)将处理的功能平等。
标签: java swing timer artificial-intelligence