垄断挑选随机卡和流行arrays

点击

function click() { createCards(); pickCard(); } 

选卡

 function pickCard() { var x = Math.floor(Math.random() * ((15 - 0) + 1) + 0); var title = cards.chance[x].title; console.log(x + ". " + title); //pop the array we just picked //adjust Math.floor since there are only 15 cards to pick from instead of 16 } 

创建卡片

 function createCards() { cards = { chance: [{ title: 'Advance to go', type: 'move', position: 40 }, { title: "Advance to London", type: "move", position: 39 }, { title: "Your ass is going to jail", type: "move", position: 10 }, { title: "Advance to Rome", type: "move", position: 24 }, { title: "Advance to Charles de Gaulle", type: "move", position: 15 }, { title: "Advance to Amsterdam", type: "move", position: 11 }, { title: "Go back 3 spaces", type: "movex", position: -3 }, { title: "No drink and driving mate1", type: "bill", bill: 20 }, { title: "Get out of Jail free card", type: "bill", bill: 150 }, { title: "Pay school fees", type: "bill", bill: 150 }, { title: "Speeding fine", type: "bill", bill: 150 }, { title: "Bank pays you dividend", type: "bonus", bonus: 40 }, { title: "You have won the competition", type: "bonus", bonus: 200 }, { title: "Your building loan matures", type: "bonus", bonus: 200 }, { title: "You are assessed for street repairs $40 per house $115 per hotel", type: "billx" }, { title: "House repairs $25 per house $100 per hotel", type: "billx" }] }; 

}

好吧,我试图选择一张随机卡,然后我想弹出它,但由于我使用的是随机发生器,我必须调整最小值,最大值,因为arrays中会少1张卡。 我也会接受一个更好的答案,一个更有效的方法。 例如shuffle? 我不知道这会怎么样。

您可以使用splice弹出元素并使用array.length而不是使用固定数字。

  // if there are no more cards, create them var cardsLeft = cards.chance.length; if(cardsLeft == 0){ createCards(); } // Math var x = Math.floor(Math.random() * cardsLeft); // pop cards.chance.splice(x, 1); 

我会在开始时“洗牌”:

 function shuffle(cards) { var shuffled = [], i = cards.length, j = 0; while (i--) { j = Math.floor(Math.random() * (i+1)); shuffled.push(cards[j]); cards.splice(j,1); } return shuffled; } var shuffledCards = shuffle(cards.chance); 

shuffledCards数组现在将以随机顺序保存所有卡。 然后,您可以在使用时从shuffledCards弹出卡片,或者使用计数器来完成它们。 后者意味着您可以稍后重新洗牌。

注意:这只是我在这里写的内容的改写: https : //stackoverflow.com/a/18806417/1937302

首先使用索引填充数组:

 var i, indexes, pickedIndex; indexes = []; for (i = 0; i < 15; i++) // 16 cards from 0 to 15 { indexes[i] = i; } 

现在,当您需要卡片时,首先选择索引:

 pickedIndex = Math.floor(Math.random() * indexes.length); 

然后,通过覆盖数组中最后一个选择的索引来删除消耗的索引:

 i = indexes.pop(); if (pickedIndex <= indexes.length) { indexes[pickedIndex] = i; } 

上面的代码片段将剩余的索引减少一个,删除所选的一个,并保持未来选择的概率在索引中均匀分布。

使用拾取的索引获取实际卡片。

当indices.length为0时,已选择所有索引。

这个答案使用索引方法以随机顺序对机会卡进行排序,然后通过卡从0到15运行。

    card shuffle