Skip to content

Instantly share code, notes, and snippets.

@invisiblefunnel
Last active December 14, 2015 08:29
Show Gist options
  • Save invisiblefunnel/5058112 to your computer and use it in GitHub Desktop.
Save invisiblefunnel/5058112 to your computer and use it in GitHub Desktop.
Shuffling and dealing cards in CoffeeScript
class Card
  @ranks = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
  @suits = ['C', 'D', 'H', 'S']

  constructor: (@rank, @suit) ->
  toString: -> "#{@rank}#{@suit}"
class FisherYatesShuffler
  shuffle: (array) ->
    i = array.length
    return false if i is 0
    while i--
      j = Math.floor(Math.random() * (i+1))
      tempi = array[i]
      tempj = array[j]
      array[i] = tempj
      array[j] = tempi
    array
class Deck
  constructor: ->
    @cards = []
    for suit in Card.suits
      for rank in Card.ranks
        @cards.push new Card(rank, suit)

  shuffle: (shuffler = new FisherYatesShuffler()) ->
    @cards = shuffler.shuffle(@cards)

  deal: ->
    throw "Deck is empty" if @empty()
    @cards.shift()

  empty: ->
    @cards.length is 0

Usage

deck = new Deck()
deck.shuffle()

console.log "Deck has #{deck.cards.length} cards remaining."

console.log deck.deal().toString() while !deck.empty()

console.log "Deck has #{deck.cards.length} cards remaining."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment