I need help with my Tic Tac Toe game

I need help with my Tic Tac Toe game
0

#1

Guys, my game is 98% complete and you can see it’s running here https://codepen.io/pierremg/pen/PQeXqd

The only problem is with the following condition: the user is the winner after choosing the fifth and last square. Instead of showing the message “you won” it’ll say “it was a draw”.

This is the problematic part of the code:

if (user.length === 5) {
    for (var j=0;j<combinations.length;j++){
      if(Array.from(new Set(user)).length == Array.from(new Set(user.concat(combinations[j]))).length){
      $('#' + combinations[j][0]).addClass("winner").removeAttr('disabled','disabled');
        $('#' + combinations[j][1]).addClass("winner").removeAttr('disabled','disabled');
        $('#' + combinations[j][2]).addClass("winner").removeAttr('disabled','disabled');
        $('.game-over').removeClass('over').html('You won..');  
        $('.buttonX').addClass('disabled');
$('.buttonO').addClass('disabled');
        gameOn = false;
        setTimeout(function() {restart()}, 2000);
    } else  {
      $('.game-over').removeClass('over').html('It was a draw..');  
        $('.buttonX').addClass('disabled');
$('.buttonO').addClass('disabled');
        gameOn = false;
        setTimeout(function() {restart()}, 2000); }
      }
    }

If the condition is met, it’ll execute the else as well, but this shouldn’t be happening. Try simulating this condition, it’s not that hard. You should win only in the last square.


#2

The else still runs, because you should have broken out of the for loop, when the if statement was true. Add a break statement at the end of your if code block and that should take care of the problem.