#include #include "grid.h" #include "snake.h" Snake *new_snake(void) { Snake *snake = (Snake *)malloc(sizeof(Snake)); if (snake == NULL) { fprintf(stderr, "Memory allocation failed\n"); exit(EXIT_FAILURE); } snake->size = 0; snake->segments_list = NULL; snake->dir = RIGHT; return snake; } void add_segment(Snake *snake, int x, int y) { Position *new_segment = (Position *)malloc(sizeof(Position)); if (new_segment == NULL) { fprintf(stderr, "Memory allocation failed\n"); exit(EXIT_FAILURE); } new_segment->x = x; new_segment->y = y; new_segment->next = NULL; if (snake->segments_list == NULL) { snake->segments_list = new_segment; } else { Position *current = snake->segments_list; while (current->next != NULL) { current = current->next; } current->next = new_segment; } snake->size++; } void free_snake(Snake *snake) { Position *current = snake->segments_list; while (current != NULL) { Position *next = current->next; free(current); current = next; } free(snake); } void debug_snake(Snake *snake) { Position *current = snake->segments_list; printf("Snake segments:\n"); while (current != NULL) { printf(" (%d, %d)\n", current->x, current->y); current = current->next; } printf("Snake size: %d\n", snake->size); } void crawl(Snake *snake, struct GridStruct *g) { Position *new_head = (Position *)malloc(sizeof(Position)); Position *current; if (new_head == NULL) { fprintf(stderr, "Memory allocation failed\n"); exit(EXIT_FAILURE); } new_head->x = snake->segments_list->x; new_head->y = snake->segments_list->y; switch (snake->dir) { case LEFT: new_head->x = (new_head->x - 1 + g->nbc) % g->nbc; break; case RIGHT: new_head->x = (new_head->x + 1) % g->nbc; break; case TOP: new_head->y = (new_head->y - 1 + g->nbl) % g->nbl; break; case BOTTOM: new_head->y = (new_head->y + 1) % g->nbl; break; } new_head->next = snake->segments_list; snake->segments_list = new_head; current = snake->segments_list; while (current->next != NULL && current->next->next != NULL) { current = current->next; } free(current->next); current->next = NULL; } Direction determine_initial_direction(struct GridStruct *g, Position *head) { int x = head->x; int y = head->y; printf("Determining initial direction from position (%d, %d)\n", x, y); if (x + 1 < g->nbc && g->grid[y][x + 1] != WALL && g->grid[y][x + 1] != SNAKE) { printf("Direction: RIGHT\n"); return RIGHT; } if (y + 1 < g->nbl && g->grid[y + 1][x] != WALL && g->grid[y + 1][x] != SNAKE) { printf("Direction: BOTTOM\n"); return BOTTOM; } if (x - 1 >= 0 && g->grid[y][x - 1] != WALL && g->grid[y][x - 1] != SNAKE) { printf("Direction: LEFT\n"); return LEFT; } if (y - 1 >= 0 && g->grid[y - 1][x] != WALL && g->grid[y - 1][x] != SNAKE) { printf("Direction: TOP\n"); return TOP; } printf("Default direction: BOTTOM\n"); return BOTTOM; }