#include "snake.h" #include struct snake* add_snake(struct snake* snake,int x,int y){ struct snake* head = calloc(1,sizeof(struct snake)); head->x = x; head->y = y; head->next = snake; return head; } struct snake* remove_snake(struct snake* snake){ struct snake* part = snake; if (snake == NULL) return NULL; if (part->next == NULL) { free(part); return NULL; } else { while(part->next->next != NULL) { part = part->next; } free(part->next); part->next = NULL; } return snake; } void free_snake(struct snake* sn){ struct snake* part = sn; if (part != NULL) { free_snake(part->next); free(part); } } int is_snake(struct snake* snake,int x,int y){ struct snake* part = snake; do { if ((part->x == x) && (part->y == y)) { return 1; } part = part->next; } while (part != NULL); return 0; } int step_state(struct state* st){ int nx = (st->snake->x + st->sx); int ny = (st->snake->y + st->sy); if (is_snake(st->snake, nx, ny)) { free_snake(st->snake); return END_SNAKE; } else { int food_eaten = 0; int remaining_food = 0; for (int i = 0; ifoodx[i] == -1) || (st->foody[i] == -1)) continue; if ((nx == st->foodx[i]) && (ny == st->foody[i])) { st->snake = add_snake(st->snake, nx, ny); food_eaten = 1; st->foodx[i] = -1; st->foody[i] = -1; } else remaining_food++; } if ((nx > 0) && (nx < st->width) && (ny > 0) && (ny < st->height)) { if ((!food_eaten)) { st->snake = add_snake(st->snake, nx, ny); st->snake = remove_snake(st->snake); } } else { free_snake(st->snake); return END_WALL; } if (remaining_food == 0) { free_snake(st->snake); return END_FOOD; } } return END_CONTINUE; }