samedi 7 novembre 2020

if statement does not work in determining the winner in tic tac toe game

I have a little question about "if statemenet" in my code. I really dont understand why this is not working propperly. Ok.. So to finish my tic-tac-toe game i have only to write a function which determining a winner of the game. And here is the problem. I have Squares-object javascript array which contains objects and it is in the state. This array with objects is used for creating a squares grid on my game board and it is also used for couple other things, like checking if square field is full, creating X's and O's on clicked suqares etc.

Here it is:

export let squares = [
    {
        id:'sq1',
        content:''
    },
    {
        id:'sq2',
        content:''
    },
    {
        id:'sq3',
        content:''
    },
    {
        id:'sq4',
        content:''
    },
    {
        id:'sq5',
        content:''
    },
    {
        id:'sq6',
        content:''
    },
    {
        id:'sq7',
        content:''
    },
    {
        id:'sq8',
        content:''
    },
    {
        id:'sq9',
        content:''
    },
];

As i said, thanks to this array i can create a squares grid on board game and each square have it's own id (sq1,sq2,sq3 etc.) from left to right in rows. Now when i click lets say on square with id SQ2 then in object where this sq2 property is stored there is content property which is being filled with 'X' or 'O' depending on another state which is playerTurn state. If player turn is 1 then put in "content" X, if 2 then "O". And this is working fine. I was checking this with console.log. So getting to the point... I wanted to choose the winner of the game using "if statement" like this:

        if(squares[0].content && squares[1].content && squares[2].content  === 'X') {
            console.log('winn');
        }

Something weird is going on there and I cant figure it out. So in this if statement I put multiple conditions that must be met to console.log('winn'). So if squares with id sq1 sq2 and sq3 are filled with 'X' (content: 'X') then we should see 'winn' in console. ANd there is a problem. When i put X on those field then OK, its working but... If I put more "X" and "O" in any place on the board, "if statement" shows me "winn" in the console anyway, even though the fields I indicated do not contain X X X but, for example, X O X. Why is this happening?

Aucun commentaire:

Enregistrer un commentaire