Skip to content

Instantly share code, notes, and snippets.

@brownmike
Created January 15, 2014 15:59
Show Gist options
  • Save brownmike/8438824 to your computer and use it in GitHub Desktop.
Save brownmike/8438824 to your computer and use it in GitHub Desktop.
Save me
# TODO: Create InvalidCard, DuplicateCard & InvalidDeck exceptions
class Card
# 11 - 14 represent Jack through Ace respectively
VALUES = (2..14).to_a
SUITS = [:spades, :clubs, :hearts, :diamonds]
attr_reader :value, :suit
def initialize value, suit
ensure_valid value, suit
@value = value
@suit = suit
end
def to_s
case @value
when 11
"Jack of " + suit_to_s
when 12
"Queen of " + suit_to_s
when 13
"King of " + suit_to_s
when 14
"Ace of " + suit_to_s
else
@value.to_s + " of " + suit_to_s
end
end
def >(other_card)
@value > other_card.value
end
def <(other_card)
@value < other_card.value
end
def ==(other_card)
@value == other_card.value
end
private
def ensure_valid value, suit
# TODO: raise InvalidCard
raise TypeError unless VALUES.include?(value) && SUITS.include?(suit)
end
def suit_to_s
@suit.to_s.capitalize
end
end
# Monkeypatch to determine if an array consists of unique elements
class Array
def uniq?
self.length == self.uniq.length
end
end
class Deck
include Enumerable
extend Forwardable
def initialize cards=[]
ensure_valid cards
@cards = cards
end
def_delegator :@cards, :shift, :draw
def_delegator :@cards, :shift, :deal_card
def_delegator :@cards, :include?, :has_card?
def_delegators :@cards, :first, :last, :select
def each &block
@cards.each &block
end
def shuffle
Deck.new @cards.shuffle
end
def shuffle!
@cards.shuffle!
self
end
def << new_card
Deck.new @cards << new_card
end
def self.full_deck
all_cards = []
Card::SUITS.each do |suit|
Card::VALUES.each do |value|
all_cards << Card.new(value, suit)
end
end
Deck.new all_cards
end
private
def ensure_valid cards
raise TypeError unless cards.uniq? # TODO: raise DuplicateCard
cards.each do |card|
raise TypeError unless card.is_a?(Card) # TODO: raise InvalidDeck
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment