user5544654
user5544654

Reputation:

Run a method every X seconds

I'm creating a text based game in Java as my first official program on my own. It's survival game with Hunger, Thirst, and Body Temperature variables.

Lets say I want hunger and thirst to decrease once every 5 seconds or so. Only thing I can get to work at the moment is this. This deceases the numbers for sure, but it goes from 100 to 0 in 2 seconds.

public void run(){
  while(running){
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while(delta >= 1){
            tick();
            delta--;
        }
    }
private void tick(){
  Health.playerHealth.tick();
}

///////////////////////////////////////////////

public static Health playerHealth = new Health();

private static int hunger = 100;
private static int thirst = 100;
private static double bodyTemperature = 98.6;

public void tick(){
    depleteHunger();
    depleteThirst();
    depleteBodyTemperature();
}

public void depleteHunger(){
    hunger--;

}

public void depleteThirst(){
    thirst--;
}

I've tried this timer as well, but it only waits 5 seconds i put in THEN decreases from 100 to 0 instantly

private void tick(){

Timer t = new Timer();
  t.schedule(new TimerTask() {
    @Override
    public void run() {
      depleteHunger();
      depleteThirst();
      depleteBodyTemperature();
    }
  }, 0, 5000);
}

Upvotes: 1

Views: 7636

Answers (3)

user5544654
user5544654

Reputation:

found a solution.

public class HealthStatsTimer extends TimerTask {
  public void run() {
    Health.playerHealth.depleteHunger();
    Health.playerHealth.depleteThirst();
    Health.playerHealth.depleteBodyTemperature();
  }
}
//////////////////////
public static void main(String[] args){
  new Stranded();

  Timer timer = new Timer();
  timer.schedule(new HealthStatsTimer(), 5000, 5000);
}

Upvotes: 0

Anton Shadrin
Anton Shadrin

Reputation: 107

final int TICKS_PER_SECOND = 20;
final int TICK_TIME = 1000 / TICKS_PER_SECOND;

while (running) {
    final long startTime = System.currentTimeMillis();
    // some actions
    final long endTime = System.currentTimeMillis();
    final long diff = endTime - startTime;

    if (diff < TICK_TIME) {
        try {
            Thread.sleep(TICK_TIME - diff);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 0

Parijat Purohit
Parijat Purohit

Reputation: 921

Probably you can look at timer's scheduleAtFixedRate:

Sample example:

Timer timerObj = new Timer(true);
timerObj.scheduleAtFixedRate(timerTask, 0, interval));

This method basically does what you wish to achieve: execute a task at specific intervals. You need to initialized the TimerTask object by overriding the run() method and putting your logic inside that though (as you have mentioned in your code as well).

Upvotes: 1

Related Questions