开发者

Javascript Array not being filled properly

I'm having some trouble getting an array to be filled properly. I'm attempting to get a deck of cards to be loaded into an array and then shuffled which does work fine initially, however, after I do a check to see if there are enough cards left, the array does not load properly and everything more or less breaks.

Here's the relevant code. Any help would be greatly appreciated. Thanks!

var deck = {
    //base deck before shuffle
    baseDeck: ['d02', 'd03', 'd04', 'd05', 'd06', 'd07', 'd08', 'd09', 'd10', 'd11', 'd12', 'd13', 'd14', 'h02', 'h03', 'h04', 'h05', 'h06', 'h07', 'h08', 'h09', 'h10', 'h11', 'h12', 'h13', 'h14', 'c02', 'c03', 'c04', 'c05', 'c06', 'c07', 'c08', 'c09', 'c10', 'c11', 'c12', 'c13', 'c14', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10', 's11', 's12', 's13', 's14'],
    //Deck Shoe 
    shoe: [],

    //pull deck #, return to shoe 
    shuffleDeck: function () {
        this.shoe.length = 0;
        this.shoe = this.baseDeck;

        for (i = 0; i < this.shoe.length; i++) {
            var randomPlace = Math开发者_高级运维.floor(Math.random() * 50) + 1;
            var currentPlace = this.shoe[i];
            this.shoe[i] = this.shoe[randomPlace];
            this.shoe[randomPlace] = currentPlace;
        }
        }


}

var cardRetrieval = {

    //return card vals
    getCard: function (curHand) {
        var q = curHand.push(deck.shoe.shift());
        this.checkValue(curHand);
        showCards(curHand, q);
        if (deck.shoe.length <= 40) {
            deck.shuffleDeck();
            }
    }

Everything works fine until the if statement at the bottom that checks if there are 40+ cards in the shoe array. But when it attempts to shuffle the deck again, it breaks.


The trouble is with this:

this.shoe.length = 0;
this.shoe = this.baseDeck;

You're not making a copy of the baseDeck into the shoe. Instead you're overwriting the reference to the empty Array you created for shoe, and you're replacing it with a reference to the same Array that baseDeck references.

So it works the first time you shuffle, because this.shoe.length = 0 is not yet affecting the baseDeck. But when you shuffle the second time, you're destroying the baseDeck. (Basically, with that first shuffle, you were using the baseDeck instead of a copy of it.)

Change it to this:

this.shoe.length = 0;
this.shoe = this.baseDeck.slice(0);

This will make a clean copy of baseDeck that is referenced by shoe each time.


There are 2 problems with your random number, 1) it will never be 0 - the first card in the deck, and 2) it may exceed the array size. Use this instead:

var randomPlace = Math.floor(Math.random() * this.shoe.length);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