문제

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.

다른 팁

An expression like a == b == c is not the same as a == b && b == c. That's why your function doesn't work as intended.

if (matrix[0][0] == matrix[0][1] == matrix[0][2]) ... 

is different than:

if (matrix[0][0] == matrix[0][1] && matrix[0][1] == matrix[0][2]) ...

In the first case, the first comparison is evaluated at first, making it equivalent to something like:

int b = matrix[0][0] == matrix[0][1];
if (b == matrix[0][2]) ...

comparison returns 0 or 1, not the value that is being compared (unlike assignment operator, which returns the value that has been assigned).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top