ncurses
можно использовать. timeout()
важен, поскольку он меняет getchar()
для предотвращения блокировки.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <ncurses.h>
#define WAIT 60.0
#define MILLION 1E6
int main ( void)
{
char ch = 0;
char *words[] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", NULL};
int row = 0;
int line = 0;
int col = 0;
int counting = 1;
char text[80] = {""};
float elapsed = 0.0f;
struct timeval start;
struct timeval stop;
srand ( time ( NULL));
int items = sizeof words / sizeof words[0];//number of words
items--;//to keep NULL at the end
while ( items > 1) {//shuffle words pointers
items--;
int swap = rand ( ) % items;
char *temp = words[swap];
words[swap] = words[items];
words[items] = temp;
}
items = 0;
initscr ( );
noecho ( );
timeout ( 100);//so getchar does not block
getmaxyx ( stdscr, row, col);//screeen size
line = row / 2;//center vertically
snprintf ( text, sizeof ( text), "press x to exit or Enter to reset");
mvprintw ( line - 1, ( col - strlen ( text)) / 2,"%s", text);//center horizontally
mvprintw ( line + 1, ( col - strlen ( words[items])) / 2,"%s", words[items]);
gettimeofday ( &start, NULL);
while ( 1) {
if ( counting) {
gettimeofday ( &stop, NULL);
elapsed = (float)(stop.tv_sec - start.tv_sec)
+ ( (float)(stop.tv_usec - start.tv_usec) / MILLION);
move ( line, 0);//move to start of line
clrtoeol ( );//clear to end of line
snprintf ( text, sizeof ( text), "%f", WAIT - elapsed);
mvprintw ( line, ( col - strlen ( text)) / 2,"%s", text);//center text
}
else {
move ( line, 0);//move to start of line
clrtoeol ( );//clear to end of line
snprintf ( text, sizeof ( text), "paused press x or Enter");
mvprintw ( line, ( col - strlen ( text)) / 2,"%s", text);
}
if ( elapsed > WAIT || ( ch = getch ( )) == 'x' || ch == '\n') {
if ( elapsed > WAIT || ch == '\n') {
gettimeofday ( &start, NULL);
elapsed = 0.0f;
counting = !counting;
if ( counting) {
items++;
if ( words[items]) {
move ( line + 1, 0);
clrtoeol ( );
mvprintw ( line + 1, ( col - strlen ( words[items])) / 2,"%s", words[items]);
}
else {
break;
}
gettimeofday ( &start, NULL);
}
}
if ( ch == 'x') {
break;
}
}
}
endwin ( );
return 0;
}