Jump To …

deck.coffee

Card Class

class Card

  constructor: (card) ->

store the card

    @card = card

get the card number

    @num = parseInt(card)

object to hold arrays for click, over & out handlers

    @handlers =
      'click': []
      'over': []
      'out': []

build the card

    @el = $('<div class="card ' + @viewClass() + '"></div>');

bind handlers

    @el.on('click', @click)
    @el.on('mouseover', @over)
    @el.on('mouseout', @out)

  viewClass: ->
    'card-' + @card

over handler

  over: =>
    for i in [@handlers.over.length..1] by -1
      @handlers.over[i-1](@) unless typeof @handlers.over[i-1] != 'function'

out handler

  out: =>
    for i in [@handlers.out.length..1] by -1
      @handlers.out[i-1](@) unless typeof @handlers.out[i-1] != 'function'

click handler

  click: =>
    for i in [@handlers.click.length..1] by -1
      @handlers.click[i-1](@) unless typeof @handlers.click[i-1] != 'function'

method for adding click handlers to the card

  addClickHandler: (handler) ->
    @handlers.click.push(handler)

method for adding hover handlers (over/out) to cards

  addHoverHandler: (over,out) ->
    @handlers.over.push(over)
    @handlers.out.push(out)

Deck Class

Controls a deck of cards, pass array of cards to build a custom deck.
Example building a deck of just the 4 aces:
myDeck = new Deck(Array('1h','1d','1s','1c'))

class Deck

constructor Method

  constructor: ->

default deck

    @cards = [
      '1h','2h','3h','4h','5h','6h','7h','8h','9h','10h','11h','12h','13h',
      '1c','2c','3c','4c','5c','6c','7c','8c','9c','10c','11c','12c','13c',
      '1d','2d','3d','4d','5d','6d','7d','8d','9d','10d','11d','12d','13d',
      '1s','2s','3s','4s','5s','6s','7s','8s','9s','10s','11s','12s','13s',
    ]

check for options

    if (arguments.length)
      options = arguments[0]
      @cards = options.cards?

create the deck

    @deck = @getCards()

getCards Method

  getCards: ->

we use .slice to get a copy of the cards array.

    return @cards.slice(0)

draw Method

  draw: (howMany) ->

create an array of cards to return

    cards = []

loop

    for i in [howMany..1] by 1

pick a random card

      ci = Math.floor(Math.random()*@deck.length)

get the randomly chosen card, create a card object with it, and push it onto the stack.

      cards.push(new Card(@deck.splice(ci,1)[0]));

just return the one card if thats all they asked for

    return cards[0] unless howMany>1
    return cards

cardsLeft method

  cardsLeft: ->
    

get the number of cards left in the deck

    return @deck.length