W
W
WarriorKodeK2018-02-28 14:37:03
JavaScript
WarriorKodeK, 2018-02-28 14:37:03

How to bind a player to cards?

Hey guys. I've been sitting for an hour thinking about how to do it, nothing happens.
I have inputs in which the number of players and the number of cards are entered.
For example, if there are 3 players and 2 cards, then some player will (randomly) have 2 cards.
I want to bind the player to the card by dataset, that is, something like this. this.card.dataset.playerId = id.
Here's how I do it:

class Card {
  constructor(parent, numbers, cardCount, players) {
    this.countOfNumbers = numbers;
    this.cardContainer = parent;
    this.cardsCount = cardCount;
    this.players = players;
    this.createCard();
  }

//Some methods...

 createCard() {
    const numsForCell = this.generateArrayOfNumbers();
    for (let i = 1; i <= this.cardsCount; i++) { // Например мы хотим 2 карточки, тут мы создаем картки
      this.card = document.createElement('div');
      this.card.className = `card`;
      this.card.dataset.id = i;
      for (let j = 1; j <= this.players; j++) { 
        this.card.dataset.playerId = j; // а тут устанавливаем playerId. Но он у меня постоянно одинаковый
      }
      numsForCell.forEach((arrays, i) => {
        const row = document.createElement('div');
        row.className = `row`;
        row.dataset.rowId = i += 1;
        arrays.forEach(number => {
          const cell = document.createElement('div');
          cell.className = 'cell';
          cell.innerHTML += number;
          row.appendChild(cell);
        });
        this.card.appendChild(row);
      });
      this.cardContainer.appendChild(this.card);
    }
  }

But as a result Idof the player, I constantly have the same number. Entered the number of players 2 playerIdwill always be 2
5a9694014450e783999467.png
Here is my full code - https://jsfiddle.net/rw1ob9qf/1/
Please tell me how to solve the problem. Very grateful!
Thank you for your attention!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-28
@WarriorKodeK

And what kind of cycle do you have there? .. No, I don’t want to know this. Do this: the player number is equal to the number of the current card, and if there are no players, then take a random value. That is, replace

for (let j = 1; j <= this.players; j++) { 
  this.card.dataset.playerId = j; // а тут устанавливаем playerId. Но он у меня постоянно одинаковый
}

to something like
this.card.dataset.playerId = i <= this.players ? i : ((Math.random() * this.players | 0) + 1);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question