我正在做一个黑白棋游戏,我做了一个简单的代码 Ai。但是当我运行我的代码时,Ai 在我点击后立即运行,我想要一些延迟,我真的不知道该怎么做,正如我所说,它运行得很快,我希望 Ai 像之后一样运行2 秒。
board.artificialIntelligence();
我的方法 Ai 存储在板类中,我希望它在我的面板类中,顺便说一句,我正在使用 NetBeans。
如果您这样做,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);
}
}
希望这可以帮助。干杯。
如果您使用的是 Swing,则可以使用Swing Timer在预定义的延迟后调用该方法
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
board.artificialIntelligence();
}
});
timer.setRepeats(false);
timer.start();
int numberOfMillisecondsInTheFuture = 2000;
Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
board.artificialIntelligence();
}
}, timeToRun);
如果您不希望主线程阻塞,请启动一个新线程,该线程等待 2 秒然后进行调用(然后终止),如下所示:
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} (catch InterruptedException e) {}
board.artificialIntelligence();
}
}).start();
Thread.sleep 使当前线程暂停执行一段指定的时间。
在你的情况下:
Thread.sleep(2000); // will wait for 2 seconds
在您的代码调用之前
try {
Thread.sleep(2000);
} catch(InterruptedException e) {}
使用Thread.sleep(2000)
等待两秒钟
使用此代码等待 2 秒:
long t0,t1;
t0=System.currentTimeMillis();
do{
t1=System.currentTimeMillis();
}while (t1-t0<2000);