垄断选择随机卡和弹出数组 [英] Monopoly pick random card and pop array

查看:30
本文介绍了垄断选择随机卡和弹出数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击

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

}

好的,我想选择一张随机卡片,然后我要弹出它,但是由于我使用的是随机发生器,因此我必须调整最小值和最大值,因为阵列中少了1张卡片.我也将接受更好的答案,更有效的方法.例如随机播放?我不知道那将如何工作.

Ok guys, I am trying to pick a random card, then I want to pop it, but since I am using random generator, I would have to adjust the min, max values because there would be 1 card less in the array. Also I would accept a better answer, a more efficient way of doing it. For example shuffle? I wouldnt know how that would work.

推荐答案

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

You can use splice to pop the element and use array.length instead of using a fixed number.

   // 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);  

这篇关于垄断选择随机卡和弹出数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