#include #include #include #include #include #include #include"input_output.h" #include"playfield.h" int difficulty = 200; static struct termios oldt, newt; char * playfield; char ** horizon; static volatile char sigint_received = 0; int main(void) { // set up the terminal for our hacky game.... static struct termios oldt, newt; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); // ok done int pos = 0; unsigned long long int score = 0; char input = KEY_DEFAULT; int to_place = 0; printf("q: end; d: right; a: left\n\n\n"); while(input != KEY_EXIT && !(EOF_received || sigint_received)) { horizon_drop_one_line(horizon); // clear both the cursor and // the last enemy playfield[pos] = ' '; horizon[0][to_place] = ' '; if(input == KEY_RIGHT) { pos++; if(pos >= WIDTH) { pos = 0; } } if(input == KEY_LEFT) { pos--; if(pos < 0) { pos = WIDTH - 1; } } if(input == KEY_EXIT) { break; } clear_screen(); print_horizon(horizon); playfield[pos] = CHAR_ME; to_place = (random() & 0xff) % WIDTH; horizon[0][to_place] = CHAR_ENEMY; put_line(playfield); if(horizon[LINES - 1][pos] == CHAR_ENEMY) { printf("GAME OVER!\nYour score was: %llu\n", score); break; } usleep(difficulty * 1000); score++; if(!(score % 50)) { difficulty--; } if(score == 0) { printf("Congrats. You won the game.\nAnd you have absolutely no life.\nat all.\n"); break; } printf("SCORE: %llu\n", score); // check this to prevent blocking if(EOF_received || sigint_received) { break; } input = get_last_key_or_default(); } tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return 0; } void __attribute__((cold)) handle_sigint(int signum) { sigint_received = 1; } void __attribute__((cold)) handle_sigterm(int signum) { printf("\n\nTERMINATED!\n"); exit(1); } /* Constructor: Add a sighandler for SIGINT and SIGTERM */ void __attribute__((constructor)) add_signal_handlers(void) { signal(SIGINT, handle_sigint); signal(SIGTERM, handle_sigterm); } /* Destructor: Free memory */ void __attribute__((destructor)) clean(void) { free(playfield); delete_horizon(horizon); printf("\n"); } /* Constructor: create all the data we need */ void __attribute__((constructor)) build_playfield(void) { playfield = allocate_playfield(WIDTH); build_horizon(&horizon); }