mardi 27 octobre 2020

Block function after condition is fulfilled

I'm facing a problem in my Tic Tac Toe app.. Problem occurs when you're playing against the computer and you win. Green heading about winner will pop-up right above the game field, winner state is changed from false to 'X WINS!', but computer makes another move and this is not supposed to happen.

Last 3 hours I'm trying to fix this by adding new states, new conditions and nothing is helping me.

I figured it is caused by setWinner function, because it is asynchronous and the 'if' statement is executed before the value of 'winner' gets updated. So when the 'if' condition is checked, the value of winner is still false and therefore the computer makes its move. I was recommended to use useEffect hook to check if there is winner or not, but again it doesn't help and computer makes a move again.

useEffect approach

  useEffect(()=>{
    if(winner){
      setPlayerVsPlayer({
        AI:false,
        AImove:false
      });
    }
  })

I've tried to prevent it like this.. In checkWinner function, which is called after every click on game field

if(xCount === 3){
     setWinner('X WINS!');
     displayWinner();

     setWinnerCount(prevState => ({
       ...prevState,
       player1:prevState.player1 + 1
     }));

     setPlayerVsPlayer({
       AI:false,
       AImove
     })
     return;
}

or in computerMove() function

if (emptyCols.length > 0 && winner === false) {
   //run whole computer move function .. i.e. pick random column and insert here O, etc..
}

So logically, If I win, computer shouldn't be able to make one more move because winner state is not false but it's value is 'X Wins!'..

I'm starting to be very frustrated about this.

Thanks to every one, who will take at it.

Codesandbox link https://codesandbox.io/s/cold-shape-xg7l7?file=/src/App.js

Aucun commentaire:

Enregistrer un commentaire