One of my favourite ways of improving my coding is by working on Katas. Katas are small coding problems that are used to practise a technique. The concept derives from Japanese martial arts where students continuously repeat a certain sequence to refine their technique. There is an early Playful Python article that goes into this concept more
The point of a software kata is not to arrive at a "correct" solution, but as a playground to experiment with different approaches. Since we just learned about the multi-value monad in the previous article, how about we use it to solve the Blackjack scoring kata?
One of the key aspects of the game of Blackjack is to determine the score for a hand of cards.
- Cards from
10are worth the points equal to their face value
- The cards Jack
Kare worth 10 points each
- The Ace
Acecan be worth either 1 point, or 11 points. Usually the higher the score is better, but if your score crosses 21 then you lose (its called going "bust"). So you want to select the points for the
Ain such a way that it is as high as possible without crossing 21
Here are some examples of hands and their scores:
2- 16 points, just add up all the numbers
A- 15 points. Here if we take
Aas 11 then the hand will bust. So we take
Aas a 1
A- 14 points. We take the first
Aas 11 points. Taking the second
Aas 11 will bust, so we consider the second
Aas 1 point
A- 13 points
Generally in blackjack you can only consider one
A as 11 as any more will definitely bust. However if we keep the bust threshold at a higher value, say 25, then there could be situations where more than one
A could be counted as 11.
So here is the problem statement
Given a hand of cards, and a bust threshold, determine the score of the hand
We are going to solve this problem in two ways: one using functions (this article), and the second one using classes (next article). We will use the multi-value monad in both approaches.