int AIMinimaxAgent::findBestMove(bool nodeType, Board b, int depth)
{
if((depth == 0))
return b.evaluateBoard();
Board c; // temp board
int best; // the best so far for this level
int value; // the value for each node
// which node are we looking at?
switch(nodeType)
{
// min node, i.e. human move
case MINNODE :
{
best = 99;
// for each square
for(int i=0;i<9;i++)
{
// make a copy of the board
c.copy(b);
// if this move is legal
if(c.isLegal(i))
{
//make the move
c.makeMove(X, i);
value = findBestMove(!nodeType, c, depth-1);
// if this move is less than the best at this level
if(value < best)
best = value; // update the best
// unmake the move so the next move can be tested
c.setSquares(EMPTY, i);
}
}
// return the best score that was found
return best;
} break;
// max node, i.e computer move
case MAXNODE :
{
best = -99;
// for each square
for(int i=0;i<9;i++)
{
// make a copy of the board
c.copy(b);
// if this move is legal
if(c.isLegal(i))
{
// make the move
c.makeMove(O, i);
// find the best move from this position
value = findBestMove(!nodeType, c, depth-1);
// if this move is better than the current best for this level
if(value > best)
best = value; // update the best score
// unmake the move so we can test the next move
c.setSquares(EMPTY, i);
}
}
// return the best score found for this level of recursion
return best;
} break;
}
return 0;
}
int AIMinimaxAgent::getMove(Board b)
{
int best;
int value;
int theMove;
for(int i=0;i<9;i++)
{
if(b.isLegal(i))
{
b.setSquares(EMPTY, i);
value = findBestMove(MINNODE, b, 6);
if(value > best)
{
best = value;
theMove = i;
}
}
}
return theMove;
}
int Board::evaluateBoard()
{
if(isWin())
{
switch(winner)
{
case HUMAN : return -1;
case COMPUTER : return 1;
}
}
if(numPieces = 9)
return 0;
}