-2

Iam new here, like week ago I started learning to program and Iam working on my text based strategic game in which I would like to make resources gather every x seconds passively.

basicaly my game is based on while (true) loop in which are switch cases and the game keeps waiting for keys to press to gather resources.

I would like the game to gather resources passively every x seconds.

example : every 10 seconds you will receive +1 wood.

I will welcome in help :) Iam programming in java using NetBeansIDE

3 Answers3

0

Just get the current time in every loop run with this and check whether the 10 seconds passed since last time you gave +1 wood. Note the time unit.

kolakao
  • 71
  • 1
  • 9
0

I am not sure how you are storing gathered resources, but if you could call a method to look it up based on when the game began. You could store the following variable as part of your game class:

private long startTime = System.currentTimeMillis();

And then get current resources by using the following method:

public int getWood() {
    long diffMilliseconds = System.currentTimeMillis() - startTime;
    int numSeconds = (int)diffMilliseconds / 1000;
    int amtWood = numSeconds/10;
    return amtWood + <any other wood gathering/calculating parameters>;
}

This does not account for using your wood. If you want a variable to update every ten seconds, you could use something like the solution here: Print "hello world" every X seconds. This solution uses the TimeTask class. Rather than printing, you could update a amtWood variable.

Community
  • 1
  • 1
  • thank you, I checked your link and this code works as I want, problem is that if I use wood = wood + 1; instead of system.out.Println .. it says local variables referenced from inner class must be final or effectively final , maybe the problem is that my resources are stored as an integer? class SayHello extends TimerTask { public void run() { System.out.println("Hello World!"); } } // And From your main() method or any other method Timer timer = new Timer(); timer.schedule(new SayHello(), 0, 5000); – Václav Stýblo May 04 '16 at 16:35
  • Don't make wood a local variable, make it an instance or class variable. You can declare private int wood; under your class declaration. – GoneTaPlaid May 04 '16 at 16:43
0

If there are no restrictions on what classes you can use, try Timer class available as part of Java Swing. You can also look at java.util.Timer class for scheduling your updates.

Prat P.
  • 21
  • 4