Last active
December 31, 2015 21:09
-
-
Save byrichardpowell/8045197 to your computer and use it in GitHub Desktop.
A function for shuffling a deck of cards into the stacks required for a game of klondike.
This file contains 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
shuffleForKlondike = () -> | |
suits = _.shuffle(['clubs', 'spades', 'diamonds', 'hearts']) | |
range = [1..13] | |
deck = | |
clubs: | |
cards: _.shuffle(range) | |
index: 0 | |
spades: | |
cards: _.shuffle(range) | |
index: 0 | |
diamonds: | |
cards: _.shuffle(range) | |
index: 0 | |
hearts: | |
cards: _.shuffle(range) | |
index: 0 | |
getNext: (suit) -> | |
number = @[suit].cards[@[suit].index] | |
@[suit].index++ | |
# All the cards from this suit have been taken. | |
# Remove this suit so that we get 13 cards from each suit | |
if @[suit].index is 13 | |
suits = _.reject(suits, (s) -> s is suit) | |
return number | |
# We will return this | |
cards = | |
deck: [] | |
tableau: [] | |
# Get cards for tableau stacks | |
# The first stack has 1 card, | |
# the 2nd has 2 and so on. | |
# There are 7 stacks | |
for stack in [0..6] | |
cards.tableau[stack] = [] | |
for card in [0..stack] | |
suit = suits[_.random(0,suits.length-1)] | |
cards.tableau[stack].push | |
suit: suit | |
number: deck.getNext(suit) | |
# Insert the remaining cards into | |
# the deck. The deck is the stack | |
# the player draws cards from | |
for i in [0..23] | |
suit = suits[_.random(0,suits.length-1)] | |
cards.deck.push | |
suit: suit | |
number: deck.getNext(suit) | |
return cards |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment