diff --git a/du4/snake.c b/du4/snake.c index e8052cd..c222da8 100644 --- a/du4/snake.c +++ b/du4/snake.c @@ -16,20 +16,17 @@ struct snake* remove_snake(struct snake* snake){ if (snake == NULL) { return NULL; } - - // If snake has only one part + if (snake->next == NULL) { free(snake); return NULL; } - - // Find the second-to-last part + struct snake* current = snake; while (current->next->next != NULL) { current = current->next; } - // Free the last part free(current->next); current->next = NULL; @@ -58,13 +55,10 @@ int is_snake(struct snake* snake, int x, int y){ int step_state(struct state* st){ int nx = (st->snake->x + st->sx); int ny = (st->snake->y + st->sy); - - // Check if new position is on the wall if (nx < 0 || nx >= st->width || ny < 0 || ny >= st->height) { return END_WALL; } - // Check if new position is on the snake (excluding the head) struct snake* current = st->snake->next; while (current != NULL) { if (current->x == nx && current->y == ny) { @@ -73,7 +67,6 @@ int step_state(struct state* st){ current = current->next; } - // Check if new position is on food int food_index = -1; for (int i = 0; i < FOOD_COUNT; i++) { if (st->foodx[i] == nx && st->foody[i] == ny) { @@ -83,13 +76,10 @@ int step_state(struct state* st){ } if (food_index != -1) { - // Mark food as eaten st->foodx[food_index] = -1; st->foody[food_index] = -1; - // Add new snake part at food position st->snake = add_snake(st->snake, nx, ny); - // Check if there is any food left int food_left = 0; for (int i = 0; i < FOOD_COUNT; i++) { if (st->foodx[i] >= 0) { @@ -104,7 +94,6 @@ int step_state(struct state* st){ return END_CONTINUE; } - // Normal move: add new head and remove tail st->snake = add_snake(st->snake, nx, ny); st->snake = remove_snake(st->snake);