### Using ComputerMove() for computer to win

Hello. I am a beginner and I've been tasked to write a tic-tac-toe game in which the human always wins. I have the ComputerMove()function in my game as well as a HumanMove(), but I'm wondering if anyone could provide some insight into how I could always have the human win the game? thanks!

 ``1234567891011121314151617181920`` ``````void ComputerMove(){ // // this code makes a move for the computer by putting an 'O' into an element of the Board array // // it should not allow selection of a position that is already occupied by an 'X' or an 'O' // // for full credit, this should be sophisticated enough such that the computer cannot lose to the human opponent // bool done = false; int choice = 0; while (!done && choice <= 9) { if (IsValidMove(choice)) { done = true; SetBoardValue(choice, 'O'); } choice++; } }``````
Last edited on
 I'm wondering if anyone could provide some insight into how I could always have the computer win the game?

Cheat? :)

Read the comments in the program more carefully. "computer cannot lose to the human opponent". Unless the human player makes a mistake, the best that can be obtained by the computer is a tie (which is not a loss).

Ha, Ha! Hard to cheat with a computer :)

Yes, I meant "User always wins, not Computer". My brain is too jumbled right now :)
the computer has no ai here is my tic tac toe computer move code (i use the tiles 0-8 instead of 1-9):

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748`` ``````int computerMove(vector board, char computer) { cout << "I shall take square number "; //if computer can win on next move, make that move for(int move = 0; move < board.size(); ++move) { if (isLegal(move, board)) { board[move] = computer; if (winner(board) == computer) { cout << move << endl; return move; } //done checking this move, undo it board[move] = EMPTY; } } //if human can win on next move, block that move char human = opponent(computer); for(int move = 0; move < board.size(); ++move) { if (isLegal(move, board)) { board[move] = human; if (winner(board) == human) { cout << move << endl; return move; } //done checking this move, undo it board[move] = EMPTY; } } // the best moves to make, in order const int BEST_MOVES[] = {4, 0, 2, 6, 8, 1, 3, 5, 7}; // since no one can win on next move, pick best open square for(int i =0; i < board.size(); ++i) { int move = BEST_MOVES[i]; if (isLegal(move, board)) { cout << move << endl; return move; } } }``````
Topic archived. No new replies allowed.