collision added, game over message

This commit is contained in:
Noah Swerhun 2021-09-18 20:39:48 -05:00
parent 2805dff95f
commit bfd45695f3
7 changed files with 42 additions and 6 deletions

BIN
nsnake

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -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

View file

@ -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

View file

@ -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();
}

View file

@ -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;
}