1

In prepping the objects for a game I'm making in javscript, I'm reading in a JSON object, deckData, and appending each as a child of this.discard. I'm then scheduling a job that checks to see if this.deck is empty. If it is, then the function should shuffle the array of cards listed as children of this.discard and then assign them as children of this.deck.

The whole process seems to work fairly smoothly except for the key line where I try to assign the newly shuffled array over:

this.deck.children_ = this.shuffle(this.discard.children_);

I'm looking for a solution that will succesfully append all elements that were children of this.discard as children of this.deck. And I realize I'm not yet emptying the array from this.discard yet either, but one step at a time. Full code snippet as follows:

sideboard = function(game) {

    this.discard = new lime.Layer();
    this.appendChild(this.discard);
    for (var key in deckData) {
        var cardData = deckData[key];
        this.addCard(cardData);
    };

    this.mythosDeck = new lime.Layer();
    this.appendChild(this.mythosDeck);

    lime.scheduleManager.schedule(this.deckShuffler, this);
};

sideboard.prototype.deckShuffler = function() {
    if (this.deck.children_.length < 1) {
        this.deck.children_ = this.shuffle(this.discard.children_);
    }
};

sideboard.prototype.shuffle = function(array) {
    var tmp, current, top = array.length;

    if(top) while(--top) {
        current = Math.floor(Math.random() * (top + 1));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
    }

    return array;
};
IanWhalen
  • 801
  • 11
  • 29

1 Answers1

2

Don't you just want to concatenate the two arrays and then reassign ? For example:

this.deck.children_ = this.deck.children_.concat(this.shuffle(this.discard.children_));
perror
  • 7,071
  • 16
  • 58
  • 85
iamjwc
  • 1,456
  • 2
  • 10
  • 7
  • Given the way you've written it there, wouldn't the browser think that children_ is a function being passed the argument 'this.shuffle...' though? I agree with what you're suggesting I do, but I guess my grasp of variable assignment in JS is tenuous - I assumed that given the way I had it the function shuffle would return an array which would get assigned to this.deck.children_. Actually doing it proved otherwise. – IanWhalen Apr 15 '11 at 04:02
  • I am tired and managed to miss the word "concat" which was the most important part of that. I've fixed it now. :) – iamjwc Apr 15 '11 at 04:07
  • Ha, I was just about to ask whether that was it. That works perfectly, thanks! – IanWhalen Apr 15 '11 at 04:10