gpt4 book ai didi

javascript - 垄断挑选随机卡和弹出阵列

转载 作者:行者123 更新时间:2023-11-29 22:05:11 28 4
gpt4 key购买 nike

点击

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"
}]
};

好的伙计们,我正在尝试随机选择一张卡片,然后我想弹出它,但是由于我使用的是随机生成器,所以我必须调整最小值和最大值,因为数组中会少一张卡片.我也会接受一个更好的答案,一个更有效的方法。例如洗牌?我不知道那会如何工作。

最佳答案

您可以使用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);

关于javascript - 垄断挑选随机卡和弹出阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21350409/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com