Přidat a4/game.c

This commit is contained in:
Mykola Syniavskyi 2025-05-03 10:27:18 +00:00
parent b1f358bf05
commit a348c0d78d

107
a4/game.c Normal file
View File

@ -0,0 +1,107 @@
#include <curses.h>
#include <stdlib.h>
#include <string.h>
#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;
}