I am trying to implement a game using ncurses in C. I have to show the current time (the time must update each second) and my while loop looks like this
while(1)
{
clk = time(NULL);
cur_time = localtime(&clk);
mvprintw(0,1,"%d %d %d",cur_time->tm_hour,cur_time->tm_min,cur_time->tm_sec);
int key = getch()
//other stuff
}
My problem is that the time will refresh only when I press a key. Is it a way to make the time refresh without the need of pressing a key (and to implement this in the same while)?
There are a couple of functions you could use:
int nodelay(WINDOW *win, bool bf);
Set bf true to make getch() non-blocking
void timeout(int delay);
Delay is in milliseconds, so if you set it to 1000, the getch will timeout after a second.
In both cases getch will return ERR if there is no input.
The solution here is EITHER to use non-blocking IO or to use threads. However, using threads will give you a new problem, which is that only one thread can use curses at any given time, so you will need to use locks or some such to prevent the other thread(s) from using curses at that point in time. Of course, one solution for that is to have one thread responsible for updating the screen content, and other threads simply send messages to that thread with "I want to put on the screen at X, Y"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With