0

I'm writing a simple card game, but for some reason this code below behaves very strangely...The turn functions is first called using theTurn(0)

players is an array of objects with player name and hand etc.

function theTurn(playerNumber) {
    if(play == 1) {
        $('#player').text(players[playerNumber].Name);
        $('#submit').click(function() {
            nextPlayer(playerNumber);
        })
    }
}

function nextPlayer(playerNumber) {
    if(playerNumber == players.length - 1) {
        theTurn(0);
    } else {
        theTurn(playerNumber + 1);
    }
}

For some reason I get player 0 then 1 then 1 again and then 0.

I've left out some of the stuff in theTurn...but this is the gist of it and the problem shows up in this simplified version too.

Any help with my faulty logic would be greatly appreciated.

4
  • What does players contain ? Commented Oct 27, 2016 at 13:21
  • Is play used as a boolean or does it increment? This will currently add a new click handler every time theTurn gets called and play=1, try removing the click handler in nextPlay Commented Oct 27, 2016 at 13:23
  • seems like infinite loop Commented Oct 27, 2016 at 13:25
  • try break instead of theTurn(0); Commented Oct 27, 2016 at 13:25

1 Answer 1

1

This actually makes a little more sense... just add the click handler once, then set the player number as a data property so the nextPlayer function knows what it is without an argument.

$('#player').data('activePlayer', 0);
$('#submit').click(function() {
    nextPlayer();
});

function theTurn(playerNumber) {
    if(play == 1) {
        $('#player').text(players[playerNumber].Name);
        $('#player').data('activePlayer', playerNumber);

    }
}

function nextPlayer() {
    var playerNumber = $('#player').data('activePlayer');

    if(playerNumber == players.length - 1) {
        theTurn(0);
    } else {
        theTurn(playerNumber + 1);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Trey...that seems to do the trick. I never knew you could assign data to an element...new trick. Awesome.
Gotta love jQuery.. I sometimes use $(selector).attr('data-prop') instead because it can serve a dual purpose as a selector for styling since it actually adds an HTML data attribute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.