user1116768
user1116768

Reputation:

How to put a time limit on user input?

I have tried various setups with input and my one second timer but nothing is working. The entire code is brought to a halt when it reaches the part asking for input. I have an unbuffered stream, so I don't need to press enter to send the input. Also the purpose of this is for a pac-man game I'm designing for terminal use. What I want is basically to have a one second interval where the user can enter a command. If no command is entered, I want the pac-man to continue moving the direction it was moving the last time a command was entered.

EDIT:

time_t startTime, curTime;

    time(&startTime);
    do
    {
        input=getchar();
        time(&curTime);
    } while((curTime - startTime) < 1);

Upvotes: 0

Views: 2909

Answers (4)

Irfy
Irfy

Reputation: 9587

My gut feeling tells me this:

  • Have one thread dedicated to processing user input and putting key events into a queue
  • The timer-activated thread, on every activation, consumes all key events in the queue, using the one that happened last, at the point of thread activation.

Make sure your access to the queue is synchronized.

// I/O Thread:
while (!stop) {
    input = getchar();
    lock_queue();
    queue.push_back(input);
    unlock_queue();
}

// Timer Thread:
while (!stop) {
    lock_queue();
    if (queue.size() == 0) {
        action = DEFAULT_ACTION;
    } else {
        // either handle multiple key events somehow
        // or use the last key event:
        action = queue.back();
        queue.clear();
    }
    unlock_queue();
    perform_action(action);
    sleep();
}

Full example posted as a Github Gist.

Upvotes: 0

Kaz
Kaz

Reputation: 58500

On Unix, you can simply use select or poll with a timeout on the standard input file descriptor (STDIN_FILENO, or fileno(stdin)). I would not bring in mouse traps built of signals and threads just for this.

Upvotes: 1

Sean Dawson
Sean Dawson

Reputation: 5786

You could use a non-blocking input function such as getch() but it isn't very cross platform compatible.

Ideally you should be using events to update the game state, depending on which OS you are targeting you could use the OS events for key press or maybe a library such as SDL.

Upvotes: 0

greg
greg

Reputation: 4953

You could try using alarm() (or similar timer function) to throw and have your application catch a SIGALRM, though this is definitely overkill for PacMac. Consider using a separate thread (POSIX thread) to control a timer.

Upvotes: 2

Related Questions