Reputation: 438
I'm working on a game written in Scala where the user has to type "BANG" as quickly as possible in order to hunt an animal.
// ...
println("When you see an animal, type BANG as quickly as possible.")
Thread.sleep(2000 + Random.nextInt(6000))
val start = System.currentTimeMillis()
println("You see an animal!")
val bang = readLine("")
val time = System.currentTimeMillis() - start
if (bang == "BANG" && time <= 1500) {
// ...you get the point
Unfortunately, there's a bug that makes so that you can type "BANG" ahead of time and always win, because it accepts input before the readLine()
.
I have tried a few different ways of clearing the input. The obvious solution, putting a readLine()
before val start = System.currentTimeMillis()
, doesn't work because it forces the user to press enter first.
Any ideas?
Upvotes: 1
Views: 255
Reputation: 68660
There's no standard way of clearing stdin with Scala's (or even Java's) API.
You can use this lower-level implementation RawConsoleInput
to clear the buffer though.
It has a read
method that returns the first character in the standard input, or -2
if the buffer is clear.
Because it uses "raw input mode", instead of the usual "line mode", keys like Enter, backspace, Ctrl+C will NOT be processed by the operating system, and will remain in the buffer until read
is called.
//drain standard input
while(RawConsoleInput.read(wait = false) >= 0) {
}
Signature:
/**
* Reads a character from the console without echo.
*
* @param wait
* <code>true</code> to wait until an input character is available,
* <code>false</code> to return immediately if no character is available.
* @return
* -2 if <code>wait</code> is <code>false</code> and no character is available.
* -1 on EOF.
* Otherwise an Unicode character code within the range 0 to 0xFFFF.
*/
public static int read (boolean wait) throws IOException
Note: make sure you've imported the JNA library.
Upvotes: 2