Skip to content

Instantly share code, notes, and snippets.

@byrichardpowell
Last active December 31, 2015 21:09
Show Gist options
  • Save byrichardpowell/8045197 to your computer and use it in GitHub Desktop.
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.
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