Karan Mehta
Karan Mehta

Reputation: 83

Tic Tac Toe Winning Function

function checkWin(){
if (arro[0] === arro[1] === arro[2] === 1 || arro[3] === arro[4] === arro[5] === 1 || arro[6] === arro[7] === arro[8] === 1 || arro[0] === arro[4] === arro[8] === 1 || arro[2] === arro[4] === arro[6] === 1 || arro[0] === arro[3] === arro[6] === 1 || arro[1] === arro[4] === arro[7] === 1 || arro[2] === arro[5] === arro[8] === 1) {
    console.log("O Won");
    return "O";
}
else if (arrx[0] === arrx[1] === arrx[2] === 1 || arrx[3] === arrx[4] === arrx[5] === 1 || arrx[6] === arrx[7] === arrx[8] === 1 || arrx[0] === arrx[4] === arrx[8] === 1 || arrx[2] === arrx[4] === arrx[6] === 1 || arrx[0] === arrx[3] === arrx[6] === 1 || arrx[1] === arrx[4] === arrx[7] === 1 || arrx[2] === arrx[5] === arrx[8] === 1){
    console.log("X Won");
    return "X";
}
else
    return "notwin"; }

Here, the arro is the matrix for O and the arrx is the array for X. Running this in the console returns notwin everytime. Some help would be great. Thanks.

Upvotes: 0

Views: 79

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

You can't combine condition checks like that. When you do a === b === c, what you're doing is comparing the result value of the a === b expression (which will be true [if they're the same] or false [if not]) with the value of c.

Instead, you need to combine them with &&, e.g. a === b && b === c.

E.g.:

function checkWin() {
    if ((arro[0] === arro[1] && arro[1] === arro[2]) ||
        (arro[3] === arro[4] && arro[4] === arro[5]) ||
        /*...and so on...*/
       ) {
        console.log("O Won");
        return "O";
    }
    // ...

Side note: If you return from the block attached to the if, there's no need for the else prior to the next if. It's harmless, but pointless.

Upvotes: 2

Related Questions