This post follows on from the previous one on union types, by showing how to use state classes to implement a Tic-Tac-Toe game (a.k.a. Noughts and Crosses here in the UK).
Background
I ran across two mentions of the game of Tic-Tac-Toe recently. First, in the excellent book “Professional Enterprise .NET” by Jon Arking and Scott Millett, chapter 4 describes using TDD for Tic-Tac-Toe.
Secondly, Tony Morris wrote a post a while back that he almost called “What to Solve Before Expecting Me to Take Your Opinions of Static Typing Seriously” in which he describes his disappointment that most programmers couldn’t implement a robust API for a trivial game like Tic-Tac-Toe.
An extremely robust API for a relatively trivial problem … was achieved by exploiting techniques available from static typing and functional programming.
[This] appears to be difficult for many programmers to reproduce.
Here is a paraphase of some of his requirements for the API:
- If you write a function, I must be able to call it with the same arguments and always get the same results.
- If I, as a client of your API, call one of your functions, I should always get a sensible result. Not null or an exception, etc.
- If I call
Move
on a tic-tac-toe board, but the game has finished, I should get a compile-time error. In other words, calling move on inappropriate game states is disallowed by the types themselves. - If I call
WhoWonOrDraw
on a tic-tac-toe board, but the game hasn’t yet finished, I get a compile-time error. - It is not possible to play out of turn.
So, before reading on, think about how you might do this in C# – can you meet the challenge!