How do I check for winner tic tac toe jquery?

Stuck setting tic tac toe up. I have the board set, turns for players 1 and 2, all box# win possibilities, and some reason it's alerting that player has won even though they didn't. Example player1=x player2=o sq1 && sq2 &&sq3 returns true so x-o-x alerts as winner for player one

$(document).ready(function() {
    var player = 1;
    $('.box').on('click', function(event) {
        alert('add symbol here');
        var boxSelected = $(this);

        if (boxSelected.hasClass('exes') || boxSelected.hasClass('ohs')) {
            alert('You cant do that! Nice try');
        } else {
            if (player == 1) {
                boxSelected.addClass('exes');
                if (checkIfPlayerWon('exes')) {
                    alert('Congrats! Player ' + player + 'has won the game!');
                } else {
                    player = 2;
                }
            } else {
                boxSelected.addClass('ohs');
                if (checkIfPlayerWon('ohs')) {
                    alert('Congrats! Player ' + player + 'has won the game!');
                } else {
                    player = 1;
                }
            }
        }
    });

    function checkIfPlayerWon(symbol) {
        if ($('.sq1').hasClass(symbol) && $('.sq2') && $('.sq3').hasClass(symbol)) {
            return true;
        } else if ($('.sq4').hasClass(symbol) && $('.sq5') && $('.sq6').hasClass(symbol)) {
            return true;
        } else if ($('.sq7').hasClass(symbol) && $('.sq8') && $('.sq9').hasClass(symbol)) {
            return true;
        } else if ($('.sq1').hasClass(symbol) && $('.sq4') && $('.sq7').hasClass(symbol)) {
            return true;
        } else if ($('.sq2').hasClass(symbol) && $('.sq5') && $('.sq8').hasClass(symbol)) {
            return true;
        } else if ($('.sq3').hasClass(symbol) && $('.sq6') && $('.sq9').hasClass(symbol)) {
            return true;
        } else if ($('.sq3').hasClass(symbol) && $('.sq5') && $('.sq7').hasClass(symbol)) {
            return true;
        } else if ($('.sq1').hasClass(symbol) && $('.sq5') && $('.sq9').hasClass(symbol)) {
            return true;
        } else if ($('.sq3').hasClass(symbol) && $('.sq5') && $('.sq7').hasClass(symbol)) {
            return true;
        } else {
            return false;
        }
    }
});

Answers 1

  • You are missing the hasClass(symbol) on some of the boxes.

    Change all:

    if ($('.sq1').hasClass(symbol) && $('.sq2') && $('.sq3').hasClass(symbol)) {
        return true;
    

    To:

    if ($('.sq1').hasClass(symbol) && $('.sq2').hasClass(symbol) && $('.sq3').hasClass(symbol)) {
        return true;
    

Related Articles