diff options
Diffstat (limited to 'snake.c')
| -rw-r--r-- | snake.c | 29 |
1 files changed, 19 insertions, 10 deletions
@@ -11,19 +11,27 @@ #include "conio.h" #include "colors.h" -volatile sig_atomic_t INT_CTRL_C = 0; +#define UNUSED(x) (void)(x) -//unsafe functions like printf cannot be called in async interrupt handler -void interrupt_handler(int sig) { - INT_CTRL_C = 1; -} +/*** GLOBAL VARIABLES ***/ +volatile sig_atomic_t INT_CTRL_C = 0; //flag for ctrl-c interrupt +int SCORE = 0; int boardSize = 15; const int updateInterval = 300000000L; + vectorp_t snakePositions; vector_t foodPos; vector_t lastMoveDir; +void interrupt_handler(int sig); // passed into signal(3) to handle ctrl-c interrupts + +//unsafe functions like printf cannot be called in async interrupt handler +void interrupt_handler(int sig) { + UNUSED(sig); + INT_CTRL_C = 1; +} + int main(int argc, char **argv) { for (int i = 0; i < argc; i ++) { if (strcmp("--version", argv[i]) == 0) { @@ -46,7 +54,7 @@ int main(int argc, char **argv) { int smallestAxis = width / 2 < height ? width / 2 : height; boardSize = smallestAxis < boardSize ? smallestAxis : boardSize; //hide cursor - printf("\e[?25l"); + printf("\033[?25l"); //make a new thread handling interrupts signal(SIGINT, interrupt_handler); //init values @@ -76,10 +84,10 @@ int main(int argc, char **argv) { //handle ctrl-c interrupt if (INT_CTRL_C) { //unhide cursor - printf("\e[?25h"); + printf("\033[?25h"); //kill the listener thread *cancellationToken = 1; - printf("Press any key to exit\n"); + printf("Your score was %d. Press any key to exit\n", SCORE); pthread_join(listenerID, NULL); free(cancellationToken); free((int*)lastInput); @@ -106,6 +114,7 @@ int main(int argc, char **argv) { int ateFood = 0; if((snakePositions.vectors[0].mx + lastMoveDir.mx == foodPos.mx) && (snakePositions.vectors[0].my + lastMoveDir.my == foodPos.my)) { ateFood = 1; + SCORE = SCORE + 1; //move the food while(1) { foodPos = init_vector(1 + (rand() % (boardSize - 2)), 1 + (rand() % (boardSize - 2))); @@ -139,8 +148,8 @@ int main(int argc, char **argv) { } //clear the last getch call from the listener *cancellationToken = 1; - printf("\n%sYou died. Press any key to exit%s\n", RED, COLOR_RESET); - printf("\e[?25h"); + printf("\n%sYou died. Score: %d. Press any key to exit%s\n", RED, SCORE, COLOR_RESET); + printf("\033[?25h"); pthread_join(listenerID, NULL); free(cancellationToken); free((int*)lastInput); |
