我正在做一个奥赛罗游戏,我已经做了一个人工智能,这是一个简单的代码。但是当我运行我的代码时,Ai在我点击后立即运行,我希望延迟一些时间,我真的不知道该怎么做,就像我说的,它运行得太快了,我想让Ai在2秒后运行。
board.artificialIntelligence();我的方法Ai存储在board类中,我希望它存储在我的panel类中,顺便说一句,我正在使用NetBeans。
发布于 2013-04-10 22:04:25
如果你使用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-10 21:54:16
如果您使用的是Swing,则可以在预定义的延迟之后使用Swing Timer调用该方法
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
board.artificialIntelligence();
}
});
timer.setRepeats(false);
timer.start();发布于 2013-04-10 22:01:49
int numberOfMillisecondsInTheFuture = 2000;
Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
board.artificialIntelligence();
}
}, timeToRun);https://stackoverflow.com/questions/15927820
复制相似问题