Search code examples
javatext-basedsystem-clock

Handling time in a text-based game (Java)


I'm trying to work up a basic text-based game as I'm learning Java. I'd like to be able to count rounds in the game as a means of managing the pacing of certain events. For instance, changing rooms could be limited to once per round (a second, in the test code.) A small creature might attack or change rooms at a higher rate, whereas a larger one might be more cumbersome. Good so far? Great.

So, I cooked this up and immediately realized that I'd be hitting a block each time the while loop waited for the player to input a command. Code:

private void startPlaying() {
    //declare clock/round variables.
    int lastRound = 0;
    int currentRound = 0;
    long lastTime = System.currentTimeMillis();
    long currentTime;

    while (player.getIsPlaying()){
        //Clocking
        currentTime = System.currentTimeMillis();
        if ((lastTime + 1000) < currentTime) {
            lastTime = currentTime;
            lastRound = currentRound;
            currentRound++;
            System.out.println("Current round:\t" + currentRound + "\tCurrent time:\t" + currentTime); //EDIT:NOTE: This is just a test line to observe the loop.
        }//end if (Clocking)

        Command command = new Command();
        String[] commandString = command.setAll(); //Array gets parsed elsewhere.
        player.doCommand(commandString);  
        //Class Player extends Pawn extends Actor; Pawn has most command methods.
    }
    finishPlaying();
}//END STARTPLAYING()

So, here is my question:

Is there a way I could use a separate method to log time/rounds concurrent to the while loop presenting the player with a command prompt?

If not, is there a different way to make this a non-issue that I'm just not seeing/practiced in yet?


Solution

  • Take a look at Concurrency tutorial. With threads you can wait user input without stopping other processes (and make these other processes execute at the same time - not in parallel, but time-sharing).