First Steps with Swift: Hands and Evaluation – High Cards

So, we have Cards with Suits and Ranks, we have a Deck, and we can draw random cards from it! Now it’s time to get some cards into the hands of the players!

Hands

Remember the rule we focused on last time:

A poker hand consists of 5 cards dealt from the deck.

We didn’t do anything with a poker hand yet, so let’s go and create it. We start off simple with our first failing test:

Next, the implementation to make our test pass, which is easy enough. We give the Hand a set of cards, and the Hand number should be 0:

The test passes, but we haven’t really done anything yet, so lets continue with another test.
What test could we add to make the implementation more sensible? One that tests one card instead of none, why not.

We have to change our code a bit:

Nothing special here. We add an array, we store the parameter from the constructor into the property and in the calculated property numberOfCards we return cards.count. Test passes 🙂

So how are we going to determine which hand is better? We need some kind of evaluation. Lets look at the rules again to see what they say.

Poker hands are ranked by the following partial order from lowest to highest: High Card, Pair, Two Pair, Three of a Kind, Straight, Flush, Full House, Four of a Kind, Straight Flush, (and Royal Flush).

Alright. Lets start with the first one, the High Card.

High Card

Hands which do not fit any higher category are ranked by the value of their highest card. If the highest cards have the same value, the hands are ranked by the next highest, and so on.

Lets first write a test that evaluates our hand to a high card. When is this the case? Well, when a hand only has one card, it is a high card by definition. Lets write a test to reflect this.

Looks easy enough, but I made some presumptions. I’d thought to make an enum for the hand strengths we have, one of them being .HighCard. We need an evaluate function that returns that .HighCard.
Heres how the enum looks:

Note that we back the HandStrength with an Int. This way we can use comparison, which means that HighCard < Pair and StraightFlush > Straight. Now lets create the evaluation function, which is super straightforward for now:

Easy does it!
But what if we compare two hands, both of which are high cards? Our evaluate function will just return us that the hand is of strength high card, so if we compare the two, they would be equal. However, it doesn’t differentiate between a high card ten and high card ace, while according to the rules the ace would win right?
So we need something to compare hands with based on more than the hand strength. Lets write a test to capture this.

Now it gets interesting! What is going on here? How are we going to make this test pass? The compiler gives us a hint already. It says “Binary operator ‘>’ cannot be applied to two ‘Hand’ operands”. How can we solve this? We need some way to make two hands comparable. Whats great about Swift is that there is a protocol for this. It is called Comparable.

Lets look at how to implement it. We are first going to create an extension on Hand and make it conform to Comparable:

XCode again will give us a hand here; it gives an error and a possible fix, so lets go with that. It provides us two stubs for functions. Looks familiar doesn’t it?

Comparable actually inherits from the protocol Equatable, and so the ‘==’ actually is required by Equatable instead. Let’s take a step back and define a test for this first, commenting out our testThatHighCardAceBeatsHighCardTen test for a moment and removing the extension adopting Comparable for a bit.

Here is our new test. Two hands are the same if they hold cards that have the same value:

Now lets adopt Equatable for hand to pass our test:

This makes our test pass, but as soon as our hand holds more cards we are going to be in trouble. Lets add another test to capture this:

And so we have to loop over the cards in the hands and compare each one as such, where we use a handy function in swift called zip, which creates an array of tuple pairs for each entry of handA and B together:

But we aren’t there yet. If we change our test a little, we can see why.

In order to fix this, we simply need to order our cards before comparing them. We define a sort function which sorts our cards high to low, and use that to sort both lhs.cards and rhs.cards using sorted(by:):

Our test passes! We can actually simplify this a bit further, so lets refactor a bit. Using what we’ve just learned, we can define Comparable for Card.

We can now replace our sort function in the Hand extension for Equatable as such, because operators are actually defined as a function!

Awesome. How does this work? We’ve defined functions for == and < , so Swift is now able to infer the other cases as well; >=, < =, > and !=. Lets check if our tests still run.

Green!

Remember we still have one commented test. Lets uncomment it. You probably already figured now how to make this test pass; we have to adopt Comparable on Hand again. It’s slightly different from the Equatable function; we’re only interested in cases where the ranks are different, hence we check if two cards have the same rank, and if so, we continue.

Note that we actually have to compare rank (lhsCard.rank == rhsCard.rank), as our == function on Card also compares suit, and would give false where the ranks are the same but the suits are not. If they’re not the same, then we return lhsCard < rhsCard. If all cards are the same, then < is obviously false:

And our test passes! Great!

