class Blackjack::Hand::BaseHand

Attributes

cards[R]
state[R]

Public Class Methods

new(cards = []) click to toggle source
# File lib/blackjack/hand/base_hand.rb, line 12
def initialize(cards = [])
  @cards = cards
  @state = :initial
end

Public Instance Methods

<<(card) click to toggle source
# File lib/blackjack/hand/base_hand.rb, line 33
def <<(card)
  append(card)
end
<=>(other) click to toggle source
# File lib/blackjack/hand/base_hand.rb, line 59
def <=>(other)
  if self.busted? && other.busted?
    0
  elsif self.busted?
    -1
  elsif other.busted?
    1
  else
    self.value <=> other.value
  end
end
append(card) click to toggle source
# File lib/blackjack/hand/base_hand.rb, line 37
def append(card)
  raise Errors::HandError.new('Unable to append: hand is busted') if busted?

  @cards.push(card)

  @state = :pushed

  self
end
blackjack?() click to toggle source
# File lib/blackjack/hand/base_hand.rb, line 51
def blackjack?
  @cards.count == 2 && value == 21
end
busted?() click to toggle source
# File lib/blackjack/hand/base_hand.rb, line 47
def busted?
  value > 21
end
to_s() click to toggle source
# File lib/blackjack/hand/base_hand.rb, line 55
def to_s
  "Cards: #{ @cards.map(&:to_s).join(', ') }. Value: #{ value }."
end
value() click to toggle source
# File lib/blackjack/hand/base_hand.rb, line 17
def value
  open_cards = @cards.reject(&:hidden?)

  aces = open_cards.select(&:ace?)

  value_without_aces = open_cards.reject(&:ace?).reduce(0) do |product, card|
    product + (card.numeric? ? card.rank : 10)
  end

  value_of_aces = aces.reduce(0) do |product, ace|
    product + (value_without_aces + product > 10 ? 1 : 11)
  end

  value_without_aces + value_of_aces
end