67 lines
1.8 KiB
C
67 lines
1.8 KiB
C
#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;
|
|
}
|
|
|
|
struct snake* remove_snake(struct snake* snake) {
|
|
if (snake == NULL) {
|
|
return NULL;
|
|
}
|
|
struct snake* current = snake;
|
|
struct snake* prev = NULL;
|
|
while (current->next != NULL) {
|
|
prev = current;
|
|
current = current->next;
|
|
}
|
|
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;
|
|
}
|
|
free(current);
|
|
return snake;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|