Skip to content

Instantly share code, notes, and snippets.

@thefrontender
Created August 16, 2011 13:59
Show Gist options
  • Save thefrontender/1149151 to your computer and use it in GitHub Desktop.
Save thefrontender/1149151 to your computer and use it in GitHub Desktop.
Javascript Dealer class for card games.
var Dealer = function (deckCount, suitCount) {
var suits = ['♥', '♣', '♦', '♠'], // French suits as a default
pack = [], // cards yet to be dealt (stock/shoe)
played = [], // cards already dealt
i,
j;
deckCount = deckCount || 1;
suitCount = suitCount || 4;
// generate basic 52-card deck
for (j = 0; j < suitCount; j++) {
for (i = 1; i < 14; i++) {
pack.push(suits[j] + i);
}
};
// put the right number of decks in the pack
while (--deckCount) {
pack = pack.concat(pack.slice(0, 52));
};
return {
// Fisher-Yates shuffle - http://jsfromhell.com/array/shuffle
shuffle: function () {
for(var j, x, v = pack, i = v.length; i; j = ~~(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
},
// deals from the top of the deck, defaults to 1 card
deal: function (num) {
var cards = pack.splice(0, num || 1);
played = played.concat(cards);
return cards;
},
// put the played cards back in the deck, defaults to keeping the original order
recycleDeck: function (reshuffle) {
pack = pack.concat(played);
played = [];
if (reshuffle) {
this.shuffle();
}
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment