vendredi 28 avril 2017

Last item in for loop executes multiple times in Javascript

I'm making a JavaScript/jQuery version of a dice game my buddies and I play. Here's a 3 player version of the game:

http://ift.tt/2oUsBI8

I'm trying to make a version of the game where the user can select how many players are playing, and have the game function in the same way:

http://ift.tt/2oGzl0s

Every time the "Go" button is pressed, it's supposed to move on to the next person's turn, and I use a modular operator if condition in a for loop to check whose turn it is, so i can perform a specific action on their turn.

var turn = 0;

$(".goButton").click(function() {
  turn = turn + 1;
  var playerCount = $('#input-number').val();  

  for (i=1;i <= playerCount;i++){
    if (turn % playerCount == i) {
    $(".player" + i + "dollars").append("Hi!");
    }
  }
});

This works great for every player I've created, except the last one (player# playerCount). This is because playerCount % playerCount = 0, and i is never 0, so the last player is always skipped.

I tried to work around this with an else statement for when turn % playerCount = 0 :

var turn = 0;

$(".goButton").click(function() {
  turn = turn + 1;
  var playerCount = $('#input-number').val();  

  for (i=1;i <= playerCount;i++){
    if (turn % playerCount == i) {
    $(".player" + i + "dollars").append("Hi!");
    } else if (turn % playerCount == 0) {
    $(".player" + playerCount + "dollars").append("Hi!");
    }
  }
});

However, when I reach player# playerCount's turn, I get playerCount times "hi!" appended. For example, for 5 players, this is the output in browser:

Player 1
$3Hi!

Player 2
$3Hi!

Player 3
$3Hi!

Player 4
$3Hi!

Player 5
$3Hi!Hi!Hi!Hi!Hi!

Is this a classic "off by 1" error on my part? Or is my else statement flawed in some way?

Aucun commentaire:

Enregistrer un commentaire