Skip to content

Instantly share code, notes, and snippets.

@worthlesscog
Created May 7, 2012 18:02
Show Gist options
  • Save worthlesscog/2629343 to your computer and use it in GitHub Desktop.
Save worthlesscog/2629343 to your computer and use it in GitHub Desktop.
Blackjack hands for initial, in-play and split
abstract class Hand {
val cards: Seq[Card]
def +(card: Card): Hand
def split: List[Hand]
lazy val scores = {
def combinations(cards: Seq[Card]): List[Seq[Int]] = {
if (!cards.isEmpty) {
for (c ← combinations(cards.tail); v ← cards.head.rank.faceValues) yield v +: c
} else List(Nil)
}
combinations(cards).map(_.sum).distinct.filter(_ < 22).sortWith(_ > _)
}
def score = {
if (scores.isEmpty) 0
else if ((cards.size == 2) && (scores.head == 21)) 22
else scores.head
}
lazy val scoreText = score match {
case 0 ⇒ "Bust"
case 22 ⇒ "Blackjack"
case _ ⇒ score.toString
}
override def toString = cards.reverse.mkString("(", ", ", ")") + " for " + scoreText
}
case class InitialHand(first: Card, second: Card) extends Hand {
val cards = Seq(second, first)
def +(card: Card) = InPlayHand(card, second, first)
def split = List(SplitHand(first), SplitHand(second))
}
case class InPlayHand(cards: Card*) extends Hand {
def +(card: Card) = InPlayHand(card +: cards: _*)
def split = throw new UnsupportedOperationException
}
case class SplitHand(cards: Card*) extends Hand {
def +(card: Card) = SplitHand(card +: cards: _*)
def split = throw new UnsupportedOperationException
override def score = 21.min(super.score)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment