From d4d57c03445ac0f79f5e0e563859ce5bfc6f5b10 Mon Sep 17 00:00:00 2001 From: Rudolf Zambory Date: Wed, 9 Apr 2025 11:12:51 +0200 Subject: [PATCH] sssssssss --- du5/snake.c | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 du5/snake.c diff --git a/du5/snake.c b/du5/snake.c new file mode 100644 index 0000000..b3d08d5 --- /dev/null +++ b/du5/snake.c @@ -0,0 +1,81 @@ +#include +#include "snake.h" + +struct snake* add_snake(struct snake* head, int x, int y) { + struct snake* new_head = (struct snake*)calloc(1, sizeof(struct snake)); + new_head->x = x; + new_head->y = y; + new_head->next = head; + return new_head; +} + +struct snake* remove_snake(struct snake* head) { + if (head == NULL) return NULL; + + struct snake* current = head; + struct snake* previous = NULL; + + while (current->next != NULL) { + previous = current; + current = current->next; + } + + free(current); + if (previous != NULL) { + previous->next = NULL; + } else { + return NULL; + } + return head; +} + +int is_snake(struct snake* head, int x, int y) { + struct snake* current = head; + while (current != NULL) { + if (current->x == x && current->y == y) { + return 1; + } + current = current->next; + } + return 0; +} + +void free_snake(struct snake* head) { + struct snake* current = head; + while (current != NULL) { + struct snake* next = current->next; + free(current); + current = next; + } +} + +int step_state(struct state* state) { + int new_x = state->snake->x + state->sx; + int new_y = state->snake->y + state->sy; + + if (new_x < 0 || new_x >= state->width || new_y < 0 || new_y >= state->height) { + return END_WALL; + } + + if (is_snake(state->snake, new_x, new_y)) { + return END_SNAKE; + } + + for (int i = 0; i < FOOD_COUNT; i++) { + if (state->foodx[i] == new_x && state->foody[i] == new_y) { + state->foodx[i] = -1; + state->foody[i] = -1; + state->snake = add_snake(state->snake, new_x, new_y); + for (int j = 0; j < FOOD_COUNT; j++) { + if (state->foodx[j] != -1) { + return END_CONTINUE; + } + } + return END_FOOD; + } + } + + state->snake = add_snake(state->snake, new_x, new_y); + state->snake = remove_snake(state->snake); + return END_CONTINUE; +}