Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ncurses and realtime (implemented in C, unix)

Tags:

c

ncurses

time.h

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)?

like image 375
Silent Control Avatar asked Dec 29 '12 15:12

Silent Control


2 Answers

There are a couple of functions you could use:

  1. nodelay
  2. timeout

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.

like image 188
parkydr Avatar answered Nov 04 '22 06:11

parkydr


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"

like image 25
Mats Petersson Avatar answered Nov 04 '22 06:11

Mats Petersson