diff --git a/du8/game.c b/du8/game.c new file mode 100644 index 0000000..e65b83c --- /dev/null +++ b/du8/game.c @@ -0,0 +1,90 @@ +#include "game.h" +#include "world.h" +#include + +void init_game(GameState* game) { + for (int y = 0; y < 3; y++) + for (int x = 0; x < 3; x++) + game->board[y][x] = EMPTY; + game->current_player = 0; + game->game_over = 0; + game->winner = 0; +} + +void draw_game(GameState *game) { + + set_message("TicTakToe / Piškvorky", 15, 2); + + + for (int y = 0; y < 3; y++) { + char line[20]; + int index = 0; + + for (int x = 0; x < 3; x++) { + char cell = game->board[y][x]; + if (cell == EMPTY) { + cell = '1' + y * 3 + x; + } + line[index++] = ' '; + line[index++] = cell; + if (x < 2) { + line[index++] = ' '; + line[index++] = '|'; + } + } + line[index] = '\0'; + set_message(line, 17, 4 + y * 2); + + if (y < 2) { + set_message("-----------", 17, 5 + y * 2); + } + } + + if (game->game_over) { + if (game->winner == 1) + set_message("Game over! Player X won.", 12, 11); + else if (game->winner == 2) + set_message("Game over! Player O won.", 12, 11); + else + set_message("Game over! It's a draw.", 12, 11); + + set_message("Press ENTER to restart or Q to quit", 15, 13); + } else { + char msg[32]; + sprintf(msg, "Turn of player %c", (game->current_player == 0) ? 'X' : 'O'); + set_message(msg, 17, 11); + set_message("Press ENTER to confirm/Q to quit", 17, 13); + } +} + +void handle_input(GameState* game, int key) { + if (key >= '1' && key <= '9') { + int pos = key - '1'; + int x = pos % 3; + int y = pos / 3; + if (game->board[y][x] == EMPTY) { + game->board[y][x] = (game->current_player == 0) ? PLAYER_X : PLAYER_O; + game->current_player = 1 - game->current_player; + } + } +} + +int check_winner(GameState* state) { + Cell (*b)[3] = state->board; + + const int win_lines[8][3][2] = { + {{0,0},{0,1},{0,2}}, {{1,0},{1,1},{1,2}}, {{2,0},{2,1},{2,2}}, + {{0,0},{1,0},{2,0}}, {{0,1},{1,1},{2,1}}, {{0,2},{1,2},{2,2}}, + {{0,0},{1,1},{2,2}}, {{0,2},{1,1},{2,0}} + }; + + for (int i = 0; i < 8; i++) { + int y0 = win_lines[i][0][0], x0 = win_lines[i][0][1]; + int y1 = win_lines[i][1][0], x1 = win_lines[i][1][1]; + int y2 = win_lines[i][2][0], x2 = win_lines[i][2][1]; + if (b[y0][x0] != EMPTY && b[y0][x0] == b[y1][x1] && b[y1][x1] == b[y2][x2]) { + return (b[y0][x0] == PLAYER_X) ? 1 : 2; + } + } + return 0; +}