Time limit in user input Prolog (read)

I am writing a translator for the game. The user enters his transition to the interpreter, and the program execution is executed.

Now I want to implement a time limit for each solution. The player must not think more than 30 seconds to write a movement and press enter.

call_with_time_limit seemed relevant, but it does not work properly as such:

call_with_time_limit (30, read (X)), problem, record (problem).

In this case, it waits for input, and when input is entered, the timer starts later. But I want the timer to start from the very beginning.

How can i do this?

+4
source share
2 answers

If you are interested in timeouts related to I / O, consider wait_for_input/3 or set_stream/2 . The built-in interface, call_with_time_limit/2 not a simple and reliable interface.

Edit: I just see that you are using read/1 for input. Please read in the above documentation how to avoid blocking in read/1 . I don’t understand why you need this, but the user can simply enter Return , thereby bypassing the initial timeout. read/1 now reads that '\n' , but will then wait for input - without a timeout, while the user generously pursues Wikipedia for an answer ... might even ask a question about SO ...

+3
source

Your approach seems reasonable: from SWI-Prolog docs: "I / O blocking can be handled using the read_term / 3 timeout parameter.

This is not very informative: changing the timeout per user leads to some error (I will test more and will report to the SWI_prolog mailing list, if necessary) even under catch / 3.

It seems to work

 ..., current_input(I), wait_for_input([I], A, 30), ... 

If the input is not specified (a shorter time to check here ...)

 ?- current_input(I), wait_for_input([I],A,5). I = <stream>(0x7fa75bb31880), A = []. 

EDIT : variable A will contain a list containing a list of streams with ready-made input: I just reported the case when the user does not enter anything before the timeout expires. To get the actual input, use the attached code:

 tql :- current_player(I), writef('Its %d. players turn: ', [I]), flush_output, current_input(Input), wait_for_input([Input], [Input], 5), read(Input, Move), writeln(Move). current_player(1). 

NTN

+1
source

Source: https://habr.com/ru/post/1385424/


All Articles