#include #include const int wins[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8}, {0,4,8},{2,4,6}}; void initialize_board(char board[9]) { for (int i=0; i<9; ++i) board[i] = ' '; } void print_board(char board[9]) { for (int i=0;i<9;i+=3) { printf(" %c | %c | %c\n",board[i],board[i+1],board[i+2]); if (i <= 3) printf("---+---+---\n"); } } // test for a draw int draw(char board[]) { int i; for (i = 0; i < 9 && board[i] != ' '; ++i); return (i==9); } // test for three-in-a-row int three_in_a_row(char board[9], char piece) { for (int i=0; i<8; ++i) { if ((board[wins[i][0]] == piece) && (board[wins[i][1]] == piece) && (board[wins[i][2]] == piece)) return(1); } return 0; } // allow human (O) to make a move void human_move(char board[9]) { int move; do { fflush(stdin); printf("enter your move: "); scanf("%d", &move); } while (move < 0 || move > 8 || board[move] != ' '); board[move] = 'O'; } // test for two-in-a-row with an empty piece in the third square int two_in_a_row(char board[9], char piece) { for (int i=0; i<8; ++i) { if ((board[wins[i][0]] == piece) && (board[wins[i][1]] == piece) && (board[wins[i][2]] == ' ')) return(wins[i][2]); if ((board[wins[i][1]] == piece) && (board[wins[i][2]] == piece) && (board[wins[i][0]] == ' ')) return(wins[i][0]); if ((board[wins[i][0]] == piece) && (board[wins[i][2]] == piece) && (board[wins[i][1]] == ' ')) return(wins[i][1]); } return -1; } // find an open corner square int corner_square(char board[9]) { int i; for (i=0;i<=8; i+=2) if (board[i] == ' ') return i; return -1; } // find any open square int first_empty_square(char board[9]) { int i; for (i=0;i<9;++i) if (board[i] == ' ') return i; return -1; } // computer move strategy void computer_move(char board[9]) { int move; if (board[4] == ' ') // move to center square if open move = 4; else { // check for two-in-a-row for a win if ((move = two_in_a_row(board,'X')) < 0) { // check for two-in-a-row for a block if ((move = two_in_a_row(board, 'O')) < 0) { // check for a corner square if ((move = corner_square(board)) < 0) move = first_empty_square(board); // take whatever square is left } } } printf("I move to square %d\n", move); board[move] = 'X'; } // Play the game of tic-tac-toe where the computer goes first. // The computer is X, the human is O. void main() { char board[9]; int game_over; initialize_board(board); do { computer_move(board); print_board(board); if (game_over = three_in_a_row(board,'X')) printf("I WIN!\n"); else if (game_over = draw(board)) printf("DRAW\n"); else { human_move(board); if (three_in_a_row(board,'O')) { game_over = 1; printf("YOU WIN!\n"); } } } while (!game_over); }