Created
February 2, 2015 19:16
-
-
Save CaffeinatedDave/106103dd6bb1e24f0e54 to your computer and use it in GitHub Desktop.
Simple card shuffler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Card(face, suit) { | |
this.face = face; | |
this.suit = suit; | |
// Cheap to_string function | |
this.to_s = function() { | |
return "The " + face + " of " + suit; | |
} | |
} | |
// Set up the suits and face values for the cards. | |
suits = ["Diamonds", "Clubs", "Hearts", "Spades"] | |
faces = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"] | |
// allCards contains a list of objects. Each object should be a sorted list of cards, and a shuffled state (true/false) | |
var allCards = []; | |
/* Function newDeck | |
* Adds a new pack of 52 cards to the end of the deck | |
* | |
* params: shuffled boolean | |
* Is the new deck shuffled or not? | |
*/ | |
function newDeck(shuffled) { | |
deck = []; | |
for (var s = 0; s < suits.length; s++) { | |
for (var f = 0; f < faces.length; f++) { | |
deck.push(new Card(faces[f], suits[s])); | |
} | |
} | |
allCards.push({cards: deck, shuffled: (shuffled == true)}); | |
} | |
/* Function draw(x) | |
* Draws the top x cards from allCards to the caller | |
* | |
* params: x int | |
* number of cards to draw | |
* | |
* returns: [Card] | |
* a list of cards - may be less than requested, depending on the number available in allCards | |
*/ | |
function draw(x) { | |
var toRet = []; | |
for (var d = 0; d < x; d++) { | |
if (allCards.length == 0) { | |
// Out of cards. | |
return toRet; | |
} else if (allCards[0].cards.length == 0) { | |
// This set is empty, move onto the next... | |
// What I wouldn't give for an lpop... | |
allCards.splice(0, 1); | |
d--; | |
} else { | |
// Actually draw a card - if we're shuffled, use a lazy evaluation of the Fisher-Yates algorithm | |
if (allCards[0].shuffled) { | |
toRet.push(allCards[0].cards.splice(parseInt(Math.random() * allCards[0].cards.length), 1)[0]); | |
} else { | |
toRet.push(allCards[0].cards.splice(0, 1)[0]); | |
} | |
} | |
} | |
return toRet; | |
} | |
// No actual shuffling happens here - just flatten allCards into a single element | |
// and deal with it later | |
function shuffle() { | |
flatten = []; | |
while (allCards.length > 0) { | |
d = allCards.pop(); | |
flatten = flatten.concat(d.cards); | |
} | |
allCards.push({cards: flatten, shuffled: true}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment