Aktualizovat du5/snake.c

This commit is contained in:
Denys Sanchuk 2025-04-08 12:38:08 +00:00
parent 5953bc57eb
commit 203181507e

View File

@ -1,48 +1,45 @@
#include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdbool.h>
#include "snake.h" #include "snake.h"
struct snake* add_snake(struct snake* snake, int x, int y) {
struct snake *add_snake(struct snake *snake, int x, int y) { struct snake* new_head = malloc(sizeof(struct snake));
struct snake *new_head = (struct snake *)malloc(sizeof(struct snake)); if (!new_head) return NULL;
if (!new_head) {
return NULL;
}
new_head->x = x; new_head->x = x;
new_head->y = y; new_head->y = y;
new_head->next = snake; new_head->next = snake;
return new_head; return new_head;
} }
struct snake *remove_snake(struct snake *snake) { struct snake* remove_snake(struct snake* snake) {
if (!snake) { if (!snake || !snake->next) {
return NULL; free(snake);
}
if (!snake->next) {
free(snake);
return NULL; return NULL;
} }
struct snake *current = snake; struct snake* current = snake;
while (current->next && current->next->next) { while (current->next->next) {
current = current->next; current = current->next;
} }
free(current->next);
free(current->next); current->next = NULL;
current->next = NULL;
return snake; return snake;
} }
int is_snake(struct snake *snake, int x, int y) { int is_snake(struct snake* snake, int x, int y) {
struct snake *current = snake; while (snake) {
while (current) { if (snake->x == x && snake->y == y)
if (current->x == x && current->y == y) { return 1;
return 1; snake = snake->next;
}
current = current->next;
} }
return 0; return 0;
} }
void free_snake(struct snake* sn) {
while (sn) {
struct snake* next = sn->next;
free(sn);
sn = next;
}
}