diff --git a/a2/snake.c b/a2/snake.c index 3aa2987..68a34ae 100644 --- a/a2/snake.c +++ b/a2/snake.c @@ -1,4 +1,5 @@ #include +#include #include // Inicializuje stav hry @@ -18,23 +19,59 @@ void init_state(struct state* state, int width, int height) { 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; + do { + state->foodx[i] = rand() % state->width; + state->foody[i] = rand() % state->height; + } while(is_snake(state->snake, state->foodx[i], state->foody[i])); } } } +// Vykresli stav hry +void draw_state(struct state* state) { + for(int y = 0; y < state->height; y++) { + for(int x = 0; x < state->width; x++) { + if(is_snake(state->snake, x, y)) { + printf("S"); + } else { + int is_food = 0; + for(int i = 0; i < FOOD_COUNT; i++) { + if(state->foodx[i] == x && state->foody[i] == y) { + is_food = 1; + break; + } + } + printf(is_food ? "F" : "."); + } + } + printf("\n"); + } +} + +// Spracuje vstup od hráča +void process_input(struct state* state) { + char input = getchar(); + switch(input) { + case 'w': state->sx = 0; state->sy = -1; break; + case 'a': state->sx = -1; state->sy = 0; break; + case 's': state->sx = 0; state->sy = 1; break; + case 'd': state->sx = 1; state->sy = 0; break; + } +} + // Hlavná slučka hry void game_loop(struct state* state) { while(1) { + draw_state(state); + process_input(state); int result = step_state(state); if(result == END_WALL || result == END_SNAKE) { + printf("Game over!\n"); break; } if(result == END_FOOD) { generate_food(state); } - // TODO: Pridajte kód pre vykreslenie hry a spracovanie vstupu od hráča } }