From 3720a2eb68bac3a85123cc6aa2eab299943d9c0d Mon Sep 17 00:00:00 2001 From: st529yr Date: Mon, 8 Apr 2024 15:14:43 +0200 Subject: [PATCH] funguje --- cv9/snake.c | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 cv9/snake.c diff --git a/cv9/snake.c b/cv9/snake.c new file mode 100644 index 0000000..7f19c5c --- /dev/null +++ b/cv9/snake.c @@ -0,0 +1,66 @@ +```c +#include "snake.h" +#include + +struct snake* add_snake(struct snake* snake, int x, int y) { + // Allocate memory for the new snake part + struct snake* new_part = (struct snake*)malloc(sizeof(struct snake)); + if (new_part == NULL) { + return NULL; // Memory allocation failed + } + + // Set the coordinates of the new part + new_part->x = x; + new_part->y = y; + + // Set the next pointer of the new part to the current head of the snake + new_part->next = snake; + + // Return the new head of the snake + return new_part; +} + +struct snake* remove_snake(struct snake* snake) { + // Check if the snake is empty + if (snake == NULL) { + return NULL; // Snake is empty, no part to remove + } + + // Save the next part of the snake + struct snake* next_part = snake->next; + + // Free the current head of the snake + free(snake); + + // Return the new head of the snake + return next_part; +} + +int is_snake(struct snake* snake, int x, int y) { + // Traverse the snake + while (snake != NULL) { + // Check if the coordinates match + if (snake->x == x && snake->y == y) { + return 1; // Coordinates are part of the snake + } + // Move to the next part of the snake + snake = snake->next; + } + // Coordinates are not part of the snake + return 0; +} + +void free_snake(struct snake* sn) { + // Traverse the snake + while (sn != NULL) { + // Save the next part of the snake + struct snake* next_part = sn->next; + + // Free the current part of the snake + free(sn); + + // Move to the next part of the snake + sn = next_part; + } +} +