From e4277701506cbbcf133c0bb744078f7db79d1f39 Mon Sep 17 00:00:00 2001 From: Illia Korpan Date: Wed, 15 Apr 2026 08:48:27 +0200 Subject: [PATCH] 123 --- du4/snake.c | 101 ++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 95 insertions(+), 6 deletions(-) diff --git a/du4/snake.c b/du4/snake.c index 7038cdb..e8052cd 100644 --- a/du4/snake.c +++ b/du4/snake.c @@ -1,23 +1,112 @@ #include "snake.h" #include -struct snake* add_snake(struct snake* snake,int x,int y){ - return NULL; +struct snake* add_snake(struct snake* snake, int x, int y){ + struct snake* new_head = (struct snake*)malloc(sizeof(struct snake)); + if (new_head == NULL) { + return snake; + } + new_head->x = x; + new_head->y = y; + new_head->next = snake; + return new_head; } struct snake* remove_snake(struct snake* snake){ - return NULL; + 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; + + return snake; } void free_snake(struct snake* sn){ + while (sn != NULL) { + struct snake* temp = sn; + sn = sn->next; + free(temp); + } } -int is_snake(struct snake* snake,int x,int y){ +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; } int step_state(struct state* st){ - int nx = (st->snake->x + st->sx); + 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) { + return END_SNAKE; + } + 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) { + food_index = i; + break; + } + } + + 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) { + food_left = 1; + break; + } + } + + if (!food_left) { + return END_FOOD; + } + 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); + return END_CONTINUE; -} +} \ No newline at end of file