This commit is contained in:
Filip Chochol 2026-04-05 14:10:39 +02:00
parent 5a63b053bd
commit 5d9421f3b0

View File

@ -2,62 +2,73 @@
#include <stdlib.h> #include <stdlib.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* nova_cast = calloc(1, sizeof(struct snake));
nova_cast->x = x; struct snake* novy_uzol = calloc(1, sizeof(struct snake));
nova_cast->y = y;
nova_cast->next = snake; novy_uzol->x = x;
return nova_cast; novy_uzol->y = y;
novy_uzol->next = snake;
return novy_uzol;
} }
struct snake* remove_snake(struct snake* hlava) { struct snake* remove_snake(struct snake* hlava) {
if (hlava == NULL) return NULL; if (hlava == NULL) return NULL;
if (hlava->next == NULL) { if (hlava->next == NULL) {
free(hlava); free(hlava);
return NULL; return NULL;
} }
hlava->next = remove_snake(hlava->next); hlava->next = remove_snake(hlava->next);
return hlava; return hlava;
} }
int is_snake(struct snake* snake, int x, int y) { int is_snake(struct snake* snake, int x, int y) {
for (struct snake* this = snake; this != NULL; this = this->next) {
if (this->x == x && this->y == y) return 1; for (struct snake* clanok = snake; clanok != NULL; clanok = clanok->next) {
if (clanok->x == x && clanok->y == y) return 1;
} }
return 0; return 0;
} }
void free_snake(struct snake* sn) { void free_snake(struct snake* sn) {
if (sn == NULL) return; if (sn == NULL) return;
free_snake(sn->next); free_snake(sn->next);
free(sn); free(sn);
} }
int step_state(struct state* st) { int step_state(struct state* st) {
int nova_x = st->snake->x + st->sx;
int nova_y = st->snake->y + st->sy;
if (nova_x < 0 || nova_x >= st->width || nova_y < 0 || nova_y >= st->height) int next_x = st->snake->x + st->sx;
int next_y = st->snake->y + st->sy;
if (next_x < 0 || next_x >= st->width || next_y < 0 || next_y >= st->height)
return END_WALL; return END_WALL;
if (is_snake(st->snake, nova_x, nova_y)) if (is_snake(st->snake, next_x, next_y))
return END_SNAKE; return END_SNAKE;
for (int i = 0; i < FOOD_COUNT; i++) { for (int i = 0; i < FOOD_COUNT; i++) {
if (st->foodx[i] == nova_x && st->foody[i] == nova_y) {
if (st->foodx[i] == next_x && st->foody[i] == next_y) {
st->foodx[i] = -1; st->foodx[i] = -1;
st->foody[i] = -1; st->foody[i] = -1;
st->snake = add_snake(st->snake, nova_x, nova_y); st->snake = add_snake(st->snake, next_x, next_y);
int zostatok = 0; int zostava_jedlo = 0;
for (int j = 0; j < FOOD_COUNT; j++) { for (int j = 0; j < FOOD_COUNT; j++) {
if (st->foodx[j] >= 0) zostatok = 1; if (st->foodx[j] >= 0) zostava_jedlo = 1;
} }
if (!zostatok) return END_FOOD;
if (!zostava_jedlo) return END_FOOD;
return END_CONTINUE; return END_CONTINUE;
} }
} }
st->snake = add_snake(st->snake, nova_x, nova_y); st->snake = add_snake(st->snake, next_x, next_y);
st->snake = remove_snake(st->snake); st->snake = remove_snake(st->snake);
return END_CONTINUE; return END_CONTINUE;
} }