From ce4506119d0f009e09b1a340301ff672fdc99838 Mon Sep 17 00:00:00 2001 From: Roman Khaliavka Date: Wed, 23 Apr 2025 14:15:14 +0000 Subject: [PATCH] a3 --- a3/snake.c | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 a3/snake.c diff --git a/a3/snake.c b/a3/snake.c new file mode 100644 index 0000000..c90ec0e --- /dev/null +++ b/a3/snake.c @@ -0,0 +1,76 @@ +#include "snake.h" +#include + +// Pridá nový diel hada na začiatok (hlavu) +struct snake* add_snake(struct snake* snake, int x, int y){ + struct snake* new_head = malloc(sizeof(struct snake)); + if(!new_head){ + return NULL; + } + new_head->x = x; + new_head->y = y; + new_head->next = snake; + return new_head; +} + +// Odstráni posledný diel hada (chvost) +struct snake* remove_snake(struct snake* snake){ + if(!snake || !snake->next){ + free(snake); + return NULL; + } + + struct snake* current = snake; + while (current->next && current->next->next){ + current = current->next; + } + free(current->next); + current->next = NULL; + return snake; +} + +// Zistí, či sa na daných súradniciach nachádza časť hada +int is_snake(struct snake* snake, int x, int y){ + while(snake){ + if(snake->x == x && snake->y == y){ + return 1; + } + snake = snake->next; + } + return 0; +} + +// Uvoľní pamäť všetkých častí hada +void free_snake(struct snake* sn){ + while(sn){ + struct snake* next = sn->next; + free(sn); + sn = next; + } +} + + // Spraví jeden krok hry – aktualizuje stav podľa pohybu +int step_state(struct state* state){ + int newx = state->snake->x + state->sx; + int newy = state->snake->y + state->sy; + + if(newx < 0 || newx >= state->width || newy < 0 || newy >= state->height) + return END_WALL; + + if(is_snake(state->snake, newx, newy)) + return END_SNAKE; + + for(int i = 0; i < FOOD_COUNT; i++){ + if(state->foodx[i] == newx && state->foody[i] == newy){ + state->foodx[i] = -1; + state->foody[i] = -1; + state->snake = add_snake(state->snake, newx, newy); + place_food(state); + return END_CONTINUE; + } + } + + state->snake = add_snake(state->snake, newx, newy); + state->snake = remove_snake(state->snake); + return END_CONTINUE; +}