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