pvjc25/du8/game.c
2025-06-08 21:47:41 +02:00

84 lines
2.7 KiB
C

#include "game.h"
#include "world.h"
#include <string.h>
void init_game(GameState *state){
memset(state->board, ' ', sizeof(state->board));
state->cursor_x = 0;
state->cursor_y = 0;
state->current_player = 0;
state->game_over = 0;
}
void draw_game(const GameState *state){
world_clear();
for (int y = 0; y < BOARD_SIZE; y++){
for (int x = 0; x < BOARD_SIZE; x++){
char symbol = state->board[y][x];
if (symbol == '\0') symbol = ' ';
world_draw_char(x * 4 + 2, y * 2 + 1, symbol);
if (x < BOARD_SIZE - 1){
world_draw_char(x * 4 + 3, y * 2 + 1, '|');
}
}
if (y < BOARD_SIZE - 1){
for (int i = 0; i < BOARD_SIZE * 4 - 1; i++){
world_draw_char(i + 1, y * 2 + 2, '-');
}
}
}
world_draw_char(state->cursor_x * 4 + 2, state->cursor_y * 2 + 1,
state->current_player == 0 ? 'X' : 'O');
world_draw_text(0, BOARD_SIZE * 2 + 2,
state->current_player == 0 ? "Hrac: X" : "Hrac: O");
if (state->game_over){
world_draw_text(0, BOARD_SIZE * 2 + 3, "Koniec hry! Stlac Q pre ukoncenie.");
}
world_display();
}
int check_winner(const GameState *state){
char p[] = {'X', 'O'};
for (int i = 0; i < 2; i++){
char c = p[i];
for (int j = 0; j < BOARD_SIZE; j++){
if (state->board[j][0] == c && state->board[j][1] == c && state->board[j][2] == c) return 1;
if (state->board[0][j] == c && state->board[1][j] == c && state->board[2][j] == c) return 1;
}
if (state->board[0][0] == c && state->board[1][1] == c && state->board[2][2] == c) return 1;
if (state->board[0][2] == c && state->board[1][1] == c && state->board[2][0] == c) return 1;
}
return 0;
}
void handle_key(GameState *state, int key){
if (state->game_over) return;
switch (key){
case KEY_UP: if (state->cursor_y > 0) state->cursor_y--; break;
case KEY_DOWN: if (state->cursor_y < BOARD_SIZE - 1) state->cursor_y++; break;
case KEY_LEFT: if (state->cursor_x > 0) state->cursor_x--; break;
case KEY_RIGHT: if (state->cursor_x < BOARD_SIZE - 1) state->cursor_x++; break;
case '\n':
case ' ':
if (state->board[state->cursor_y][state->cursor_x] == ' ') {
state->board[state->cursor_y][state->cursor_x] = state->current_player ? 'O' : 'X';
if (check_winner(state))
{
state->game_over = 1;
}
else
{
state->current_player = !state->current_player;
}
}
break;
}
}