From c4a07b8879878b87f71b065f2df4bb1baa841582 Mon Sep 17 00:00:00 2001 From: Denis Landa Date: Fri, 11 Apr 2025 10:20:30 +0200 Subject: [PATCH] 12 --- du5/snake.c | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 du5/snake.c diff --git a/du5/snake.c b/du5/snake.c new file mode 100644 index 0000000..a725652 --- /dev/null +++ b/du5/snake.c @@ -0,0 +1,104 @@ +#include +#include "snake.h" + +struct snake* add_snake(struct snake* snake, int x, int y){ + struct snake* nova_cast = (struct snake*) calloc(1, sizeof(struct snake)); + if (nova_cast == NULL){ + return snake; + } + + nova_cast->x = x; + nova_cast->y = y; + nova_cast->next = snake; + + return nova_cast; +} + +struct snake* remove_snake(struct snake* snake){ + if (snake == NULL){ + return NULL; + } + + if (snake->next == NULL){ + free(snake); + return NULL; + } + + struct snake* predposledny = snake; + struct snake* posledny = snake->next; + + while (posledny->next != NULL){ + predposledny = posledny; + posledny = posledny->next; + } + + free(posledny); + predposledny->next = NULL; + + return snake; +} + + +int is_snake(struct snake* snake, int x, int y){ + struct snake* aktualny = snake; + + while (aktualny != NULL){ + if (aktualny->x == x && aktualny->y == y){ + return 1; + } + + aktualny = aktualny->next; + } + + return 0; +} + +void free_snake(struct snake* sn){ + struct snake* dalsi; + + while (sn != NULL){ + dalsi = sn->next; + free(sn); + sn = dalsi; + } +} + +int step_state(struct state* state){ + int nova_pozicia_x = state->snake->x + state->sx; + int nova_pozicia_y = state->snake->y + state->sy; + + if (nova_pozicia_x < 0 || nova_pozicia_y < 0 || nova_pozicia_x >= state->width || nova_pozicia_y >= state->height){ + return END_WALL; + } + + if (is_snake(state->snake, nova_pozicia_x, nova_pozicia_y)){ + return END_SNAKE; + } + + for (int i = 0; i < FOOD_COUNT; i++){ + if (state->foodx[i] == nova_pozicia_x && state->foody[i] == nova_pozicia_y){ + state->snake = add_snake(state->snake, nova_pozicia_x, nova_pozicia_y); + state->foodx[i] = -1; + state->foody[i] = -1; + + int este_jedlo = 0; + for (int j = 0; j < FOOD_COUNT; j++){ + if (state->foodx[j] != -1 && state->foody[j] != -1){ + este_jedlo = 1; + } + } + + if (este_jedlo == 0){ + return END_FOOD; + } + + return END_CONTINUE; + } + } + + state->snake = add_snake(state->snake, nova_pozicia_x, nova_pozicia_y); + state->snake = remove_snake(state->snake); + + return END_CONTINUE; +} +