Skip to content

Instantly share code, notes, and snippets.

@REPOmAN2v2
Created September 3, 2014 09:38
Show Gist options
  • Save REPOmAN2v2/67eb1b4d3c532f1f802a to your computer and use it in GitHub Desktop.
Save REPOmAN2v2/67eb1b4d3c532f1f802a to your computer and use it in GitHub Desktop.
Some ncurses functionality in str8 C
#include <stdio.h> // I/O Junk
#include <stdlib.h> // For rand()
#include <unistd.h> // For usleep()
#include <signal.h> // For Signal handler
#ifdef __linux__
#include <termios.h> // To change term settings (no echo mode)
#elif _WIN32
#include <conio.h>
#else
#error "Unsupported operating system"
#endif
#ifdef __linux__
#define getch() getchar()
/* Where we store our old settings and make a function which is called on exit */
struct termios init_settings;
void exit_proc(void)
{
tcsetattr(STDIN_FILENO, TCSANOW, &init_settings);
}
/* Check if we have input */
int kbhit(void)
{
struct timeval tv = { 0 };
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
return select(1, &fds, NULL, NULL, &tv);
}
#endif
/* Catch SIGINT so the program can exit and restore modes correctly */
void signal_handler(int signo) { if (signo == SIGINT) exit(1); }
int main(void)
{
/* Catch all SIGINT's (^C) and use it to exit program */
signal(SIGINT, signal_handler);
/* Print details before changing mode */
printf("Select the speed:\n"
"\t1 (Slow)\n"
"\t2 (Medium)\n"
"\t3 (Fast)\n"
);
#ifdef __linux__
/* Store current term settings */
tcgetattr(STDIN_FILENO, &init_settings);
atexit(exit_proc);
/* Noecho mode */
struct termios new_settings = init_settings;
new_settings.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &new_settings);
#endif
int speed = 5000; /* Default to medium */
while (1) {
if (kbhit()) { /* If we got a character in the queue deal with it */
int c = getch();
switch (c) {
case '1':
speed = 10000;
break;
case '2':
speed = 5000;
break;
case '3':
speed = 1000;
break;
default:
; /* Do nothing */
}
}
usleep(speed);
fflush(stdout);
printf("\033[22;3%dm %d", rand() % 10, rand() % 10);
}
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment