So here's one for ya. I have this gomoku (5 ina row tic tac toe) code and I want to change it so the computer AI is not super stupid. Currently, all the computer does is put a piece in the first row. It doesn't even try to block. I simply want to make it a little smarter.
Code:
/* A simple Tic Tac Toe game */
#include<stdio.h>
#include<stdlib.h>
char matrix[15][15]; /* the tic tac toe matrix */
char check(void);
void init_matrix(void);
void get_player_move(void);
void get_computer_move(void);
void disp_matrix(void);
int main(void)
{
char done;
printf("This is the game of Tic Tac Toe. \n");
printf("You will be playing against the computer. \n");
done = ' ';
init_matrix ();
do {
disp_matrix();
get_player_move();
done = check(); /* check if winner */
if (done != ' ') break; /* winner! */
get_computer_move();
done = check(); /* see if winner */
} while( done == ' ');
if (done == 'X') printf("You won! \n");
else printf("I won!!! \n");
disp_matrix(); /* Show final positions */
return 0;
}
/* Initialize the matrix */
void init_matrix(void)
{
int i, j;
for (i=0; i<15; i++)
for (j=0; j<15; j++) matrix[i][j] = ' ';
}
/* Get a player's move */
void get_player_move(void)
{
int x, y;
printf("Enter X,Y coordinates for your move: ");
scanf("%d%*c%d", &x, &y);
x--; y--;
if(matrix[x][y] != ' ') {
printf("Invalid move, try again. \n");
get_player_move();
}
else matrix[x][y] = 'X';
}
/* Get a move from the computer */
void get_computer_move(void)
{
int i, j;
for(i=0; i<15; i++) {
for (j=0; j<15; j++)
if (matrix[i][j] == ' ') break;
if (matrix[i][j] == ' ') break;
}
if (i*j == 225) {
printf("draw\n");
exit (EXIT_SUCCESS);
}
else
matrix[i][j] = '0';
}
/* Display the matrix on the screen */
void disp_matrix(void)
{
int t;
for (t=0; t<15; t++) {
printf(" %c | %c | %c | %c | %c | %c | %c | %c | %c | %c | %c | %c | %c | %c | %c ", matrix[t][0], matrix[t][1], matrix[t][2], matrix[t][3], matrix[t][4], matrix[t][5], matrix[t][6], matrix[t][7], matrix[t][8], matrix[t][9], matrix[t][10], matrix[t][11], matrix[t][12], matrix[t][13], matrix[t][14]);
if(t!=14) printf("\n---|---|---|---|---|---|---|---|---|---|---|---|---|---|---\n");
}
printf("\n");
}
/* See if there is a winner */
char check(void)
{
int i;
for (i=0; i<4; i++) /* check rows */
if (matrix[i][0] == matrix[i][1] && matrix[i][0] == matrix[i][2] && matrix[i][0] == matrix[i][3] && matrix[i][0] == matrix[i][4])
return matrix[i][0];
for (i=0; i<4; i++) /* check columns */
if (matrix[0][i] == matrix[1][i] && matrix[0][i] == matrix[2][i] && matrix[0][i] == matrix[3][i] && matrix[0][i] == matrix[4][i])
return matrix[0][i];
/* test diagonals */
if(matrix[0][0] == matrix[1][1] && matrix[1][1] == matrix[2][2] && matrix[2][2] == matrix[3][3])
return matrix[0][0];
if(matrix[0][2] == matrix[1][1] && matrix[1][1] == matrix[2][0])
return matrix[0][2];
return ' ';
}