Arduino Game: Tic-Tac-Toe

[Updated 19/02/2013]

Let’s recreate the game of Tic-tac-toe with our Arduino systems. This game is also known as Noughts and Crosses or Three-in-a-row. Whatever we call it, I’m sure you will be familiar with the game from your childhood or general messing about. For the uninitiated, there is an excellent explanation of the game over at Wikipedia.

tttboard

In the following examples, a human will play against the machine (Arduino). The demonstration sketches are almost identical except for one function – machineMove();. This function contains the method of deciding a move for the machine. By localising the machine’s decision making into that function we can experiment with levels of intelligence without worrying about the rest of the sketch. In writing this article it is assumed the reader has some basic Arduino or programming experience. If not, perhaps read some of my Arduino tutorials indexed here.

However first we will examine the hardware. I have used my well-worn Freetronics Eleven board, which is equivalent to the Arduino Uno. For a display, the Sparkfun LCD shield is used. For user input we have two buttons connected to digital pins 6 and 7, using 10k pull-down resistors as normal. The buttons are wired via a ScrewShield set. To save time I have used my generic button-board, whose schematic is below:

example12p3schematic

 

If you were to construct a more permanent example, this could be easily done. One could possibly use a DS touch-screen over their LCD. Perhaps for mark II? Nevertheless, time to move on. Now to explain how the sketch works – please download a copy from here so you can follow along with the explanation.

I have tried to make the sketch as modular as possible to make it easy to follow and modify. The sketch itself is relatively simple. We use an array board[] to map the pieces of the game board in memory – board[0] being the top-left and board[8] being the bottom-right position. We create a graphical representation of the board by drawing rectangles for the horizontal and vertical lines, lines to form crosses, and circles for … circles. The function drawBoard(); takes care of the board lines and calls drawPiece(); to place the players’ pieces. drawBoard(); reads the board[] array to determine if a position is blank (zero), a nought (1) or a cross (2).

The flow of the sketch is easy to follow. First the function introScreen() is called – it displays the introductory screen. Then drawBoard() is called to draw the initially-blank game board. Then the main function playGame(); is called. We have a global variable winner, whose value determine the winner of the game (0 – game still in play, 1 – human, 2 – machine, 3 – draw). playGame(); and other functions will refer to winner throughout the sketch. Within playGame();, the human and machine take turns placing their pieces. The function humanMove(); accepts the human’s choice in piece position, storing it into board[], and not allowing false moves. The function machineMove(); controls the decision-making process for the machine’s moves. In the first example, the machine moves by randomly selecting a board position. If the position is taken, another random position is selected (and so on) until a valid move can be made.

After each instance of humanMove(); and machineMove();, the function checkWinner(); is called. This function compares the contents of the array board[] against all possible scenarios for a win by either player, and calls the function drawTest(); – which checks for a draw – and stores the result in the variable winner as described earlier. Checking for a win is simple, however checking for a draw was a little more complex. This involves counting the number of 1s and 2s in the board[] array. If there are five 1s and four 2s or four 1s and five 2s ( in other words, the board is full) there is a draw. Easy!

If, after the function checkWinner(); is called, the varible winner >0 – then something to end the game has happened – either a win or a draw. This is determined using the switch…case function at the end of checkWinner();. At this point a function relative to the game status is called, each of which display the outcome and wait for the user to press button A to start a new game. At the end of each of these functions, we call the function clearBoard(); – which resets the array board[] and winner back to zero, ready for the next battle of wits.

Now for our first example in action. The function machineMove() is an example of the simplest form of play – the machine randomly selects blank positions on the board until the game ends. In the following video clip you can see this in action:

For the forthcoming examples, we will allow the choice of who moves first. This is accomplished with the function moveFirst(); which sets the variable whofirst to 1 for human first, or 2 for machine first. This is read by playGame() to determine the first move. Now let’s inject some strategy into our machineMove(); function to give the machine a slight edge above sheer randomness.

In the following example, the machine will first only use the centre or corners until those positions have been taken. This is accomplished by placing the position numbers into another array strategy1[]={0,2,4,6,8} which the machine will randomly select from until those positions are used.  Once all those positions have been filled, the machine will revert to random positioning to attempt a win. You can download this example sketch from here. Do you think the machine can win if allowed to move first? Let’s see what happens in the following video clip:

In the second example the player who moves first will generally have the advantage. From this point, how could we strengthen the machine’s level of intelligence to improve its strategy? If you have a better method, and can integrate it into the example sketch, and are happy to publish it under Creative Commons – email the sketch to john at tronixstuff dot com.

So there you have it, some variations on a classic game translated for our Arduino systems. I hope you found it interesting… or at least something different to read about.

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

The following two tabs change content below.

John Boxall

Founder, owner and managing editor of tronixstuff.com.

4 Responses to “Arduino Game: Tic-Tac-Toe”

  1. Scouris says:

    What a neat idea and implementation! How do you keep your head from exploding, with all these great ideas inside? =)

    • John Boxall says:

      Howdy
      Thanks for that. The process for deciding what to write about is quite difficult, usually a function of the stock here to use, what I can lay my hands on, how much it might cost, and the amount of time required to learn how to do something in order to be able to write about it. Plus I find a lot of things interesting that others do not, and vice versa. So around half of my posts are things I think others will enjoy, and the rest are purely selfish. At the end of the day the site is a public notebook of my goings-on.
      have fun
      john

  2. me says:

    hey man, how would i implement this using a pic 18f4550.

Trackbacks/Pingbacks


Leave a Reply

Receive notifications of new posts by email.

Arduino Tutorials

The Arduino Book

Arduino Workshop

Für unsere deutschen Freunde

Dla naszych polskich przyjaciół ...

Australian Electronics!

Buy and support Silicon Chip - Australia's only Electronics Magazine.

Use of our content…

%d bloggers like this: