
TicTacToe AI
I have written a progam that allows two people to play tictactoe, how can I modify it so that the second player becomes the computer?
************source code***********8
#include <stdio.h>
#define SIZE 3
void display( int[][] );
int winner( int[][] );
int main()
{
int win = 1, i, j, col, row, player = 0;
int array[SIZE][SIZE];
printf( "TIC TAC TOE\n\n" );
// initalize the array
for ( i = 0; i < SIZE; i++ )
for( j = 0; j < SIZE; j++ )
array[i][j] = 3;
while (win == 1) {
display( array );
printf( "Enter row(0 to quit): " );
scanf( "%d", &row ); // read in row
if (row == 0 )
break;
printf( "Enter column: ");
scanf( "%d", &col ); // read in col
if ( array[row1][col1] == 3 ) { // check if square is empty
array[row1][col1] = (player); // assign player# to square
player = (player+1)%2;
}
else
printf( "Invalid entry\n" );
win = winner( array );
if ( win == 0 ) {
display( array );
printf( "X is the winner\n" );
}
if ( win == 1 ) {
display( array );
printf( "O is the winner\n" );
}
}
return 0;
}
void display( int board[SIZE][SIZE] )
{
int i, j;
printf("1 2 3\n\n" ); // print first line
for( i = 0; i < SIZE; i++ ) {
for( j = 0; j < SIZE; j++ ) {
if ( board [i][j] == 0 ) // print X
printf( "X " );
if ( board [i][j] == 1 ) // print O
printf( "O " );
if ( board [i][j] == 3 ) // print blank
printf( " " );
}
printf( "%d\n\n", i+1); // print row number
}
}
int winner( int board[SIZE][SIZE] )
{
int i, j, total = 0, win = 1;
// check horizontal
for( i = 0; i < SIZE; i++ ) {
for( j = 0; j < SIZE; j++ )
total += board[i][j];
if ( total == 0 )
win = 0;
if ( total == 3 )
win = 1;
total = 0;
}
// check vertical
for( j = 0; j < SIZE; j++ ) {
for( i = 0; i < SIZE; i++ )
total += board[i][j];
if ( total == 0 )
win = 0;
if ( total == 3 )
win = 1;
total = 0;
}
// check diagonals
for( j = 0; j < SIZE; j++ )
total += board[j][j];
if ( total == 0 )
win = 0;
if ( total == 3 )
win = 1;
total = board[0][2] + board[1][1] + board[2][0];
if ( total == 0 )
win = 0;
if ( total == 3 )
win = 1;
return win;
}
**************************

My way to do it is this, I'll check all the possibilities of the computer (places where I still can put a piece) and give them points, like, if in a certain place I'll put a X and in the same line I have another X and don't have any O on the same line I'll give 100 points, and like this works..., at the end, the most valuable play, I'll do it.
Also use code tags