diff --git a/nsnake b/nsnake index dca6414..9942424 100755 Binary files a/nsnake and b/nsnake differ diff --git a/obj/main.o b/obj/main.o index 38b473c..9de51b2 100644 Binary files a/obj/main.o and b/obj/main.o differ diff --git a/obj/snake.o b/obj/snake.o index 36c3503..8beece2 100644 Binary files a/obj/snake.o and b/obj/snake.o differ diff --git a/src/include/main.h b/src/include/main.h index 02b5028..df6e766 100644 --- a/src/include/main.h +++ b/src/include/main.h @@ -1,8 +1,12 @@ #ifndef MAIN_H #define MAIN_H +#include "snake.h" +#include "field.h" + void die(char *, ...); void free_s(void *); int irandom(int, int); +void game_over(Snake *, Field *, char *, ...); #endif diff --git a/src/include/snake.h b/src/include/snake.h index fa1b0ed..734e76b 100644 --- a/src/include/snake.h +++ b/src/include/snake.h @@ -22,5 +22,6 @@ void delete_snake(Snake *); void snake_forward(Snake *, int); void snake_print(Snake *); int snake_eat(Snake *, Field *); +int snake_collide(Snake *, int, int); #endif diff --git a/src/main.c b/src/main.c index b1e3c4b..977d9d2 100644 --- a/src/main.c +++ b/src/main.c @@ -32,6 +32,21 @@ int irandom(int lower, int upper) { return i; } +void game_over(Snake *s, Field *f, char *fmt, ...) { + va_list args; + va_start(args, fmt); + + delete_snake(s); + delete_field(f); + endwin(); + + vprintf(fmt, args); + printf("\n"); + + va_end(args); + exit(0); +} + int main(void) { int c, dirn, score; Snake *s; @@ -74,11 +89,13 @@ int main(void) { dirn = LEFT; break; case quit_key: - goto quit; + game_over(s, f, "SEE YOU LATER! SCORE: %d", score); break; } snake_forward(s, dirn); + if (snake_collide(s, getmaxx(stdscr), getmaxy(stdscr) - 1)) + game_over(s, f, "!! GAME OVER !! COLLISION !! SCORE: %d", score); score += snake_eat(s, f); box(stdscr, 0, 0); @@ -89,9 +106,4 @@ int main(void) { refresh(); napms(screen_speed); } - -quit: - delete_snake(s); - delete_field(f); - endwin(); } diff --git a/src/snake.c b/src/snake.c index 84eb963..8861d5d 100644 --- a/src/snake.c +++ b/src/snake.c @@ -83,3 +83,22 @@ int snake_eat(Snake *s, Field *f) { return 0; } + +int snake_collide(Snake *s, int x_max, int y_max) { + if (s->n[0]->x == x_max) + return 1; + if (s->n[0]->y == y_max) + return 1; + if (s->n[0]->x == 0) + return 1; + if (s->n[0]->y == 0) + return 1; + + for (size_t i = 1; i < s->len; i++) { + if (s->n[0]->x == s->n[i]->x) + if (s->n[0]->y == s->n[i]->y) + return 1; + } + + return 0; +}