This is a program that allows you to play a 5x5 tic tac toe game with a computer. I am going to implement smart steps for the computer, but first I need to fix the check for winning. If you win with a column or diagonal, it works, but winning with a row only works on line 2 + 3, and not on line 4 or 5. Can someone tell me why? I use exclusively C.
#include <stdio.h>
#include <stdlib.h>
char matrix[5][5];
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();
if(done!= ' ') break;
get_computer_move();
done = check();
} while(done== ' ');
if(done=='X') printf("You won.\n");
else printf("Computer won.\n");
disp_matrix();
return 0;
}
void init_matrix(void)
{
int i, j;
for(i=0; i<5; i++)
for(j=0; j<5; j++) matrix[i][j] = ' ';
}
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';
}
void get_computer_move(void)
{
int i, j;
for(i=0; i<5; i++){
for(j=0; j<5; j++)
if(matrix[i][j]==' ') break;
if(matrix[i][j]==' ') break;
}
if(i*j==25) {
printf("Draw.\n");
exit(0);
}
else
matrix[i][j] = 'O';
}
void disp_matrix(void)
{
int t;
for(t=0; t<5; t++) {
printf(" %c | %c | %c | %c | %c ",matrix[t][0], matrix[t][1], matrix [t][2], matrix[t][3], matrix[t][4]);
if(t!=4) printf("\n---|---|---|---|---\n");
}
printf("\n");
}
char check(void)
{
int i;
for(i=0; i<5; i++)
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<5; i++)
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];
if(matrix[0][0]==matrix[1][1] &&
matrix[1][1]==matrix[2][2] &&
matrix[2][2]==matrix[3][3] &&
matrix[3][3]==matrix[4][4])
return matrix[0][0];
if(matrix[0][4]==matrix[1][3] &&
matrix[1][3]==matrix[2][2] &&
matrix[2][2]==matrix[3][1] &&
matrix[3][1]==matrix[4][0])
return matrix[0][4];
return ' ';
}
source
share