0

I am doing a project in Java (RPG-Game) and there is a method, called "sleep()", if the hero sleep he can't fight against enemys or others and if he has for example 1 HP after he slept he gets max HP and then he is ready to fight. And my problem is that I need a timer for the sleep method, for example the Hero "Venus" sleeps for 3 Minutes and he can't fight in that time.

My attributes and my method:

public class Superhero {
private String id = UUID.randomUUID().toString();;
private String name;
private int healthPointsMax;
private int healthPointsCurrent;
private int damage;
private int critStrike;
private int critChance;
private String heroRole;
private int experiencePoints;
private String superpowers;
private boolean readyToFight;
private boolean inFight;
private boolean alive;`

and my method:

public void sleep() {
    System.out.println("Dein Superheld " + name + " legt sich schlafen.");
    System.out.println(name + " hat wieder volle HP, wenn er/sie wach ist.");
    setHealthPointsCurrent(getHealthPointsMax());
    readyToFight = false;
}
3
  • Did you try anything yet as for the timer? I don't see anything related to that in your post. Commented Dec 10, 2019 at 12:25
  • maybe you ask your question also on gamedev.stackexchange.com Commented Dec 10, 2019 at 12:47
  • Do you want nothing else happen while the hero is sleeping or do you want the rest of the game to continue (with the restriction that they can't fight)? Commented Dec 10, 2019 at 12:49

2 Answers 2

1

you can try using a java.util.Timer in your method as below :

public void sleep() {
    System.out.println("Dein Superheld " + name + " legt sich schlafen.");
    System.out.println(name + " hat wieder volle HP, wenn er/sie wach ist.");
    readyToFight = false;
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
         public void run() {
              setHealthPointsCurrent(getHealthPointsMax());
              readyToFight = true;
              timer.cancel();
         }
    };

    long delay = 120000L; // 2 minutes delay
    timer.schedule(task, delay);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Okay, Thanks I understand and if I write to long delay = 1000 would be that than 1 second? :/
0

You can instanciate an actual Timer in Java. Check the documentation here: https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.