Tag Archive | "gaming"

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.

Posted in arduino, education, games, LCD-09363, lesson, microcontrollers, tutorialComments (4)

Project – Let’s make Electronic Dice

In this project we make electronic dice.

Updated 18/03/2013

In this article you can learn how to make an electronic die (die is the singular of dice), using an ATmega328 with Arduino bootloader and a few inexpensive components. The reason for doing this is to introduce another object that you can build, learn from and be proud of. It is a fairly simple procedure, and at the end you will have something that is useful for a long time to come. Again this article will be a design-narrative, so please read it in full before making a die yourself.

First of all, here is a photo of my finished product.

finishedssss1

Naturally the cosmetic design is up to you, I have used this box, LEDs and switches as they were already in my stock of parts. The die is quite a simple design – with a twist. Inside the unit is a mercury switch. This consists of a small glass tube with two wires at one end and a small amount of mercury. When the mercury rolls over the wires, they are shorted out. Just like a push button when it is pushed, for example:

tiltdemoss

 

We will make use of this switch to start the die “rolling” – to simulate the use of a non-electronic, under-engineered wooden die. For safety, I will be using a mercury switch that is enclosed with plastic:

tiltswitchss

Over the last few years several people have contacted me saying “don’t use mercury switches”. Fair enough, if you don’t want to either, use element-14  part number 540614.

First of all, the circuit is assembled on a breadboard using our Eleven Arduino-compatible board. There is no need to build the complete independent circuit yet, as we just want to test the aspects of the sketch, and try various LEDs out. I have some bright blue ones which match with the blue housing:

bboard1ss

There is a function in the sketch (below) called

which is used to display the numbers 1 to 6. The following video is a demonstration of this:

The sketch is quite simple – you can download it from here. Once the behaviour of the die met my expectation, I used my ZIF-socket programming board to upload the sketch into a nice fresh ATmega328 with bootloader. One could also add a piezo buzzer for sound effects, as described in sketch. This will end up being a birthday present for a young niece, so I have omitted the sound effects.

Next,  time to rebuild the circuit on the breadboard – using the bootrom and not our Eleven. Here is the schematic:

dieschematicss

and the resulting layout:

prototypess

And it works! Things are starting to come together now. As usual I was curious about the current draw, as this helps me determine how long the battery will last. On standby it draws between 10 and 20 milliamps, and between 30 and 40 milliamps when displaying numbers.

By now you probably would like to see it work, so here is the prototype demonstration:

Now it is your turn… from a hardware perspective, we will need the following:

  • IC1 – ATmega328 with Arduino bootloader programmed with the sketch
  • IC2 – LM78L05 voltage regulator – note that with the front facing you, pins are 1-output, 2-GND, 3-input
  • D1-D7 – LEDs of your choosing
  • R1, R9: 10 kilo ohm resistors
  • R2-R8: 560 ohm resistors
  • X1 – 16 MHz resonator – centre pin to ground, outside pins to IC1 pins 9 and 10
  • small piece of protoboard
  • SW1 – on/off button
  • SW2 – mercury tilt switch
  • 9V PP3 battery and snap
  • optional – 28-pin IC socket
  • a nice case, but not too large
  • some thin heatshrink
  • some sponge or insulating foam which has a width and length slightly larger than the protoboard

The ideal housing would be one that fits in the palm of your hand. However, such miniaturisation levels are quite difficult in the home workshop. The biggest problem (literally) was the power supply. The only battery with the voltage and a decent amp-hour rating was the 9V PP3. Alkaline models are usually good for 500 to 625 mAh, and should power the die for about ten hours of continuous use. Furthermore, whilst running the prototype on the breadboard, it would function down to 6 volts, however the LEDs were a little dim – but still perfectly usable. However I managed to squeeze it all in – sans the IC socket.

So if you are like me, and soldering the IC in directly – make sure you are happy with your sketch!

Anyhow, time to start the hardware work of assembly. Using veroboard/protoboard is easy if you plan things out first.

Remember – to fail to plan is to plan to fail

So in this case, I like to get some graph paper and draw out the tracks with a highlighter, such as:

templatess

My diagram shows the tracks as they would be on the rear of the veroboard. With this, using a pencil one can mark out component placement, links, and where to cut tracks if necessary. Those long lines are great for +5V and ground. Etcetera. When you have laid out the parts, go and have a break. Return and check your work, then fire up your iron and go!

Once completed you then have an easy to follow plan to solder along with. Here is the above example after I finished soldering:

after

After the soldering was completed, and the board checked for any shorts or poor-quality joints – it was time to have a clean-up and clear the mess away. Now it was time to stuff the whole lot into the housing… but it would be prudent to test the circuit beforehand. So I soldered in the tilt switch, and the battery snap, connected the battery – and it worked. Notice in the image below the placement of the centre LED – I have used some heatshrink over the legs to totally insulate them, and have it at the centre of the board:

almostdoness

Now to focus on the enclosure. In order to keep the costs down I used a box (and almost everything else) from my existing stock. It turned out to be a little small, but with some creative squeezing everything would fit. The PCB and battery are separated by a thin layer of anti-static foam, to prevent the possibility of the sharp edges of the PCB underside scratching the label of the battery and causing a short.

The final messy task was to drill the holes for the LEDs and the power switch. The switch was easy enough, just knock a small hole in then use a tapered reamer to get the exact size:

switchholess

Then to drill the holes in the lid for the LEDs to poke through. Easily done, just be sure to mark where you want the holes to be before drilling. Furthermore, you need to get the LEDs as far through the holes as possible:

ledsholess

Then the final step before sealing the lot up is to get the power wires soldered to the switch and the battery snap:

beforelidss

When you are putting everything in the box, make sure the tilt switch is tilted so that when the die is at rest, the tilt switch is laying in the off position. Otherwise the die will just merrily repeat forever until you turn it off.

finishedssss1

And of course, an action video:

Once again I hope that this demonstration has shown how easy it is for anyone with some spare time and the knowledge from my Arduino tutorials can create something from scratch.

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.

Posted in arduino, atmega328, dice, games, projects, tutorialComments (4)


Subscribe via email

Receive notifications of new posts by email.

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: