Code Kata: Bowling Game

Maybe you’ve heard that term before, or maybe you haven’t. When I was searching for the correct words for Code Kata definition, I’ve realised I should just copy them from a web page where you can find a lot of these exercises.

How do you get to be a great musician? It helps to know the theory, and to understand the mechanics of your instrument. It helps to have talent. But ultimately, greatness comes from practicing; applying the theory over and over again, using feedback to get better every time. (…) In software we do our practicing on the job, and that’s why we make mistakes on the job. We need to find ways of splitting the practice from the profession. We need practice sessions.

Those practice sessions shouldn’t be too long – they should take around 15-20 minutes. I believe you can find that amount of time even today.

Why this particular Kata?

There are a few reasons why I’ve picked this one:

  • it was made to practise test-driven development (red -> green -> refactor cycle)
  • it’s not listed in exercises
  • it reminds us to cover exceptions, but only a pair of them: strike and spare
  • it is short – we should implement only 2 public methods here:

If you’ll find below concept too hard – you can always look at my implementation on GitHub. But before you open this repository, just read next paragraph and try to do it by yourself.

Bowling game rules

It is easier to explain this on an example – that fancy card where you can put your score:

There are 3 rows: frames 1-10 for 21 rolls (3 in last), number of rolled pins, total score. The first is obvious. The second – if you do strike (knock all 10 bowling pins) you put X in the cell on right side of frame. Otherwise – you have 2 cells per frame to put number of knocked pins. If you manage to do spare (knock 10 pins in 2nd throw in frame) you put /. If you didn’t hit anything just put dash.

And here’s how to count score (you do this after whole game): 1st frame had strike – it allows you to add 2 more throws to this frame score. So it’s 10 for 1st frame and 9 and 1 from 2nd – 20 score in 1st frame. Now we move to 2nd frame. We have 9 + 1 points here. Since we managed to do spare – we can take 1st throw from 3rd frame and add to 2nd frame score. 9 + 1 + 5 = 15 and 20 points from 1st frame = 35 total. Thats almost everything you need to know.

There is also 10th frame that has 3 cells to fill. It is because if we do strike here – we still can add 2 more rolls. But we don’t have 11th frame so we’ll have to roll them to fill the card. If we do strike again on those extra rolls, we just ignore that. The same goes with spare (we can see it on this sample sheet). Player managed to roll 9 and 1, so he can add 1 more result. But since there is no 11th frame he has to throw the ball additional time. He was lucky and he did strike here, but since it’s extra throw he won’t get another bonus.

Good luck!