0
votes

So basically I try to get back into Java by programming a round based Game

Till now you only could start a new round by pressing a button ( x)

if (x.getKeyChar() == 'o') {      

            TimerRounds.cancel();
            // methods to start the next round //
            TimerRounds = new Timer();
            // Timer Method
            Timer Rounds.schedule(new TimerTask() {
                public void run() {
                    System.out.println("Time is over, next round is started");
                 //methods to start the next round //
                  //Timer has to start from the beginning again//
                     //already tried to start the timer here, didnĀ“t work//
                }
            }, 3000);

Let me explain the code: If the player presses o, a new round is started and it is t he turn of the next player. However, in addition to that, there is a countdown for each round and if the countdown is expired, a new round starts automatically

I manage to do everything, but what I do not understand is the following problem: The Timer ends and a new round starts , but how do I manage that it automatically starts a new timer for the next round? Till now it only does when the key is pressed, but I want it to start a new timer as well whenever the countdown from the last round is expired.

I hope you get the Problem, my english is really bad Would be great to get some advice

2

2 Answers

1
votes

You should separate three concerns of your code: Your actual turn structure, where turns can end and new turns can begin, the game's user interface, where he can press the button, and the game's timing logic.

In your turn structure class, you would have a startNextTurn method that cancels a possible pending timer and starts a new one. In your user interface class, you would call that method - don't do the timer logic in the user interface, let the turn structure do it.

Instead of using a Timer directly, encapsulate it into a class that provides two methods: cancelTimer and startTimer; the timer going off would call startNextTurn. Depending on your needs, you could even combine them into a restartTimer method.

When designing these units of abstractions, think of these issues: What kind of data and logic belongs together? What does an operation have to do to be complete? For example, starting a new turn is only complete when the timer is started, so it needs to be encapsulated by a method, and the two events (user input and timer) that trigger a new turn will both reuse the same logic.

0
votes

You might want to look into Timer's fixed-delay execution. This will let you schedule repeating tasks