#include #include #include #include "consts.h" #include "protos.h" SOLUTION is_board_solved(BOARD board) { char cases[8] = {EMPTY}; char i; // rows and cols for (i = 0; i < 3; i++) { cases[i] = board[i][0] * board[i][1] * board[i][2]; cases[i + 3] = board[0][i] * board[1][i] * board[2][i]; } // diagonals cases[6] = board[0][0] * board[1][1] * board[2][2]; cases[7] = board[0][2] * board[1][1] * board[2][0]; // check cases for winner for (i = 0; i < 8; i++) { if (cases[i] == 1) { // X won return X_WON; } else if (cases[i] == 8) { // O won return O_WON; } } // check cases for remaining moves for (i = 0; i < 9; i++) { if (cases[i] == EMPTY) { // more spaces left; game continues return MOVES_LEFT; } } // stalemate return TIE; } void print_board(BOARD board) { char i, j; printf("\n"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { printf("%d ", board[i][j]); } printf("\n"); } } void opponent_move(BOARD board, DIFFICULTY difficulty) { char move, move_x, move_y; printf("Opponent is moving..."); // take winning moves (medium) // if (difficulty > EASY) { // } // prevent winning move (hard) // if (difficulty > MEDIUM) { // } // take random move (easy) do { move = rand() % 9; move_x = move % 3; move_y = move / 3; } while (board[move_y][move_x] != EMPTY); board[move_y][move_x] = O; } void print_endgame(SOLUTION solution) { switch (solution) { case X_WON: printf("X won"); break; case O_WON: printf("O won"); break; case TIE: printf("Stalemate"); break; } printf("\n"); } void player_move(BOARD board) { char move = EMPTY; char move_x = EMPTY; char move_y = EMPTY; do { printf("\nEnter a valid move..."); move = cgetc() - '0' - 1; printf("%d\n", move); move_x = move % 3; move_y = move / 3; } while (0 <= move_x <= move_y <= 2 && board[move_y][move_x] != EMPTY); board[move_y][move_x] = X; } int main() { SOLUTION solution = MOVES_LEFT; char move = EMPTY; char move_x = EMPTY; char move_y = EMPTY; BOARD board = {{EMPTY}, {EMPTY}, {EMPTY}}; cursor(1); print_board(board); do { player_move(board); print_board(board); if ((solution = is_board_solved(board)) == MOVES_LEFT) { opponent_move(board, EASY); print_board(board); } } while (solution == MOVES_LEFT); print_endgame(solution); return 0; }