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:

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!

First steps with Swift: Representing cards in a deck

Earlier I talked about the poker hands kata to practice our coding. Today we’re going to start easy.
Here is the first line in the rules:

A poker deck contains 52 cards – each card has a suit which is one of clubs, diamonds, hearts, or spades (denoted C, D, H, and S in the input data). Each card also has a value which is one of 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace (denoted 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, A). For scoring purposes, the suits are unordered while the values are ordered as given above, with 2 being the lowest and ace the highest value.

I’ve annotated the rules, and put the main concepts in bold. These are Deck, Card, Suit and Value. So how can we represent these? A Deck obviously consists of Cards, and each Card always has both a Suit and a Value.

Cards

Lets talk about Cards first! We have 52 unique cards, and thus we note that there is a limit to the amount different values a Suit and a Value can have. We only have four possible Suits, and of each Suit we only have thirteen different Values. We could have each Suit and Value represented by an Integer. Say for Suit we have the numbers 0-3. What happens if we accidentally create a card with a Suit outside this range? Is it then invalid, or are we going to modulo to make it work? We would need a lot of extra code to deal with these edge cases, just to make our code reliable. Lucky we don’t have to, as Swift provides us with a concept in which we can limit the amount of values to exactly the amount we need, using Enums.

Enums in Swift are, opposed to in Objective-C, one of the core concepts (or first class citizens as we call them), next to classes, structs and functions. While Integer can represent any number from 0 to 18.446.744.073.709.551.615, enums can have only as much different values as defined by the enum cases. This is useful, because we then don’t have to care if a certain value is invalid or not, or how to deal with such cases otherwise. Having a finite number of possible values makes Suit and Value ideal enum candidates.

Lets start off first by creating a Single View project, and don’t forget to add the test target. Since it’s a kata we follow the rules of TDD, and thus we start by writing our first failing test:

We create a Card which is initialised by a Suit and a Rank, and we test if the Suit is what we expect, being a Diamond. We run the test and it fails, because we haven’t implemented anything yet. So what do we need to implement this? Lets start off by creating a Card:

So do we have everything we need? Lets run the test again. It fails, because we still haven’t defined Suit and Rank. Lets do that as well:

Lets try our test again. It passes! Awesome.

Deck

Lets continue building on this, here is our new failing test in which we create an empty deck. We expect the number of cards to be 0.

To make it work, we need to create a deck, and have a computed property totalNumberOfCards that returns 0. Let’s create it. Computed properties don’t hold any value, they’re always computed and thus have a body. They’re actually very similar to a function/method. There are no rules for when you should use a computed property and when a function. My tip: as soon as there is some complicated logic going on, you might just want to have a function. That conveys that its not just a property, and that there is more to it than just returning a value.
Also note that computed properties are always ‘var’. We’ve only used ‘let’ until now, so I need to explain this further. ‘let’ means that the value or variable cannot change, i.e. mutate. ‘var’ means variable (obviously), so it is either computed or can be changed. We’ll see some more of ‘var’ later.

Great! The tests pass again. Note that we only did the most limited change possible to make the test work. This is important to realise.
Of course a deck should also hold cards, so let’s make that work as well. Let’s add a test for that:

We need to change a few things to make it work. First of all, we will need an initialiser that takes an array of cards. Second, we need to store the array of cards and let totalNumberOfCards return the amount of cards in the array. Our Deck is going to look like this:

Pass!
Finally, we want to have a deck of 52 cards. It is going to be a bit of a hassle to create every card in the code manually, so lets write a convenience method for it. First the test:

Then the implementation. To make it easier to instantiate all the different cards we need, we need something convenient. What if we could create a loop? Unfortunately we cannot just ask the enum to loop over all of its cases. If only they could be Ints instead, then it would be easy right? Swift has a way to accomplish that. We can back an enum by an Int as such:

We do the same for Rank, and we make sure that Two = 2, so that all the following cases have the correct value. Ace will have value 14. That also makes us check off the rule that the values are ordered as given above, with 2 being the lowest and ace the highest value.

The addition of the Int backing also gives us a failable initialiser for the enum: init?(rawValue: Int). Initialising a Suit with a rawValue gives us either a valid Suit or nil, which is captured in a concept called Optional. Actually Optional is an enum by itself and conforms to ExpressibleByNilLiteral, so that .none returns nil:

On to our Deck class, we add a class func singleDeck(), which creates an array of cards, and fills them using the values we’ve just set on our Int backed enums. We also need to change our Deck from a struct to a class because of this:

Green!
Remember we talked about how ‘var’ allows for the variable to change? Here’s a perfect local example. We initialise an empty cards array and by looping over it we add new cards to the array, therefore mutating the cards array.
There is a rule to using var though; we only make a property or variable var, if we actually mutate. The compiler is really great and will help in this by informing you that you’ve used a ‘var’ but no mutation took place, and that you should be using a ‘let’ instead.

Thats it for now!
Next time, we’ll go into drawing cards from the deck!

Prologue to first steps with Swift

It has already been like 6 months since I announced I would make a fresh start given I would have to make some time for it. Lets do it!

