1

我正在做一个黑白棋游戏,我做了一个简单的代码 Ai。但是当我运行我的代码时,Ai 在我点击后立即运行,我想要一些延迟,我真的不知道该怎么做,正如我所说,它运行得很快,我希望 Ai 像之后一样运行2 秒。

board.artificialIntelligence();

我的方法 Ai 存储在板类中,我希望它在我的面板类中,顺便说一句,我正在使用 NetBeans。

4

8 回答 8

5

如果您这样做,Thread.sleep(TIME_IN_MILLIS)您的游戏将在 2 秒内无响应(除非此代码在另一个线程中运行)。

我能看到的最好的方法是ScheduledExecutorService在你的班级中有一个并将 AI 任务提交给它。就像是:

public class AI {

    private final ScheduledExecutorService execService;

    public AI() {
        this.execService = Executors.newSingleThreadScheduledExecutor();
    }

    public void startBackgroundIntelligence() {
        this.execService.schedule(new Runnable() {
            @Override
            public void run() {
                // YOUR AI CODE
            }
        }, 2, TimeUnit.SECONDS);
    }
}

希望这可以帮助。干杯。

于 2013-04-10T14:04:24.727 回答
4

如果您使用的是 Swing,则可以使用Swing Timer在预定义的延迟后调用该方法

Timer timer = new Timer(2000, new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
         board.artificialIntelligence();
      }
   });
timer.setRepeats(false);
timer.start();
于 2013-04-10T13:54:16.047 回答
2
int numberOfMillisecondsInTheFuture = 2000;
    Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
    timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
                     board.artificialIntelligence();
        }
    }, timeToRun);
于 2013-04-10T14:01:49.393 回答
0

如果您不希望主线程阻塞,请启动一个新线程,该线程等待 2 秒然后进行调用(然后终止),如下所示:

new Thread(new Runnable() {
    public void run() {
        try {
            Thread.sleep(2000);
        } (catch InterruptedException e) {}
        board.artificialIntelligence();
    }
}).start();
于 2013-04-10T13:58:29.933 回答
0

Thread.sleep 使当前线程暂停执行一段指定的时间。

在你的情况下:

Thread.sleep(2000); // will wait for 2 seconds
于 2013-04-10T13:54:07.927 回答
0

在您的代码调用之前

try {    
    Thread.sleep(2000);

} catch(InterruptedException e) {}
于 2013-04-10T13:54:39.140 回答
0

使用Thread.sleep(2000)等待两秒钟

于 2013-04-10T13:53:53.893 回答
0

使用此代码等待 2 秒:

long t0,t1;
t0=System.currentTimeMillis();
do{
   t1=System.currentTimeMillis();
}while (t1-t0<2000);
于 2013-04-10T13:57:12.910 回答