pvjc24/a2/snake.c
2024-04-24 20:31:18 +02:00

56 lines
1.6 KiB
C

#include "snake.h"
#include <stdlib.h>
// Pridá novú odmenu na náhodnú voľnú pozíciu v rámci hracej plochy
void add_food(struct state* state) {
int placed = 0;
while (!placed) {
int x = rand() % state->width;
int y = rand() % state->height;
if (!is_snake(state->snake, x, y)) {
state->foodx[state->foods] = x;
state->foody[state->foods] = y;
state->foods++;
placed = 1;
}
}
}
int step_state(struct state* state) {
// Vypočíta novú pozíciu hlavy hada
int new_x = state->snake->x + state->sx;
int new_y = state->snake->y + state->sy;
// Overí, či je nová pozícia mimo hracej plochy
if (new_x < 0 || new_x >= state->width || new_y < 0 || new_y >= state->height) {
return END_WALL;
}
// Overí, či je nová pozícia na tele hada
if (is_snake(state->snake, new_x, new_y)) {
return END_SNAKE;
}
// Overí, či je na novej pozícii odmena
for (int i = 0; i < FOOD_COUNT; i++) {
if (state->foodx[i] == new_x && state->foody[i] == new_y) {
state->foodx[i] = -1;
state->foody[i] = -1;
state->foods_eaten++;
add_food(state); // Pridá novú odmenu
state->snake = add_snake(state->snake, new_x, new_y);
if (state->foods_eaten == FOOD_COUNT) {
return END_FOOD;
} else {
return END_CONTINUE;
}
}
}
// Odstráni poslednú časť hada
state->snake = add_snake(state->snake, new_x, new_y);
state->snake = remove_snake(state->snake);
return END_CONTINUE;
}