96 lines
2.0 KiB
C
96 lines
2.0 KiB
C
#include <stdlib.h>
|
|
#include "snake.h"
|
|
|
|
// pridanie na zaciatok
|
|
struct snake* add_snake(struct snake* snake, int x, int y) {
|
|
struct snake* head = calloc(1, sizeof(struct snake));
|
|
head->x = x;
|
|
head->y = y;
|
|
head->next = snake;
|
|
return head;
|
|
}
|
|
// odstranenie posledneho
|
|
struct snake* remove_snake(struct snake* snake) {
|
|
if (snake == NULL) return NULL;
|
|
|
|
if (snake->next == NULL) {
|
|
free(snake);
|
|
return NULL;
|
|
}
|
|
|
|
struct snake* snak = snake;
|
|
|
|
while (snak->next->next != NULL) {
|
|
snak = snak->next;
|
|
}
|
|
|
|
free(snak->next);
|
|
snak->next = NULL;
|
|
|
|
return snake;
|
|
}
|
|
|
|
// kontrola ci bod je v hadovi
|
|
int is_snake(struct snake* snake, int x, int y) {
|
|
struct snake* snak = snake;
|
|
|
|
while (snak != NULL) {
|
|
if (snak->x == x && snak->y == y) return 1;
|
|
snak = snak->next;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
// uvolnenie celeho hada
|
|
void free_snake(struct snake* sn) {
|
|
struct snake* snak = sn;
|
|
|
|
while (snak != NULL) {
|
|
struct snake* next = snak->next;
|
|
free(snak);
|
|
snak = next;
|
|
}
|
|
}
|
|
|
|
// krok hry
|
|
int step_state(struct state* state) {
|
|
int nx = state->snake->x + state->sx;
|
|
int ny = state->snake->y + state->sy;
|
|
|
|
// stena
|
|
if (nx < 0 || ny < 0 || nx >= state->width || ny >= state->height) {
|
|
return END_WALL;
|
|
}
|
|
|
|
// had
|
|
if (is_snake(state->snake, nx, ny)) {
|
|
return END_SNAKE;
|
|
}
|
|
|
|
// jedlo
|
|
for (int i = 0; i < FOOD_COUNT; i++) {
|
|
if (state->foodx[i] == nx && state->foody[i] == ny) {
|
|
|
|
state->foodx[i] = -1;
|
|
state->foody[i] = -1;
|
|
|
|
state->snake = add_snake(state->snake, nx, ny);
|
|
|
|
int je_jedlo = 0;
|
|
for (int j = 0; j < FOOD_COUNT; j++) {
|
|
if (state->foodx[j] >= 0) je_jedlo = 1;
|
|
}
|
|
|
|
if (!je_jedlo) return END_FOOD;
|
|
|
|
return END_CONTINUE;
|
|
}
|
|
}
|
|
|
|
// normalny pohyb
|
|
state->snake = add_snake(state->snake, nx, ny);
|
|
state->snake = remove_snake(state->snake);
|
|
|
|
return END_CONTINUE;
|
|
} |