From 5ec0f07e6fcac1a88144c835673cbc1f4d7dbb73 Mon Sep 17 00:00:00 2001 From: Anzhelika Nikolaieva Date: Thu, 13 Apr 2023 13:50:39 +0000 Subject: [PATCH] Update 'du7/snake.c' --- du7/snake.c | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/du7/snake.c b/du7/snake.c index 7038cdb..7535d1a 100644 --- a/du7/snake.c +++ b/du7/snake.c @@ -2,22 +2,103 @@ #include struct snake* add_snake(struct snake* snake,int x,int y){ - return NULL; + struct snake* new_head = (struct snake*) malloc(sizeof(struct 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; + } + + struct snake* current = snake; + struct snake* p = NULL; + + while (current->next != NULL) { + p = current; + current = current->next; + } + + free(current); + + if (p == NULL) { + return NULL; + } + + p->next = NULL; + return snake; } + void free_snake(struct snake* sn){ + struct snake* current = snake; + while (current != NULL) { + struct snake* next = current->next; + free(current); + current = next; + } } + 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 ny = (st->snake->y + st->sy); + if (new_head_x < 0 || new_head_x >= state->width || new_head_y < 0 || new_head_y >= state->height) { + return END_WALL; + } + + // Check if snake hit itself + if (is_snake(state->snake, new_head_x, new_head_y)) { + return END_SNAKE; + } + + // Check if snake ate food + int food_eaten = 0; + for (int i = 0; i < FOOD_COUNT; i++) { + if (state->foodx[i] >= 0 && state->foodx[i] == new_head_x && state->foody[i] == new_head_y) { + state->foodx[i] = -1; + state->foody[i] = -1; + state->snake = add_snake(state->snake, new_head_x, new_head_y); + food_eaten = 1; + break; + } + } + + // Check if game ended + if (!food_eaten) { + int food_left = 0; + for (int i = 0; i < FOOD_COUNT; i++) { + if (state->foodx[i] >= 0) { + food_left = 1; + break; + } + } + if (!food_left) { + return END_FOOD; + } + // Remove the last snake part + state->snake = remove_snake(state->snake); + // Add new snake part + state->snake = add_snake(state->snake, new_head_x, new_head_y); + } + return END_CONTINUE; } +