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?
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).
It is called "game loop" which allows the game to run smoothly regardless of the input of the user.
The most straightforward solution - create 2 threads, frist will wait for user input and puts it into ConcurrentLinkedQueue
with capacity 1. The second thread will run your game loop and takes user input from queue to process it if queue is not empty.
You can use any data structure you want to exchange data between 2 threads, it can be even volatile string variable. The only requirements read write access to this variable should be synchronized somehow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With