So I'm working on writing a C program that will play TicTacTo against the user. However, I'm having issues with the function that checks if there is a winner. It doesn't seem to function at all. The game just continues when there are 3 in a row. Here's the relevant code.
This is in my main function:
do {
humanChoice(); // let the user make a play
computerChoice(); // does nothing at the moment
gameStatus = checkWin(); // returns 1 if it finds a winner
} while(gameStatus==0);
The humanChoice plays an "X" in the array at the position the user selected. This has been tested thoroughly and works perfectly. And then the checkWin() function:
int checkWin() {
if (
matrix[0][0] == matrix[0][1] == matrix[0][2] || // 1st row
matrix[1][0] == matrix[1][1] == matrix[1][2] || // 2nd row
matrix[2][0] == matrix[2][1] == matrix[2][2] || // 3rd row
matrix[0][0] == matrix[1][0] == matrix[2][0] || // 1st column
matrix[0][1] == matrix[1][1] == matrix[2][1] || // 2nd column
matrix[0][2] == matrix[1][2] == matrix[2][2] || // 3rd column
matrix[0][0] == matrix[1][1] == matrix[2][2] || // left to right diagonal
matrix[0][2] == matrix[1][1] == matrix[2][0] // right to left diagonal
) {
printf("Win! Game Over!");
return(1);
}
return(0);
}
I'm using the following 2 dimensional array for my "matrix":
char matrix[3][3];
I realize that right now the program can't distinguish between a computer win and a user win. Right now that's irrelevant. I just need it to check for a win in general.
Anything you notice?
The ==
operator returns true
if the left and right hand operands are equal.
a == b
will return true
when they are equal.
b == c
will return true
when they are equal.
a == b == c
however, will return true when a == b
evaluates to the same value as c
.
You will want to use (a == b) && (b == c)
to achieve what you're trying to achieve.