[英]In Java, how do I execute code every X seconds?
我正在做一個非常簡單的蛇游戲,並且有一個名為Apple的對象,我希望每X秒移動到一個隨機位置。 所以我的問題是,每X秒執行此代碼的最簡單方法是什么?
apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);
謝謝。
編輯:
好吧,已經有一個這樣的計時器了:
Timer t = new Timer(10,this);
t.start();
它的作用是在游戲啟動時繪制我的圖形元素,它運行以下代碼:
@Override
public void actionPerformed(ActionEvent arg0) {
Graphics g = this.getGraphics();
Graphics e = this.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
e.fillRect(0, 0, this.getWidth(), this.getHeight());
ep.drawApple(e);
se.drawMe(g);
我會用遺囑執行人
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable toRun = new Runnable() {
public void run() {
System.out.println("your code...");
}
};
ScheduledFuture<?> handle = scheduler.scheduleAtFixedRate(toRun, 1, 1, TimeUnit.SECONDS);
最簡單的事情就是利用sleep
。
apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);
Thread.sleep(1000);
循環運行以上代碼。
這將使您大約延遲一秒鍾(可能不准確)。
您應該具有某種負責處理游戲的游戲循環。 您可以每隔x毫秒觸發一次在此循環內執行的代碼,如下所示:
while(gameLoopRunning) {
if((System.currentTimeMillis() - lastExecution) >= 1000) {
// Code to move apple goes here.
lastExecution = System.currentTimeMillis();
}
}
在此示例中,if語句中的條件每1000毫秒評估為true
。
使用計時器:
Timer timer = new Timer();
int begin = 1000; //timer starts after 1 second.
int timeinterval = 10 * 1000; //timer executes every 10 seconds.
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//This code is executed at every interval defined by timeinterval (eg 10 seconds)
//And starts after x milliseconds defined by begin.
}
},begin, timeinterval);
文檔: Oracle文檔計時器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.