Skip to content

Instantly share code, notes, and snippets.

@trnila
Last active October 5, 2020 13:38
Show Gist options
  • Save trnila/57da254d2a8a48020d2ffd2cb0cb75d0 to your computer and use it in GitHub Desktop.
Save trnila/57da254d2a8a48020d2ffd2cb0cb75d0 to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <signal.h>
struct termios orig;
void term_cursor_setpos(int row, int col) {
printf("\033[%d;%dH", row, col);
}
void term_putchar(int row, int col, char c) {
term_cursor_setpos(row, col);
putchar(c);
}
void term_cursor_show(int show) {
if(show) {
printf("\e[?25h");
} else {
printf("\e[?25l");
}
}
void term_clearscreen() {
printf("\033c");
}
void term_restore(int signal) {
printf("da end\n");
tcsetattr(0, TCSANOW, &orig);
term_clearscreen();
term_cursor_show(1);
exit(0);
}
void term_init() {
struct termios conf;
tcgetattr(0, &orig); // get current terminal configuration
conf = orig;
conf.c_lflag &= ~(ECHO | ICANON); // disable echoing typed characters
conf.c_cc[VMIN] = 0;
conf.c_cc[VTIME] = 0; // nonblocking input
tcsetattr(0, TCSANOW, &conf); // set new terminal configuration
// restore terminal to original state on application exit
struct sigaction action = {0};
action.sa_handler = term_restore;
sigaction(SIGTERM, &action, NULL);
sigaction(SIGINT, &action, NULL);
sigaction(SIGKILL, &action, NULL);
setvbuf(stdout, NULL, _IONBF, 0); // disable stdout buffering
term_clearscreen();
term_cursor_show(0);
}
int main() {
term_init();
while(1) {
// handle event
char c;
while(read(0, &c, 1) == 1) {
// ctrl+c or 'q' pressed
if(c == 3 || c == 'q') {
return 0; // end the loop
} else if(c == 'A') {
printf("up\n");
} else if(c == 'B') {
printf("down\n");
} else if(c == 'D') {
printf("left\n");
} else if(c == 'C') {
printf("right\n");
}
}
term_putchar(rand() % 10, rand() % 10, '#');
usleep(50000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment