pvjc26/a5/game.c
2026-05-08 13:39:55 +02:00

129 lines
3.6 KiB
C

#include <curses.h>
#include <stdlib.h>
#include <string.h>
#include "world.h"
#include "game.h"
// Start is called one in the beginning
void* init_game(){
// Allocate memory for the state
struct game* st = calloc(1,(sizeof(struct game)));
// Initialize cat
st->catx = 0;
st->caty = 0;
st->catx_position = 15;
st->caty_position = 15;
st->caught_count = 0;
// Initialize 5 mice at random positions
for(int i = 0; i < MOUSE_COUNT; i++){
st->mousex[i] = 5 + rand() % 30;
st->mousey[i] = 5 + rand() % 15;
st->mouse_state[i] = 0; // alive
}
// Store pointer to the state to the world variable
return st;
}
// Step is called in a loop once in interval.
// It should modify the state and draw it.
int game_event(struct event* event,void* game){
// Get state pointer
struct game* state = game;
if ( event->type == EVENT_ESC){
// Non zero means finish the loop and stop the game.
return 1;
}
// Check if all mice are caught
if(state->caught_count == MOUSE_COUNT){
clear_screen();
set_message("VSETKY MYSKY ZJEDENE! VITAZ!",10,12);
return 0;
}
// Check each mouse if it's caught by cat
for(int i = 0; i < MOUSE_COUNT; i++){
if(state->mouse_state[i] == 0){ // mouse is alive
if(state->mousex[i] == state->catx_position && state->mousey[i] == state->caty_position){
state->mouse_state[i] = 1; // caught
state->caught_count++;
}
}
}
if(event->type == EVENT_TIMEOUT) {
// Move cat
int cx = state->catx_position + state->catx;
int cy = state->caty_position + state->caty;
// Check boundaries
if (cx > 0 && cx < event->width && cy > 0 && cy < event->height){
state->catx_position = cx;
state->caty_position = cy;
}
// Move each alive mouse randomly
for(int i = 0; i < MOUSE_COUNT; i++){
if(state->mouse_state[i] == 0){ // mouse is alive
int m = rand() % 4;
int mx = state->mousex[i];
int my = state->mousey[i];
if (m == 0) my -= 1;
else if (m == 1) my += 1;
else if (m == 2) mx -= 1;
else if (m == 3) mx += 1;
// Check boundaries
if (mx > 0 && mx < event->width && my > 0 && my < event->height){
state->mousex[i] = mx;
state->mousey[i] = my;
}
}
}
}
else if (event->type == EVENT_KEY){
// Move cat according to keyboard
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;
}
}
// Draw world state
clear_screen();
// Draw cat
set_color_cell('c',state->catx_position,state->caty_position,COLOR_YELLOW,COLOR_RED);
// Draw mice
for(int i = 0; i < MOUSE_COUNT; i++){
if(state->mouse_state[i] == 0){ // only draw alive mice
set_cell('m',state->mousex[i],state->mousey[i]);
}
}
// Draw caught count
char msg[100];
sprintf(msg,"Chytene: %d/%d", state->caught_count, MOUSE_COUNT);
set_message(msg, 1, 0);
return 0;
}