0

I'm making a really simple snake game, and I have an object called Apple which I want to move to a random position every X seconds. So my question is, what is the easiest way to execute this code every X seconds?

apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);

Thanks.

Edit:

Well do have a timer already like this:

Timer t = new Timer(10,this);
t.start();

What it does is draw my graphic elements when the game is started, it runs this code:

@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);
Misoxeny
  • 93
  • 2
  • 3
  • 10

4 Answers4

8

I would use an executor

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);
Liviu Stirb
  • 5,876
  • 3
  • 35
  • 40
2

Use a timer:

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);

Documentation: Oracle documentation Timer

CularBytes
  • 9,924
  • 8
  • 76
  • 101
Ospho
  • 2,756
  • 5
  • 26
  • 39
1

Simplest thing is to use Thread.sleep().

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

Run the above code in loop.

This will give you an approximate (may not be exact) one second delay.

Oriol Roma
  • 329
  • 1
  • 5
  • 9
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
1

You should have some sort of game loop which is responsible for processing the game. You can trigger code to be executed within this loop every x milliseconds like so:

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

        lastExecution = System.currentTimeMillis();
    }
}

In this example, the condition in the if statement would evaluate to true every 1000 milliseconds.

Phil K
  • 4,939
  • 6
  • 31
  • 56