Swift 2.1 got introduced a week or two ago, and the time comes closer that we are going to drop Objective-C in favour of it. You might wonder why the heck after a year of Swift we are still using Objective-C, but the answer is quite simple. Given that we have a large user base, we still provide extensive support for iOS 7 on all of our apps. They share a large code base in multiple static libraries. As you might know, you can’t really pack swift code in static libraries, and dynamic frameworks only came available in iOS 8 (There is of course the CocoaPods workaround, but we’ve decided against using it). We couldn’t therefore afford to abandon Objective-C just yet. As iOS 9 adoption rate grows and that of iOS 7 dwindles though, the time draws closer to finally drop iOS 7 support and leap into the future.

So here we are. Lets start with Swift!

Before we start, we are going to have to think up a project. Most people would probably make some kind of example app, but not me. I’ve been reading The Clean Coder (I’ll do a post on some nice new books i’ve read soon) by Uncle Bob Martin a while ago, and he proposed to do coding katas on a regular basis to hone your programming skills. The idea is presumably first coined by one of the writers of another quite famous book, The Pragmatic Programmer. There are a few websites that collect katas, and there are those that go a step further and build a whole suite around them. One I have to mention is Code Wars, which has literally dozens and dozens, provides a ranking and honour system, and allows you to take it up against others as well in the process.

For now, we’ll do with picking one from Coding Dojo and start with the Poker Hands Kata. In the next post we’ll start coding.

Hiatus and Future

Im aware I’ve left this blog bare for the previous few years. I’ve decided it is high time to do something with it again.

I’ve been working in the mobile industry for the past few years, so I have some new ideas for topics regarding iOS development mainly, and Android development secondly. Next, we are currently deploying scrum in our organisation, so i’ll give some insights in how that works. Furthermore I’ve been exploring some new hobbies, so expect some posts on board games, running, cycling and hiking.

Enough to talk about, now lets find the time to write it down as well 😉

/MrJre out

Global Game Jam – Tips from the trenches

So last week I’ve been participating in this years global game jam with theme ‘extinction’. The location here in the Netherlands being the HKU in Hilversum, having over 140 participants in total. I was invited by the people of Digital Dreams Games since they needed a second programmer on the team. The game we created is called FYI (see here and here for downloads and more info), and is a platformer puzzler game based around the concept of infographics. Every action you do in the game affects the platform elements in the game (bar graphs, circle graphs etc), so the trick is to do all the correct actions such that all the elements are in their right state (with bar graphs its having them at correct heights for example) to finish a level.

During the 48 hours we made the game, we did some things right and we did some things that we could have done better in retrospect, so I decided on a quick writeup for some obvious tips.

– Throw away your first three designs. This is one tip that the organization proposed as well and i think that really worked out well for us. The idea is that the first three ideas you are going to have, are also the ideas that other people are going to have and are therefore not original enough to be used.

– Make sure you have a good source control system in place. Source control can benefit greatly to the production efficiency, so be sure to use it. We used dropbox as our tool, which was not the best choice to make as it has no version history and no merging capabilities. This arguably cost us a considerable amount of time, since effectively we couldn’t work in the same files at the same time, and face overwrites of files on previously made changes.

– Have a good assets pipeline. If you start on building a game, make sure that when you have finalized assets that they can be placed into the game immediately without intervention of other people. This means first of all that the team has to decide what kind of assets are needed and in what format, size and orientation they will have to be. Take empty space into account when you are using sprites; as an artist think what the asset is supposed to be doing. The programmer needs to have the piece of code to use that asset into place using placeholder graphics such that the only thing that has to be done is replace the assets when they are ready, which the artist should be able to do just by overwriting the placeholder. The next thing to do is have all variables in a separate class such that they can be adjusted easily also by a game designer. Make sure you don’t hard-code levels into your game for the same reason.

– Don’t manically code stuff together with all kinds of pieces from earlier projects because of the time constraints. Honestly, piecing together sections of code from other games is just as fast as coding from scratch, but causes the game code to be chaotic, bloated and incomprehensible quite fast. Try to setup your code base similar to how you would normally do, add structure and try to keep everything as tidy as possible without spending a lot of time on it. If you want to use previously written code, set it up in such a way that it can be easily integrated for example by making it a library.

– Have a clear idea on what needs to be done. It is really an obvious tip, but in the hectic hours of the jam this is easily neglected. Have a board up with post-its, a site to track those things or something similar. It will ease communications and have a positive effect on production efficiency as you can easily prioritize TODO features, see who’s working on what and so on. Also don’t have long arguments on how things should be looking, and don’t spend a lot of time on changing things that had been finalized unless it is absolutely necessary.

– Get sleep and eat healthy. Even if its only 48 hours, even having four or five hours of sleep a night will help you to see things clearer, and makes you work more effectively then when not sleeping at all. It was really a disappointment to see the organization serve french fries and other fried junkfood the first day as if it is inherent to the whole thing. Eating fruit and veggies and drinking fruit juice are a better option always 😉

– Utilize the knowledge available in other teams. It may sound a bit odd, but ask other teams in the event for quick advice when you’re stuck on a problem as it can save you precious time.

I’m sure there are plenty more tips to go around, but these are the most obvious ones in my opinion 😉 All-in-all it was a really cool experience to participate in the global game jam, i really encourage people both veterans, starters and students to participate and make cool games together. The organization did well, and breakfast and lunch at least were up to spec 😉