mercredi 27 juin 2018

Conditional should change based on even/odd of the counter within the conditional

I am trying to append either "X" or "O", depending on whether the counter (in this case, var = turn) is odd or even.

The counter works as intended (it counts per clicK), but it won't bounce back and forth between the if/else if as the clicks go back and forth between odd/even.

Here are the two functions that are pertinent to the question.

My turn variable is at the top of my script.

var turn = 0

function player() {
    return turn % 2 ? "O" : "X";
    //based off even/odd of turn number, sets the player token
}


$(function gameFunction() {
    $('#myBoard tr').each(function() {
        $(this).find('td').each(function() {
            if ($(this).html() == '' && player() == "X") {

                    $(this).on("click", function() {
                        $(this).append("X");
                        console.log(turn++);
                });

            } else if ($(this).html() == '' && player() == "X") {

                    $(this).on("click", function() {
                        $(this).append("O");
                        console.log(turn++);
                });
            }   
        });
    });
});

Basically, it keeps appending "X", when I need it to append "O" when turn = odd.

Thanks!

Aucun commentaire:

Enregistrer un commentaire