#include #include "snake.h" struct snake* add_snake(struct snake* snake, int x, int y) { struct snake* new_part = (struct snake*)malloc(sizeof(struct snake)); if (new_part == NULL) { return snake; } new_part->x = x; new_part->y = y; new_part->next = snake; return new_part; } struct snake* remove_snake(struct snake* snake) { if (snake == NULL) { return NULL; } if (snake->next == NULL) { free(snake); return NULL; } struct snake* current = snake; while (current->next->next != NULL) { current = current->next; } free(current->next); current->next = NULL; return snake; } int is_snake(struct snake* snake, int x, int y) { struct snake* current = snake; while (current != NULL) { if (current->x == x && current->y == y) { return 1; } current = current->next; } return 0; } void free_snake(struct snake* sn) { while (sn != NULL) { struct snake* temp = sn; sn = sn->next; free(temp); } } int step_state(struct state* state) { if (state == NULL || state->snake == NULL) { return END_USER; } int new_x = state->snake->x + state->sx; int new_y = state->snake->y + state->sy; if (new_x < 0 || new_x >= state->width || new_y < 0 || new_y >= state->height) { return END_WALL; } int food_index = -1; int items_left = 0; for (int i = 0; i < FOOD_COUNT; i++) { if (state->foodx[i] == new_x && state->foody[i] == new_y) { food_index = i; } else if (state->foodx[i] >= 0 && state->foody[i] >= 0) { items_left++; } } if (food_index >= 0) { state->foodx[food_index] = -1; state->foody[food_index] = -1; if (is_snake(state->snake, new_x, new_y)) { state->snake = add_snake(state->snake, new_x, new_y); return END_SNAKE; } state->snake = add_snake(state->snake, new_x, new_y); if (items_left == 0) { return END_FOOD; } return END_CONTINUE; } else { state->snake = remove_snake(state->snake); if (is_snake(state->snake, new_x, new_y)) { state->snake = add_snake(state->snake, new_x, new_y); return END_SNAKE; } state->snake = add_snake(state->snake, new_x, new_y); return END_CONTINUE; } }