65 lines
2.3 KiB
C
65 lines
2.3 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++) {
|
|
int wx = 5 + x * 4;
|
|
int wy = 3 + y * 2;
|
|
if (x == state->cursor_x && y == state->cursor_y)
|
|
world_draw_char(wx, wy, state->board[y][x], COLOR_RED);
|
|
else
|
|
world_draw_char(wx, wy, state->board[y][x], COLOR_WHITE);
|
|
}
|
|
}
|
|
world_draw_text(0, 0, "Hráč: %c", state->current_player ? 'O' : 'X');
|
|
if (state->game_over)
|
|
world_draw_text(0, 1, "Koniec hry! Stlač Q na ukončenie.");
|
|
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;
|
|
}
|
|
} |