0

I'm working on a typing game written in C and ncurses.
The game asks player to enter lines of text. If the input from the user is identical to the string, it then continue to ask the user to enter next line of string.
And I want to show a timer on the top of the screen to let user know how much time does he/she spend already.

Currently, the main architecture of the game is like this:

Main thread:   1. Use getstr() to get the input of the user 
               2. Check if the input string is correct
               3. If yes, use printw() to print the next line of string.

Second thread: 1. Get current time
               2. Save the current cursor position, use mvprintw() to print
                  current time at top of the screen and move() back to the
                  cursor position that has been saved before.
               3. sleep() 1 seconds

However, when the user is typing, sometimes the character might be printed on top of the screen and the display of the game become messy.
Is there a better way that can fix the issue?

Abra
  • 19,142
  • 7
  • 29
  • 41
  • 1
    A typical user-interface usually needs to be single-threaded and event-based. Instead of calling an input function that blocks your program, try to find a way to make it event-based, or possible using polling of non-blocking input functions. Both are relatively easy to do in a POSIX environment (where ncurses is most commonly used). – Some programmer dude Mar 11 '20 at 07:16
  • For example, using polling, you can have a loop which iterates ten times every second. Each iteration it polls the input to see if there is any, and if there is it handles it. Otherwise it does other things, like checking the time to see if it's changed and then update the clock in the user-interface. – Some programmer dude Mar 11 '20 at 07:18
  • Another possible solution is to have one thread that only does input, another that only does output, and a possible third that handles other events (like checking the time). Whenever something needs to be updated in the user-interface, a "message" is passed to the "output" thread which updates the display accordingly. – Some programmer dude Mar 11 '20 at 07:21

0 Answers0