I am trying to make a text based game which involves a timer in the centre of the screen.
The idea is that every 10 seconds, your strength(stamina) depletes by -2. And once you get to 0% strength, you die.
So far, I have a working timer, not yet converted into mins:seconds, just a basic seconds timer, however, my strength starts on 0% rather than 100% and the number does not change
I tried this by making a while loop with a nested if loop inside of it.
My thought process involved:
While strength is bigger than 0%, if second % 10 == 0 then deplete by -2 and set new strength to new value
Else if second % 10 != 0 then second
I'd really appreciate any help as it is for my A level course
CodePudding user response:
I suggest you focus your attention on the stamina level rather than on accumulating time count. The stamina level is what drives your game really. And I imagine your game might eventually gain a feature where stamina can increase as well as decrease.
ScheduledExecutorService
A scheduled executor service can run a task after a specified amount of time elapses.
ScheduledExecutorService ses = Executors. newSingleThreadScheduledExecutor() ;
Define your task as implementing Runnable
or Callable
. That task would do three things, after checking that we have some remaining stamina:
- Decrement the stamina level kept in an
AtomicInteger
. - Call back to the user-interface to note the change in stamina status. GUI frameworks such as Vaadin, JavaFX, and Swing offer a hook for thread-safe callbacks.
- Reschedule itself with the scheduled executor service.
Be sure to eventually shut down your executor service before your app ends. See boilerplate code given on Javadoc for ExecutorService
.
CodePudding user response:
Not certain how this will fit into your design but here is one way to schedule a countDown timer.
First, create a class that subclasses TimerTask.
class MyTask extends TimerTask {
int strength;
int decrement;
public MyTask(int initialStrength, int decrement) {
this.strength = initialStrength;
this.decrement = decrement;
}
public void run() {
strength -= decrement;
System.out.println(strength);
}
public int getStrength() {
return strength;
}
}
The you can start a Timer supplying the task, initial delay, and duration. Here the duration is 2 seconds.
Timer t = new Timer("MyTimer");
MyTask myTask = new MyTask(1000, 2);
t.schedule(myTask, 0, TimeUnit.SECONDS.toMillis(2));
prints every two seconds
98
96
94
92
90
88
...
...