* Outputs the board to the screen */
void output(void)
{
int i,j;
char out[12][24]={" | | ",
" | | ",
" | | ",
"-----------------------",
" | | ",
" | | ",
" | | ",
"-----------------------",
" | | ",
" | | ",
" | | "};
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
/* Put the square number in upper right corner */
out[4*i][8*j+6]=i*3+j+49;
/* Put 'X' or 'O' in the out array */
if(board[i][j]==-1)
out[4*i+1][8*j+3]='X';
else if(board[i][j]==1)
out[4*i+1][8*j+3]='O';
}
/* Output the array to screen */
for(i=0;i<12;i++)
printf("%s\n",out[i]);
}
/* Finds the best computer move for the given board
using the minimax function */
void compmove(int who)
{
/* a[] is a list of the all the moves and it's score */
int i,j,a[9];
for(i=0;i<9;i++)
a[i]=-who;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
/* Check for invalid move */
if (board[i][j]!=0)
continue;
/* Try a move */
board[i][j]=who;
/* Score this board with the trial move */
a[i*3+j]=minimax(-who);
/* Undo the move */
board[i][j]=0;
}
/* Find the best move in the array */
i=find(a,who);
/* Make the move */
board[i/3][i%3]=who;
}
/* Recursive minimax the finds the score of
a branch of the move tree */
int minimax(int who)
{
/* Tie = boolean test to see if a tie move has been found
Best = The best score so far */
int tie=0,i,j,best;
/* Test for a loss (win for one level up) */
if(win(-who))
return -who;
/* Test for tie */
if(boardfull())
return 0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
/* Skip invalid moves */
if (board[i][j]!=0)
continue;
/* Try move */
board[i][j]=who;
/* Score this move */
best=minimax(-who);
/* Undo move */
board[i][j]=0;
/* Return the best move if it's a win
because it's not going to get better */
if(best==who)
return who;
/* At least one tie has been found */
else if (best==0)
tie=-1;
}
/* If a tie has been found return tie */
if(tie)
return 0;
/* Return a loss */
else
return -who;
}
/* Finds the best move for who in a[] */
int find(int a[9],int who)
{
int i,best,index=0;
best=-who;
for(i=0;i<9;i++)
{
if(a[i]==who)
return i;
if(a[i]==0 && best==-who)
{
best=0;
index=i;
}
}
/* Returns the location of the best move */
return index;
}