2013-04-10 26 views
1

我正在做一個其他的遊戲,我做了一個簡單的Ai代碼。但是當我運行我的代碼時,Ai在點擊後運行正常,我想要一些延遲,但我不知道該怎麼做,正如我所說,它運行速度很快,我希望Ai能夠像在2秒。如何推遲一個方法

board.artificialIntelligence(); 

我的方法艾存儲在板類,我想在我的面板類,順便說一句,我使用NetBeans。

+0

'Thread.sleep()'? – devnull 2013-04-10 13:54:22

回答

0

的Thread.sleep導致當前線程掛起了 指定的時間執行。

你的情況:

Thread.sleep(2000); // will wait for 2 seconds 
4

如果你使用的鞦韆,您可以使用Swing Timer預定延遲

Timer timer = new Timer(2000, new ActionListener() { 
     public void actionPerformed(ActionEvent evt) { 
     board.artificialIntelligence(); 
     } 
    }); 
timer.setRepeats(false); 
timer.start(); 
0

後調用該方法的代碼調用之前

try {  
    Thread.sleep(2000); 

} catch(InterruptedException e) {} 
0

使用此代碼等待2秒鐘:

long t0,t1; 
t0=System.currentTimeMillis(); 
do{ 
    t1=System.currentTimeMillis(); 
}while (t1-t0<2000); 
+1

千萬不要這樣做。它會完全沒有目的地燒掉CPU週期。 – grahamparks 2013-04-10 14:04:24

0

如果你不希望主線程阻塞,開始一個新的線程來等待2秒然後再打電話(然後死),像這樣:

new Thread(new Runnable() { 
    public void run() { 
     try { 
      Thread.sleep(2000); 
     } (catch InterruptedException e) {} 
     board.artificialIntelligence(); 
    } 
}).start(); 
2
int numberOfMillisecondsInTheFuture = 2000; 
    Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture); 
    timer = new Timer(); 
    timer.schedule(new TimerTask() { 
     public void run() { 
        board.artificialIntelligence(); 
     } 
    }, timeToRun); 
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); 
    } 
} 

希望這有助於。乾杯。