81 lines
2.1 KiB
C
81 lines
2.1 KiB
C
#include "snake.h"
|
|
#include "world.h"
|
|
#include <stdlib.h>
|
|
|
|
struct state* game_state;
|
|
|
|
void* init_game() {
|
|
game_state = malloc(sizeof(struct state));
|
|
if (!game_state) return NULL;
|
|
|
|
game_state->width = COLS;
|
|
game_state->height = LINES;
|
|
game_state->sx = 1;
|
|
game_state->sy = 0;
|
|
|
|
// Inicializuj hada do stredu
|
|
int start_x = game_state->width / 2;
|
|
int start_y = game_state->height / 2;
|
|
game_state->snake = add_snake(NULL, start_x, start_y);
|
|
|
|
// Náhodné jedlo
|
|
for (int i = 0; i < FOOD_COUNT; ++i) {
|
|
game_state->foodx[i] = rand() % game_state->width;
|
|
game_state->foody[i] = rand() % game_state->height;
|
|
}
|
|
|
|
return game_state;
|
|
}
|
|
|
|
void destroy_game(void* game) {
|
|
struct state* st = (struct state*)game;
|
|
free_snake(st->snake);
|
|
free(st);
|
|
}
|
|
|
|
int world_event(struct event* event, void* game) {
|
|
struct state* st = (struct state*)game;
|
|
if (event->type == EVENT_KEY) {
|
|
if (event->key == KEY_UP) {
|
|
st->sx = 0; st->sy = -1;
|
|
} else if (event->key == KEY_DOWN) {
|
|
st->sx = 0; st->sy = 1;
|
|
} else if (event->key == KEY_LEFT) {
|
|
st->sx = -1; st->sy = 0;
|
|
} else if (event->key == KEY_RIGHT) {
|
|
st->sx = 1; st->sy = 0;
|
|
}
|
|
} else if (event->type == EVENT_ESC || event->type == EVENT_END) {
|
|
return 1;
|
|
} else if (event->type == EVENT_TIMEOUT) {
|
|
int status = step_state(st);
|
|
if (status != END_CONTINUE) {
|
|
set_message("Koniec hry!", st->width / 2 - 5, st->height / 2);
|
|
return 1;
|
|
}
|
|
|
|
clear_screen();
|
|
|
|
// Zobraz hada
|
|
struct snake* s = st->snake;
|
|
while (s) {
|
|
set_cell('O', s->x, s->y);
|
|
s = s->next;
|
|
}
|
|
|
|
// Zobraz jedlo
|
|
for (int i = 0; i < FOOD_COUNT; ++i) {
|
|
if (st->foodx[i] >= 0 && st->foody[i] >= 0) {
|
|
set_color_cell('*', st->foodx[i], st->foody[i], COLOR_RED, COLOR_BLACK);
|
|
}
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
int main() {
|
|
return start_world(init_game, world_event, destroy_game);
|
|
}
|
|
|