From b2c01620ed6142f3084e53a1b4cfc488dff1b2a4 Mon Sep 17 00:00:00 2001 From: Filip Chochol Date: Tue, 31 Mar 2026 14:31:00 +0200 Subject: [PATCH] push --- du4/snake.c | 71 ++++++++++++++++++++++------------------------------- 1 file changed, 30 insertions(+), 41 deletions(-) diff --git a/du4/snake.c b/du4/snake.c index 4d6cac1..2bbacb8 100644 --- a/du4/snake.c +++ b/du4/snake.c @@ -2,71 +2,60 @@ #include struct snake* add_snake(struct snake* snake, int x, int y) { - struct snake* nova_hlava = malloc(sizeof(struct snake)); - nova_hlava->x = x; - nova_hlava->y = y; - nova_hlava->next = snake; - return nova_hlava; -} - -struct snake* remove_snake(struct snake* snake) { - if (snake == NULL) return NULL; - if (snake->next == NULL) { - free(snake); - return NULL; - } - struct snake* aktualny = snake; - while (aktualny->next->next != NULL) { - aktualny = aktualny->next; - } - free(aktualny->next); - aktualny->next = NULL; + struct snake* nova_cast = calloc(1, sizeof(struct snake)); + nova_cast->x = x; + nova_cast->y = y; + nova_cast->next = snake; return snake; } -void free_snake(struct snake* sn) { - while (sn != NULL) { - struct snake* dalsi = sn->next; - free(sn); - sn = dalsi; +struct snake* remove_snake(struct snake* hlava) { + if (hlava == NULL) return NULL; + if (hlava->next == NULL) { + return NULL; } + hlava->next = remove_snake(hlava->next); + return hlava; } 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; + for (struct snake* this = snake; this != NULL; this = this->next) { + if (this->x = x && this->y == y) return 1; } return 0; } +void free_snake(struct snake* sn) { + if (sn == NULL) return; + free_snake(sn->next); +} + int step_state(struct state* st) { - int nx = (st->snake->x + st->sx); - int ny = (st->snake->y + st->sy); + int nova_x = st->snake->x + st->sx; + int nova_y = st->snake->y + st->sy; - if (nx < 0 || nx >= st->width || - ny < 0 || ny >= st->height) { + if (nova_x < 0 || nova_x >= st->width || nova_y < 0 || nova_y >= st->height) return END_WALL; - } - if (is_snake(st->snake, nx, ny)) { + if (is_snake(st->snake, nova_x, nova_y)) return END_SNAKE; - } for (int i = 0; i < FOOD_COUNT; i++) { - if (st->foodx[i] == nx && st->foody[i] == ny) { - st->snake = add_snake(st->snake, nx, ny); + if (st->foodx[i] == nova_x && st->foody[i] == nova_y) { st->foodx[i] = -1; st->foody[i] = -1; + st->snake = add_snake(st->snake, nova_x, nova_y); + + int zostatok = 0; for (int j = 0; j < FOOD_COUNT; j++) { - if (st->foodx[j] >= 0) return END_CONTINUE; + if (st->foodx[j] >= 0) zostatok = 1; } - return END_FOOD; + if (!zostatok) return END_FOOD; + return END_CONTINUE; } } - st->snake = add_snake(st->snake, nx, ny); - st->snake = remove_snake(st->snake); + st->snake = add_snake(st->snake, nova_x, nova_y); + remove_snake(st->snake); return END_CONTINUE; }