We’ve covered a lot again, making use of zip and sorted(by:) and implementing Comparable to make things easier for us. Next time we’re going a bit further to see if we can detect any other hand strengths as well, like Pairs, Straights and Flushes.

First steps with Swift: Drawing from the deck

So previously we’ve created a simple deck of cards. Now its time to go a bit further and actually do something useful with those. Lets add the Hand!

We’re still doing the kata, of which the rules say the following about a hand:

A poker hand consists of 5 cards dealt from the deck

Cool, so cards are dealt from the deck! Bet you didn’t saw that one coming 🙂 How do we capture this in a test?

What we can do is test if the number of cards go down when we draw a card. Let’s take our singleDeck() of cards, draw a card, and test if the amount of cards go down:

How would we make that test pass? Easy enough:

Oh wait! Remember from the previous blog post that when we are mutating, we should use ‘var’ and not ‘let’ right? The compiler will tell us that cardsInPile is immutable, so let’s change it to var.

Now, we don’t get a card back, let alone test if that card is actually removed from the deck. It’s not very useful yet. Let’s try to improve on that by writing another test, that allows us to verify if a card is still in the deck or not.

Next, our implementation, which is pretty straightforward. Array has a contains function which takes a closure which provides an element and returns a boolean:

We can simplify this by refactoring a bit. We can actually make use of a protocol called Equatable. If we make Card adopt Equatable, we can move this piece of code there. Lets create an extension on Card and adopt Equatable:

XCode will give an error, and will tell us to implement the curious looking function ==(lhs: Card, rhs: Card) -> Bool. How cool is this!? We can actually define the == operator for our Card!

Having implemented this, we can now simplify our contains function:

Cool! Now we can also check if the card we’ve drawn is no longer in the deck:

For that to work we need to rewrite our drawCard() method a bit, as we now need to return a card. Theres a little caveat, because what if the deck has been emptied? Lucky we can define this in Swift, returning an optional Card (Card?). When we don’t have any cards, we just return nil, else we return the card we remove:

Our test needs to deal with this as well. Our card is now of type Card?, not Card. The contains method takes a Card, so how do we match that up? There are two ways to do it; the safe way and the unsafe way. Since this is a test, we want a failure as soon as possible, so we’ll go with the unsafe way; we force cast our optional Card? to a Card by using an exclamation mark:

Great! The test passes! We’ll discuss how to go about optionals in a safe way later, as force casting an optional that is nil will result in a crash. Something we would really like to avoid in our real application.

Note that the compiler currently warns us that for the testDrawCard() test, the result of call to ‘drawRandomCard()’ is unused. We can easily fix this by prefixing the method with @discardableResult:

Running the test again will now no longer show the compiler warning, awesome!

So let’s recap. We can draw a card and check if a card is in the deck (or not), but we still always get the first card that is still in the deck. We would first get a ♦️2, then ♦️3, etc. To get a random card, we need to either randomise our draws or shuffle our deck. Intuitively, randomising our draws seems least effort. We just pick a random number the size of the deck and take that card out of the array. But how would we test it? Random does imply that you don’t know which card comes next, right? Well, we can go around that by using the same seed for the random number generator in our test. We’re going to utilise GKARC4RandomSource and as you can see, it takes a Data object as a seed. Let’s define our test:

Let’s see if we can change the code to accommodate this. Our singleDeck() method doesn’t change much, we add a seed parameter of type Data?, and we default it to nil:

Next, we add the seed parameter to the initialiser, also defaulting to nil. We then add a property randomNumberGenerator of type GKARC4RandomSource, which we create in the initialiser using the seed. The so-called nil coalescing operator (??) picks between our optional parameter or the current date if our optional parameter is nil:

Finally, we are going to change our drawCard() method. We ask the random number generator for a new Int at every draw. Notice that we pass in an upper bound that is the size of the array of cards, this makes sure that we pick a number in the right range, and not for example 53 while our deck is only 52 cards:

And now the test passes again, great!

But how do I knew what cards to check against? I didn’t. I tried the test and printed randomCards to see what the outcome was, which arguably isn’t that good of strategy. So how can we make sure it’s actually random? We could try different seeds and check if the cards are different:

Pfew, the test passes, nice! Testing for random is generally not a good idea, as you can never know what to test against. There are some techniques to help test code that use random numbers, but that involves a more advanced technique called mocking. I probably won’t cover mocking in this series.

That is it for today! As you can see, we took some smaller steps and some bigger steps. TDD is all about thinking up that next step. If you feel confident, you can take a bigger step. If you feel that you’re not in control or working on something intricate, you can choose to take smaller steps. Meanwhile, we’re getting to know Swift better and better.

Next time we’re going to take a look at how we can evaluate hands of cards!