This commit is contained in:
Jana Kapalková 2026-04-17 00:48:56 +02:00
parent 9a31fd09f8
commit 64578a9e8c

View File

@ -1,14 +1,6 @@
#include "snake.h"
#include <stdlib.h>
static struct snake* get_tail(struct snake* snake) {
struct snake* tail = snake;
while (tail != NULL && tail->next != NULL) {
tail = tail->next;
}
return tail;
}
struct snake* add_snake(struct snake* snake, int x, int y) {
struct snake* head = calloc(1, sizeof(struct snake));
if (head == NULL) {
@ -57,25 +49,38 @@ int is_snake(struct snake* snake, int x, int y) {
}
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 ate_food = nx == st->foodx && ny == st->foody;
struct snake* tail = get_tail(st->snake);
int food_index = -1;
if (nx < 0 || ny < 0 || nx >= st->width || ny >= st->height) {
return END_SNAKE;
return END_WALL;
}
if (is_snake(st->snake, nx, ny)) {
if (ate_food || tail == NULL || tail->x != nx || tail->y != ny) {
return END_GAME;
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 (st->snake == NULL) {
return END_GAME;
}
if (!ate_food) {
st->snake = remove_snake(st->snake);
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;
}
}