Last night I stayed up a little late and got a human vs human, and a cpu vs cpu move working for tic-tac-toe. Today I worked on getting a medium mode up and running. After a long period of debating how to best implement a medium it clicked with me that the hard mode I had designed before implementing mini-max could work.

This implementation is a rule based implementation. I check to see if a win in the next turn is possible. If it is, the AI takes that move. If a win is not possible in the next move, it checks if a block is available and takes that instead. If the block is not available, it just chooses the first available move.

Tomorrow I’ll be working on the easy mode. My specifications for it are that it’d be fun for a child to play. The only way I can think of at the moment that’d be fun for a child to play is to make it random. I’m not sure how to test for random with any degree of accuracy, but I figured I can test if it is working as I intend for it to work.

My plan right now is to check all available moves, and create a function that selects one at random.

The rand-nth function seems like my best bet on implementing this. My available moves function filters out anything that is not a number (because if the space is occupied it gets a string “X” or “O”).

Rand-nth

The rand-nth function is an easy one to understand. It takes a single argument (a sequence) and picks a random item from it to display.

(rand-nth [1 2 3 4])
=> 3

(rand-nth [1 2 3 4])
=> 2

(rand-nth [1 2 3 4])
=> 3

(rand-nth [1 2 3 4])
=> 1

(rand-nth [1 2 3 4])
=> 4

If you look at the source code it does this very simply.

(defn rand-nth [coll]
      (nth coll (rand-int (count coll))))

All it does is count the collection, then produce a random integer in the range of the index with rand-int, and apply the nth (return item at that index) function to it.

Isn’t it fun that Clojure is written in Clojure?