在为对象分配值之前,循环继续进行

时间:2020-04-29 22:37:53

标签: arrays node.js mongodb for-loop

我正在使用Node / Express / MongoDB创建一个纸牌游戏应用,并使用for循环为每个玩家分发4张纸牌。 for循环会在完成将值分配给cards对象之前继续下一次迭代。

在下面的示例中,游戏中有4个玩家,每个玩家应发4张牌。

发卡功能:

exports.start = async (_id) => {
  const deck = await this.get(_id);
  deck.cards = casinoDeck.cards; // json object with the cards initial state

  // deal 4 cards to each player
  for (let i=0; i<4; i++) {
    for (const player of deck.players) {
      const remainingDeckCards = deck.cards.filter(card => card.state === 'deck').length
      console.log(remainingDeckCards);

      const randomCardIndex = this.getRandomInt(remainingDeckCards);

      deck.cards[randomCardIndex].player = player;
      deck.cards[randomCardIndex].state = 'hand';
    };
  };

  deck.save();
  return deck;
};

分配剩余卡的随机索引:

exports.getRandomInt = max => Math.floor(Math.random() * Math.floor(max));

甲板模式:

const deckSchema = new Schema({
  cards: [{
    name: {type: String, enum:['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2']},
    suit: {type: String, enum:['C', 'D', 'H', 'S']},
    rank: {type: Number},
    altRank: {type: Number},
    player: {type: Schema.Types.ObjectId, ref: 'user', default: null},
    state: {type: String, enum: ['deck', 'table', 'hand', 'won'], default: 'deck'},
    image: {type: String}
  }],
  players: [{type: Schema.Types.ObjectId, ref:'user', default: null}]
});

console.log(remainingDeckCards)记录以下内容,其中在某些迭代中,卡片组中的其余卡未更改。这表示for循环在将值分配给deck.cards.state(可能还有deck.cards.player)之前继续进行迭代。这导致某些卡被“降级两次” ...

52 51 50 49 48 47 46 45 44 43 42 42 41 40 39 39

在for循环继续进行下一次迭代之前,如何确保为deck.cards分配一个值?

0 个答案:

没有答案