pvjc26/du4/snake.c
2026-04-17 00:48:56 +02:00

87 lines
2.0 KiB
C

#include "snake.h"
#include <stdlib.h>
struct snake* add_snake(struct snake* snake, int x, int y) {
struct snake* head = calloc(1, sizeof(struct snake));
if (head == NULL) {
return snake;
}
head->x = x;
head->y = y;
head->next = snake;
return head;
}
struct snake* remove_snake(struct snake* snake) {
if (snake == NULL) {
return NULL;
}
if (snake->next == NULL) {
free(snake);
return NULL;
}
struct snake* prev = snake;
struct snake* last = snake->next;
while (last->next != NULL) {
prev = last;
last = last->next;
}
prev->next = NULL;
free(last);
return snake;
}
void free_snake(struct snake* sn) {
while (sn != NULL) {
struct snake* next = sn->next;
free(sn);
sn = next;
}
}
int is_snake(struct snake* snake, int x, int y) {
for (struct snake* node = snake; node != NULL; node = node->next) {
if (node->x == x && node->y == y) {
return 1;
}
}
return 0;
}
int step_state(struct state* st) {
if (st == NULL || st->snake == NULL) {
return END_USER;
}
int nx = st->snake->x + st->sx;
int ny = st->snake->y + st->sy;
int food_index = -1;
if (nx < 0 || ny < 0 || nx >= st->width || ny >= st->height) {
return END_WALL;
}
if (is_snake(st->snake, nx, ny)) {
return END_SNAKE;
}
for (int i = 0; i < FOOD_COUNT; i++) {
if (st->foodx[i] == nx && st->foody[i] == ny) {
food_index = i;
break;
}
}
st->snake = add_snake(st->snake, nx, ny);
if (food_index >= 0) {
st->foodx[food_index] = -1;
st->foody[food_index] = -1;
for (int i = 0; i < FOOD_COUNT; i++) {
if (st->foodx[i] >= 0 && st->foody[i] >= 0) {
return END_CONTINUE;
}
}
return END_FOOD;
}
st->snake = remove_snake(st->snake);
return END_CONTINUE;
}