I am making a text based quiz and I want to make it so that if the player doesn't answer after a certain amount of time than it will act as if they got the question wrong. Im not really sure how to do this. I have a few ideas: Multithreading and Timers; However I have no idea how to do either.
Would either of those be good options for this?
Method with my question:
public void questionOneA(String choice) {
choice = scanner.nextLine();
setWrong(false);
switch(choice) {
case "a":
setLives(lives - 1);
setWrong(true);
if (getLives() > 0) {
System.out.println("WRONG! Try again.");
}
else {
System.out.println("WRONG!");
}
break;
case "b":
System.out.println("CORRECT!");
setCorrect(true);
break;
case "c":
setLives(lives - 1);
setWrong(true);
if (getLives() > 0) {
System.out.println("WRONG! Try again.");
}
else {
System.out.println("WRONG!");
}
break;
case "d":
setLives(lives - 1);
setWrong(true);
if (getLives() > 0) {
System.out.println("WRONG! Try again.");
}
else {
System.out.println("WRONG!");
}
break;
case "skip":
if (skips > 0) {
setSkips(skips - 1);
setCorrect(true);
}
else {
System.err.println("You do not have any skips left!");
}
break;
default:
System.err.println("Please type an answer.");
break;
}
}
You can do it the same way you would for anything else that's based on doing something after a certain amount of time, with either a Timer
or a Delta-time loop
setting off an event (in this case one that corresponds to getting the question wrong) after a certain amount of (delta-)time.
Assuming your quiz runs in a loop (as games and game-like software should), then all you need to do is:
//Specify a maximum time and record it in a variable; in this case, I'm using milliseconds as unit, and 30 seconds of time.
long maxQuestionTime = 30000;
//Outside the game-loop, at start of a question, record a timestamp of the current time + max time.
long maxQuestionTimestamp = System.currentTimeMillis()+maxQuestionTime;
//Inside game-loop, check if current time has gone above the timestamp, effectively measuring elapsed time.
if(System.currentTimeMillis()>maxQuestionTimestamp){
//fail the question here
}