From a348c0d78d5d5bfe4886194603f6432e361df2a8 Mon Sep 17 00:00:00 2001 From: Mykola Syniavskyi Date: Sat, 3 May 2025 10:27:18 +0000 Subject: [PATCH] =?UTF-8?q?P=C5=99idat=20a4/game.c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- a4/game.c | 107 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 a4/game.c diff --git a/a4/game.c b/a4/game.c new file mode 100644 index 0000000..cc181f3 --- /dev/null +++ b/a4/game.c @@ -0,0 +1,107 @@ +#include +#include +#include +#include "world.h" +#include "game.h" + + +void* init_game() { + struct game* st = calloc(1, sizeof(struct game)); + st->catx_position = rand() % COLS; + st->caty_position = rand() % LINES; + + for (int i = 0; i < MOUSE_COUNT; i++) { + st->mousex[i] = rand() % COLS; + st->mousey[i] = rand() % LINES; + st->mouse_state[i] = 0; + } + + return st; +} + + +int game_event(struct event* event, void* game) { + struct game* state = game; + if (event->type == EVENT_ESC) { + return 1; + } + if (event->type == EVENT_KEY) { + if (event->key == KEY_UP) { + state->catx = 0; + state->caty = -1; + } else if (event->key == KEY_DOWN) { + state->catx = 0; + state->caty = 1; + } else if (event->key == KEY_LEFT) { + state->catx = -1; + state->caty = 0; + } else if (event->key == KEY_RIGHT) { + state->catx = 1; + state->caty = 0; + } + } + + if (event->type == EVENT_TIMEOUT) { + int cx = state->catx_position + state->catx; + int cy = state->caty_position + state->caty; + if (cx >= 1 && cx < event->width - 1 && cy >= 1 && cy < event->height - 1) { + state->catx_position = cx; + state->caty_position = cy; + } + + int alive = 0; + + for (int i = 0; i < MOUSE_COUNT; i++) { + if (state->mouse_state[i] == 0) { + int mx = state->mousex[i]; + int my = state->mousey[i]; + + int move = rand() % 4; + if (move == 0 && my > 1) my--; + else if (move == 1 && my < event->height - 2) my++; + else if (move == 2 && mx > 1) mx--; + else if (move == 3 && mx < event->width - 2) mx++; + + state->mousex[i] = mx; + state->mousey[i] = my; + + if (mx == state->catx_position && my == state->caty_position) { + state->mouse_state[i] = 1; + } else { + alive++; + } + } + } + if (alive == 0) { + clear_screen(); + set_message("all mouses catched", 10, event->height / 2); + return 1; + } + + + clear_screen(); + + + for (int x = 0; x < event->width; x++) { + set_cell('#', x, 0); + set_cell('#', x, event->height - 1); + } + for (int y = 0; y < event->height; y++) { + set_cell('#', 0, y); + set_cell('#', event->width - 1, y); + } + + set_color_cell('C', state->catx_position, state->caty_position, COLOR_YELLOW, COLOR_RED); + + + for (int i = 0; i < MOUSE_COUNT; i++) { + if (state->mouse_state[i] == 0) { + set_color_cell('m', state->mousex[i], state->mousey[i], COLOR_WHITE, COLOR_GREEN); + } + } + sprintf(state->message, "mouses left: %d", alive); + set_message(state->message, 1, 0); + } + + return 0; +}