pvjc24/cv9/snake.c

67 lines
1.8 KiB
C
Raw Permalink Normal View History

2024-04-08 13:26:13 +00:00
#include "snake.h"
#include <stddef.h>
#include <stdlib.h>
struct snake* add_snake(struct snake* snake,int x,int y) {
// Allocate memory for the new snake part
struct snake* new_snake_part = calloc(1, sizeof(struct snake));
if (new_snake_part == NULL) {
return NULL; // Memory allocation failed
}
// Set coordinates of the new snake part
new_snake_part->x = x;
new_snake_part->y = y;
// The new snake part becomes the head of the snake
new_snake_part->next = snake;
return new_snake_part;
}
2024-04-08 13:14:43 +00:00
struct snake* remove_snake(struct snake* snake) {
if (snake == NULL) {
2024-04-08 13:16:50 +00:00
return NULL;
2024-04-08 13:14:43 +00:00
}
2024-04-08 13:23:28 +00:00
struct snake* current = snake;
struct snake* prev = NULL;
while (current->next != NULL) {
prev = current;
current = current->next;
2024-04-08 13:14:43 +00:00
}
2024-04-08 13:23:28 +00:00
if (prev != NULL) {
prev->next = NULL;
} else {
// If prev is NULL, it means we are removing the head of the list
// and the new head will be the next node
snake = NULL;
2024-04-08 13:14:43 +00:00
}
2024-04-08 13:23:28 +00:00
free(current);
return snake;
2024-04-08 13:16:50 +00:00
}
2024-04-08 13:26:13 +00:00
int is_snake(struct snake* snake,int x, int y) {
// Traverse the snake linked list
struct snake* current = snake;
while (current != NULL) {
// Check if current snake part has the given coordinates
if (current->x == x && current->y == y) {
return 1; // Coordinates found in the snake
}
current = current->next;
}
return 0; // Coordinates not found in the snake
}
void free_snake(struct snake* sn) {
struct snake* current = sn;
while (current != NULL) {
struct snake* next = current->next;
free(current);
current = next;
}
}
int step_state(struct state* state) {
// Implementation of this function is left to you
return END_CONTINUE;
}