【问题标题】:Adding Java.Swing Timer to Synchronize US for player and AI添加 Java.Swing Timer 以同步玩家和 AI 的 US
【发布时间】: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


【解决方案1】:

这不是计时器的工作方式。阅读Swing documentation。这很清楚。您需要在当前所在的位置启动计时器,然后在计时器的处理程序中调用 AI,稍后将调用该处理程序。 else 块现在看起来像:

int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    actionAI();
  }
};
Timer timer = new Timer(delay, taskPerformer)
timer.setRepeats(false);
timer.start();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 2012-10-28
    相关资源
    最近更新 更多