Skip to content

Instantly share code, notes, and snippets.

@sleepyfox
Created February 21, 2012 21:37
Show Gist options
  • Save sleepyfox/1879125 to your computer and use it in GitHub Desktop.
Save sleepyfox/1879125 to your computer and use it in GitHub Desktop.
Deck of cards - hand of 5 random cards sorted by Black->Red, Spades->Clubs, Diamonds->Hearts, A high
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
class Card
constructor: (value, suit) ->
@suit ?= suits[random(4)]
@value ?= cards[random(13)]
toString: ->
"#{@value} of #{@suit}"
random = (range) -> Math.floor(Math.random() * range)
equal = (card, otherCard) ->
(card.suit == otherCard.suit and card.value == otherCard.value)
greater = (card, otherCard) ->
if card.suit is otherCard.suit
if cards.indexOf(card.value) > cards.indexOf(otherCard.value)
true
else
false
else
if suits.indexOf(card.suit) > suits.indexOf(otherCard.suit)
true
else
false
compare = (card, otherCard) ->
if equal(card, otherCard) then 0
else
if greater(card, otherCard) then 1 else -1
hand = []
hand[i] = new Card for i in [0..4]
hand.sort compare
console.log "#{card.toString()}" for card in hand
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment