bestMove(int p, int*v)
{ int i;
int lastTie;
int lastMove;
int subV;
/*First, check for a tie*/
if (isTie()) {
*v=0;
return(0);
};
/*If not a tie, try each potential move*/
for (*v=-1, lastTie=lastMove=-1,i=0;i<9;i++)
{
/*If this isn't a possible, skip it*/
if (board!=0) continue;
/* Make the move. */
lastMove=i;
board=p;
/* Did it win? */
if (hasWon(p)) *v=1;
else{
/*If not, find out how good the other side can do*/
bestMove(-p,&subV);
/* If they can only lose, this is still a win.*/
if (subV==-1) *v=1;
/* Or, if it's a tie, remember it. */
else if (subV==0){
*v=0;
lastTie=i;
};
};
/* Take back the move. */
board=0;
/*If we found a win, return immediately
(can't do any better than that)*/
if (*v==1) return(i);
/*If we didn't find any wins, return a tie move.*/
if (*v==0) return(lastTie);
/*If there weren't even any ties, return a loosing move.*/
else return(lastMove);
};