1

I have a Sudoku game written in Java. The main course of the game is in main method. I have a while loop, in which I have myClassObject.getCommandFromScanner() function to read input with Scanner, so user can fill the empty position on a sudoku board or choose other option from menu(for example save, show solution and exit to main menu). This loop ends only if user choose exit to menu, because function myClassObject.getCommandFromScanner() return false only in that case. I want to set the specified time of game, but cannot do it in while loop (while((System.currentTimeMillis()-nGame.timeAtStart < 10000) && myClassObject.getCommandFromScanner())) <- for the first time the first condition is true and loop can wait for user input on and on. Only if user enter something, the loop condition is chceck again and then exit from this loop. How can I solve this problem? I also try to use ExecutorService and it almost work, the loop is executing for specified time, but then it exit to menu and user cannot start new game. Scanner stop working correctly and my main window with game is crashed... I am new here so sorry if my question isn't clear enough. I hope you will help me

public class Sudoku
{
public static void main(String[] args) throws Exception
{        
while(course != exit)
{
    opt = new String(in.next());
    int option;

    option = Character.getNumericValue(opt.codePointAt(0));

    if(course == menu)
    {
        //go to menu
    }

    else if(course == newGame)
    {
        //setup new game
    }

    if(course == game)
    {
        nGame.timeAtStart=System.currentTimeMillis();
        myClassObject.setGame(newGame);

        ExecutorService executor = Executors.newFixedThreadPool(1);
        Future<?> future = executor.submit(new Runnable() {
            @Override
            public void run() {
                try{
                    while(myClassObject.getCommandFromScanner());
                }
                catch(Exception e) {}
            }
        });

        executor.shutdown();

        try {
            future.get(8, TimeUnit.SECONDS);  //
        } catch (InterruptedException e) {    //
            System.out.println("job was interrupted");
        } catch (ExecutionException e) {
            System.out.println("caught exception: " + e.getCause());
        } catch (TimeoutException e) {
            future.cancel(true); 
            System.out.println("Your game timed out!");
        }

        course.printMessage("TIMEOUT");
        course = menu;

    }
}
}
}

This is original version of my code:

public class Sudoku
{
public static void main(String[] args) throws Exception
{        
while(course != exit)
{
    opt = new String(in.next());
    int option;

    option = Character.getNumericValue(opt.codePointAt(0));

    if(course == menu)
    {
        //go to menu
    }

    else if(course == newGame)
    {
        //setup new game
    }

    if(course == game)
    {
        nGame.timeAtStart=System.currentTimeMillis();
        myClassObject.setGame(newGame);
        while(myClassObject.getCommandFromScanner()); //while user don't choose 'menu' option, read input from keyboard
        course = menu; //user choose 'menu', go to menu section

    }
   }
  }

} I want to set the max time for game, then show message: "timeout" and go to main menu

adnut
  • 29
  • 4
  • 1
    Possible duplicate of [Time out method in java](http://stackoverflow.com/questions/8982420/time-out-method-in-java) – brummfondel Dec 03 '16 at 14:36

1 Answers1

1

The TimerTask may help :

TimerTask task = new TimerTask()
{
    public void run()
    {
        if( str.equals("") )
        {
            System.out.println( "TimeOut. exit..." );
            System.exit( 0 ); //or other operation.
        }
    }    
};
Timer timer = new Timer();
timer.schedule(task, 10*1000 );  //10 seconds
String cmd = myClassObject.getCommandFromScanner();
timer.cancel();  //if not timeout ,cancle it.
System.out.println( "you have entered: "+ cmd );

Ref:https://stackoverflow.com/a/5854048/6037575

UPDATED:

Set timeout for the whole game:

static void main(){
...
// ready to start the game
TimerTask task = new TimerTask()
{
    public void run()
    {

            System.out.println( "TimeOut.Return to the mani menu." );
            course = menu; // how to return main menu is dependent on you

    }    
};

while(true){
//  Here the user is playing the game.
// and if he can work it out before timeout
// you should do something else to end the game.
}

Sorry I can't give you the real code which can working just dependent on the code you have given, but only some pseudocode that I think may be a feasible solution.

Community
  • 1
  • 1
Dai Kaixian
  • 1,045
  • 2
  • 14
  • 24
  • First of all, my function getCommandFromScanner return boolean. It read input and return true if user write command to fill the empty position on board, if choose prompt, save game, but return false if user want to exit to the main menu (where he can start new game for example). And only then my while loop breaks. User can enter command all the time, but if it lasts more than e.g 10 seconds I want to stop game and return to main menu. – adnut Dec 03 '16 at 14:17
  • So are't you just waiting for the user to press 'Enter'? If he pressed, the scan.reaLline() return. And you can continue your game.But if it has been 10 seconds before he pressed 'Enter',you exit your game. – Dai Kaixian Dec 03 '16 at 14:25
  • I don't want to exit, just to return false. But run method is void – adnut Dec 03 '16 at 14:38
  • I have a while loop to enable user fulfilling the sudoku. He can enter command which position he wants to fill. For example he enter: 2x1:4, 4x5:9, etc, and after specified time the game should timeout and return to the main menu, where user can decide whether he wants to start new game or exit program. In your solution, when I enter my first command, the exception occured because "java.lang.IllegalStateException: Task already scheduled or cancelled". Second problem is that I only want to return false from the loop and go to menu – adnut Dec 03 '16 at 14:58
  • So I get it .You want to set the time of the whole game ,not the single step ,right? – Dai Kaixian Dec 03 '16 at 15:19
  • Exactly, I want to give the user 15 minutes to solve the sudoku, after this time he returns to the main menu of the game – adnut Dec 03 '16 at 16:19