Tic Tac Toe Bonanza - Part II

This post is a follow-up on the promise made previously which is the implementation in C# of a Tic Tac Toe algorithm often asked in an interview. I have already previously explained the algorithm therefore in this post I am going to focus just on the making of it.
The key aspects of the code are the initialization phase and the move chunk of code.
  public static void main() {
            player = new TttNums[2];
            player[0] = new TttNums("Toto");
            player[1] = new TttNums("Molly");

            int who = 1; //player numbers are 1 and 0
            board = new bool[10]; //only 1-9 are used

            for (int k = 0; k < 9 && player[0].isTrying() && player[1].isTrying(); k++)
                who = 1 - who;    //now it’s the other player’s turn
Many of the recorded pairs do not share the same row, column or diagonal (such as 8 and 9). Recording this information does not hurt our solution and is more efficient than incurring the overhead of testing each pair for collinearity.
        // Game playing strategy goes here - this version makes random moves
        public void move() {
            // make a random move
            int spot;
            { //find an empty board location
                spot = (int) new Random().Next(9) + 1;
            } while (board[spot]);

            Console.WriteLine(name + ": move to " + spot);
            if (pairs[15 - spot]) { //check for a win
                Console.WriteLine(name + "!!!WIN!!!");
                trying = false;
                for (int j = 1; j < 10; j++) {

                // update pairs array
                if (taken[j] && j + spot < 15) {
                    pairs[j + spot] = true;

                    // this helps you to understand what's going on in the back stage
                    Console.WriteLine(">>>>>>> " + name +"  setting " + (j+spot));
        taken[spot] = board[spot] = true;
If you write some code that you expect to rely on, don’t miss to write some unit testing. I know, I can feel your pain just in reading that sentence but experience demonstrate that is worth it. Always. For this particular exercise take a look at this article. It’s will give you enough guidance to understand the principle behind it.
The code for this article his hosted on GitHub, enjoy making it and also watching how the computer plays against itself :-)


Popular posts from this blog

Bring Boxee Box back to life

Postgres on Synology

Zen-inification - The art of decluttering