pvjc24/a2/snake.c

56 lines
1.6 KiB
C
Raw Normal View History

2024-04-24 18:31:18 +00:00
#include "snake.h"
2024-04-18 13:46:41 +00:00
#include <stdlib.h>
2024-04-18 13:43:15 +00:00
2024-04-24 18:31:18 +00:00
// 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;
2024-04-18 15:07:21 +00:00
}
}
}
int step_state(struct state* state) {
2024-04-24 18:31:18 +00:00
// Vypočíta novú pozíciu hlavy hada
int new_x = state->snake->x + state->sx;
int new_y = state->snake->y + state->sy;
2024-04-18 15:07:21 +00:00
2024-04-24 18:31:18 +00:00
// 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;
2024-04-18 15:07:21 +00:00
}
2024-04-24 18:31:18 +00:00
// Overí, či je nová pozícia na tele hada
if (is_snake(state->snake, new_x, new_y)) {
return END_SNAKE;
2024-04-18 15:07:21 +00:00
}
2024-04-24 18:31:18 +00:00
// Overí, či je na novej pozícii odmena
2024-04-18 15:07:21 +00:00
for (int i = 0; i < FOOD_COUNT; i++) {
2024-04-24 18:31:18 +00:00
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;
2024-04-18 15:07:21 +00:00
}
}
}
2024-04-24 18:31:18 +00:00
// Odstráni poslednú časť hada
state->snake = add_snake(state->snake, new_x, new_y);
state->snake = remove_snake(state->snake);
2024-04-11 12:06:05 +00:00
2024-04-24 18:31:18 +00:00
return END_CONTINUE;
2024-04-18 13:46:41 +00:00
}