123
This commit is contained in:
parent
773c7ac82b
commit
5e079b3a5b
43
a2/snake.c
43
a2/snake.c
@ -1,4 +1,5 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
|
|
||||||
// Inicializuje stav hry
|
// Inicializuje stav hry
|
||||||
@ -18,23 +19,59 @@ void init_state(struct state* state, int width, int height) {
|
|||||||
void generate_food(struct state* state) {
|
void generate_food(struct state* state) {
|
||||||
for(int i = 0; i < FOOD_COUNT; i++) {
|
for(int i = 0; i < FOOD_COUNT; i++) {
|
||||||
if(state->foodx[i] == -1) {
|
if(state->foodx[i] == -1) {
|
||||||
state->foodx[i] = rand() % state->width;
|
do {
|
||||||
state->foody[i] = rand() % state->height;
|
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
|
// Hlavná slučka hry
|
||||||
void game_loop(struct state* state) {
|
void game_loop(struct state* state) {
|
||||||
while(1) {
|
while(1) {
|
||||||
|
draw_state(state);
|
||||||
|
process_input(state);
|
||||||
int result = step_state(state);
|
int result = step_state(state);
|
||||||
if(result == END_WALL || result == END_SNAKE) {
|
if(result == END_WALL || result == END_SNAKE) {
|
||||||
|
printf("Game over!\n");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if(result == END_FOOD) {
|
if(result == END_FOOD) {
|
||||||
generate_food(state);
|
generate_food(state);
|
||||||
}
|
}
|
||||||
// TODO: Pridajte kód pre vykreslenie hry a spracovanie vstupu od hráča
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user