1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
int computerMove(vector<char> 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;
}
}
}
|