0

私は非常に単純なスネーク ゲームを作成しています。X 秒ごとにランダムな位置に移動したい Apple というオブジェクトがあります。私の質問は、このコードを 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);
4

4 に答える 4

7

エグゼキュータを使用します

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);
于 2012-11-23T16:41:05.667 に答える
2

タイマーを使用します。

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 ドキュメント タイマー

于 2013-08-06T05:20:38.233 に答える
1

最も簡単なのは を使用することsleepです。

        apple.x = rg.nextInt(470);
        apple.y = rg.nextInt(470);
        Thread.sleep(1000);

上記のコードをループで実行します。

これにより、おおよその(正確ではない場合があります) 1 秒の遅延が得られます。

于 2012-11-23T15:10:46.387 に答える
1

ゲームの処理を担当するある種のゲーム ループが必要です。次のように、 xミリ秒ごとにこのループ内でコードを実行するようにトリガーできます。

while(gameLoopRunning) {
    if((System.currentTimeMillis() - lastExecution) >= 1000) {
        // Code to move apple goes here.

        lastExecution = System.currentTimeMillis();
    }
}

この例では、if ステートメントの条件はtrue1000 ミリ秒ごとに評価されます。

于 2012-11-23T15:23:23.737 に答える