pvjc25/du5/snake.c
2025-04-11 10:27:40 +02:00

105 lines
2.2 KiB
C

#include <stdlib.h>
#include "snake.h"
struct snake* add_snake(struct snake* snake, int x, int y){
struct snake* nova_cast = (struct snake*) calloc(1, sizeof(struct snake));
if (nova_cast == NULL){
return snake;
}
nova_cast->x = x;
nova_cast->y = y;
nova_cast->next = snake;
return nova_cast;
}
struct snake* remove_snake(struct snake* snake){
if (snake == NULL){
return NULL;
}
if (snake->next == NULL){
free(snake);
return NULL;
}
struct snake* predposledny = snake;
struct snake* posledny = snake->next;
while (posledny->next != NULL){
predposledny = posledny;
posledny = posledny->next;
}
free(posledny);
predposledny->next = NULL;
return snake;
}
int is_snake(struct snake* snake, int x, int y){
struct snake* aktualny = snake;
while (aktualny != NULL){
if (aktualny->x == x && aktualny->y == y){
return 1;
}
aktualny = aktualny->next;
}
return 0;
}
void free_snake(struct snake* sn){
struct snake* dalsi;
while (sn != NULL){
dalsi = sn->next;
free(sn);
sn = dalsi;
}
}
int step_state(struct state* state){
int nova_x = state->snake->x + state->sx;
int nova_y = state->snake->y + state->sy;
if (nova_x < 0 || nova_y < 0 || nova_x >= state->width || nova_y >= state->height){
return END_WALL;
}
if (is_snake(state->snake, nova_x, nova_y)){
return END_SNAKE;
}
for (int i = 0; i < FOOD_COUNT; i++){
if (state->foodx[i] == nova_x && state->foody[i] == nova_y){
state->snake = add_snake(state->snake, nova_x, nova_y);
state->foodx[i] = -1;
state->foody[i] = -1;
int jedlo_ostalo = 0;
for (int j = 0; j < FOOD_COUNT; j++){
if (state->foodx[j] != -1 && state->foody[j] != -1){
jedlo_ostalo = 1;
}
}
if (jedlo_ostalo == 0){
return END_FOOD;
}
return END_CONTINUE;
}
}
state->snake = add_snake(state->snake, nova_x, nova_y);
state->snake = remove_snake(state->snake);
return END_CONTINUE;
}