diff --git a/a2/snake.c b/a2/snake.c index 0da9cca..3aa2987 100644 --- a/a2/snake.c +++ b/a2/snake.c @@ -1,57 +1,48 @@ -struct snake* add_snake(struct snake* old_head, int x, int y) { - struct snake* new_head = (struct snake*) malloc(sizeof(struct snake)); - new_head->x = x; - new_head->y = y; - new_head->next = old_head; - return new_head; +#include +#include + +// Inicializuje stav hry +void init_state(struct state* state, int width, int height) { + state->width = width; + state->height = height; + state->snake = add_snake(NULL, width / 2, height / 2); + state->sx = 0; + state->sy = 1; + for(int i = 0; i < FOOD_COUNT; i++) { + state->foodx[i] = rand() % width; + state->foody[i] = rand() % height; + } } -int is_snake(struct snake* snake, int x, int y) { - while (snake != NULL) { - if (snake->x == x && snake->y == y) { - return 1; +// Generuje nové jedlo na náhodnej pozícii +void generate_food(struct state* state) { + for(int i = 0; i < FOOD_COUNT; i++) { + if(state->foodx[i] == -1) { + state->foodx[i] = rand() % state->width; + state->foody[i] = rand() % state->height; } - snake = snake->next; } +} + +// Hlavná slučka hry +void game_loop(struct state* state) { + while(1) { + int result = step_state(state); + if(result == END_WALL || result == END_SNAKE) { + break; + } + if(result == END_FOOD) { + generate_food(state); + } + // TODO: Pridajte kód pre vykreslenie hry a spracovanie vstupu od hráča + } +} + +int main() { + srand(time(NULL)); + struct state state; + init_state(&state, 20, 20); + game_loop(&state); + free_snake(state.snake); return 0; } - -void free_snake(struct snake* snake) { - while (snake != NULL) { - struct snake* next = snake->next; - free(snake); - snake = next; - } -} - -int step_state(struct state* state) { - int new_x = state->snake->x + state->sx; - int new_y = state->snake->y + state->sy; - - if (new_x < 0 || new_x >= state->width || new_y < 0 || new_y >= state->height) { - return END_WALL; - } - - if (is_snake(state->snake->next, new_x, new_y)) { - return END_SNAKE; - } - - 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->snake = add_snake(state->snake, new_x, new_y); - return END_FOOD; - } - } - - state->snake = add_snake(state->snake, new_x, new_y); - struct snake* tail = state->snake; - while (tail->next->next != NULL) { - tail = tail->next; - } - free(tail->next); - tail->next = NULL; - - return END_CONTINUE; -}