0

this is my first question on stackoverflow :)

I'm trying to make the Snake game, and I'm having trouble setting a timer for the user input.

With Snake I want to read input(a string) from the user in order to know which way do to move (up,down,right,left) in the next iteration. However I want to continue the script even if the user doesn't provide an input for 200ms. (I want it to continue moving the same direction it moved prior)

I tried to look everywhere and I cant seem to find a solution. I am using StdIn library for reading input.

I tried using "sleep" or "System.currentTimeMillis()" but whenever I enter the StdIn.readString(); line it will not leave this line until the user provides the input.

edit:(code added + explanation)

The function is recursive and calls itself endlessly until the user has lost the game. Each iteration I go to this part of the code to read the user input using StdIn.readString(), and I want to exit the StdIn.readString() method if 200ms has passed since calling the method.

    String inputStr = StdIn.readString();
    c = inputStr.charAt(0);
    if (c != 'w' && c != 's' && c != 'a' && c != 'd') {
        System.out.println("invalid input");
        play(x, y, c, snakeParts, food);
    }

Thanks in advance!

0 Answers0