Skip navigation
2014

In this blog post, we are going to create a hangman game powered by the Google App EngineHangman is a game where you are trying determine a secret word by guessing letters that might be in the word.

 

Hangman Cloud Backend

The first thing to do is to create a cloud service that returns back a random word that we can use as our secret word.  To do this, we first need a list of possible words to choose from.  Fortunately, there is such a list of all 109582 words in the English language.

 

After downloading that list, we can write a quick little python cloud application that chooses a random word and returns it to the caller:

This code segment is very much based on the Google App Engine Hello World example.  The code is actually very similar, but instead of returning “Hello World”, we return a random word to be used as the secret word in a game of hangman.

 

The biggest difference is the first section where we read in the text file (wordsEn.txt), and filter out any word that does not have at least four letters in it.  We filter out short words because they are not very fun to play a game of hangman with. After we have the word list, it is just a matter of picking a random index into the array and returning that word.

 

Running the application locally and publishing it to the cloud are both covered very well in the Hello World tutorial, so I won’t go into much detail here.  It requires another file to describe the application:

And then you can use the Google App Engine Launcher to run the application locally or publish (deploy) it to the cloud.

 

I published mine to http://hangman-riot.appspot.com/, so if you navigate there, you should see a random word in your browser:

hangman-riot.png

 

Hangman Client Application

Fortunately, there’s already a great implementation of hangman in python from InventWithPython.com. So, we’ll use that as a starting point and add in some logic to use the cloud as the source of the secret word.  The code can be downloaded from: http://inventwithpython.com/hangman.py

 

I suggest running this a few times before you modify it just to get a feel of how it works.

 

Now, there are two places that we need to modify.  First, we need to remove the list of built in words that the application comes with, and replace the getRandomWord function with an implementation that grabs the word from our hangman cloud backend:

word-diff.png

And then we need to add in a reference to the library that we are using the fetch the random word:

import-diff.png

That’s it!  The final version of the code can be found here.

 

For a detailed description of how the code works, check out the InventWithPython website.

 

Right now the code is set up to hit the google app engine instance that I created.  If you want to hit a locally running application, just change the URL to be:

 

http://localhost:8080

 

Running Hangman on the Raspberry Pi

The hangman client python program requires python 3 in order to run.  So, if you don’t already have that installed, install it with this command:

 

sudo apt-get install python3

 

Once that completes you can run the hangman program:

 

python3.2 hangman.py

 

That should do it. Good luck, the words can be pretty tricky!

The Raspberry Pi Model B+Raspberry Pi Model B+ has been with us for a few months now and there are a growing number of projects that make use of the extra GPIO pins.

 

B%2BLES.jpg

 

For this project we will look back to our childhood and bring a much loved game from our past into the future. The humble board game.

Board games have been a traditional family pastime for many generations but with the rise of computer games their novelty has started to dwindle. These card and paper based games have little to offer the children of today who have been brought up on a diet of downloadable content packs and gamer scores.

 

But what if we could take a game from yesteryear and adapt it using the Raspberry Pi?

 

15039632047_fe71e45672_z_d.jpg

Meet the latest interactive board game...Pythons and Resistors

 

This project is split into three parts

 

  • Assembling the board game
  • Assembling and testing the electronic components
  • Writing and testing the Python code

 

To build this project you will need the following equipment.

 

 

Game Rules

The board game is based on a simple snakes and ladders setup, with 100 squares in total via a grid of 10 x 10 squares. The object of the game is for 2 or more players to roll a dice and move their game piece to match the number given on the dice. If the player lands on a python's head, then they will slither down the game board to the tail of the Python. If the player lands on the bottom of a resistor then they will climb up the game board. The winner is the first player to reach square 100, which is at the top left of the board.

 

Board game assembly

The board game components consists of

 

  • The game board, printed on glossy photo paper
  • Sugru rubber game pieces
  • Neodymium magnets to trigger the reed switches
  • Spare components to decorate the game pieces.

 

board.png

 

Start by printing at least two copies of the game board as it is easy to make a mistake when assembling the game. While they are drying open a pack or two of Sugru. Sugru is a form of air curing rubber that starts life as a sticky ball with a similar consistency to blutack. Form the Sugru into the shape that you wish. When you are happy with the shape add about three neodymium magnets to the base of the piece ensuring that they are gripped firmly by the sugru. Also if you wish decorate the game pieces with spare components such as LED or resistors.

 

tT_2xSJDK4DX05QMNMF2lKi3Yv3JSx91_MVet2Xknxs=w900-h600-no

 

Assemble and test the hardware

With the game board and player pieces completed our focus turn to the wiring and components that are under the board.

 

Reed switch

At the head of every python and the base of every resistor we are going to place a reed switch on the underside of the game board. These reed switches will be triggered by the magnets inside of our game pieces. A reed switch is a tiny switch contained inside of a glass vial. The contacts that form the switch mechanism come normally open so a current does not flow through the switch. By placing a magnet near to the switch we can trigger the contacts to quickly make contact, with a small audible click / pop being heard when this is the case. When contact is made the current will flow through the switch and in this case the current will flow to a GPIO pin on the Raspberry Pi which has been configured to be an input and react when this happens.

The best place to start is by fixing the reed switches into place on the underside of the board. To easily locate the correct spot I used a magnet on the printed side to trigger the reed switch on the underside. Once found I simply used cellotape over the glass vial of the switch to fix it into place. Repeat this action for all of the reed switches for all of the pythons and resistors.

 

15101706357_93e287a4a2_z_d.jpg

 

Jumper leads

With the switches in place we must now attach jumper cables to each end of the reed switch component. In one end of the switch we will supply 3v3 power from the Raspberry Pi 3v3 pin and the other will be connected to the corresponding pin. It doesn't matter which side that you choose, just make a note of which side you will be using as the 3v3 supply as we will go into more detail on the wiring for this later in the guide. For these connections use a female to female jumper lead and slide the connections over each end of the reed switch then use cellotape to secure them firmly in place. Do this for all of the reed switches.

 

15101499099_9d104c6bae_z_d.jpg

reed switch.png

 

Wiring the 3v3

The Raspberry Pi can supply 3 volts, commonly referred to as 3v3 from multiple pins on the GPIO but because for this project there are more switches than there are 3v3 pins on the Raspberry Pi we must break out the supply using a breadboard. A breadboard is a great prototyping tool that enables components and circuits to be tested before soldering. Typically a breadboard has two sets of two rails which are on the outer most reaches of the board. These rails are marked + and – and refer to a positive voltage, in this case our 3v3 supply from the Pi and a negative voltage which is commonly called Ground, often shortened to GND. Any connection made on a rail is available to all of the holes in the same rail as the supply. So a 3v3 supply from the Pi connected to the + rail will be available to all other holes in the + rail. For this project we need to connect the 3v3 supply from our Raspberry Pi to the + rail of our breadboard. 3V3 is supplied via pin 1 of the Raspberry Pi, which is the top left pin nearest the micro SD card slot. Connect pin 1 of your Raspberry Pi to the breadboard, and then using Male to Male jumper leads connect the reed switch 3v3 connections to the + rail of the breadboard.

 

reed_switches.png

 

Connecting the switches to their respective GPIO pins

In this project we have used a number of reed switches which are triggered by magnets and supplied 3v3 from the Raspberry Pi. When a magnet is placed over the reed switch, the switch will close and supply 3v3 from the Pi, through the switch and back to the Pi via another wire connected to the other side of the reed switch. On the Raspberry Pi we will configure the receiving pins for each reed switch attached to each Python and resistor square to wait for a signal, in this case the voltage change and when it receives it will trigger an audio file to play. To connect our switches to their corresponding GPIO pin, please refer to the table below.

 

Connecting our push button

With the reed switches complete, we now need to install the push button that controls the roll of our dice. Our push button is connected from the 3v rail of our breadboard and to the GPIO 13 pin, which is pin 33 using the logical numbering layout. The best way to ensure a good connection is to solder the wires directly to the push button. If you can't solder it is easy to learn but should be attempted with an experienced maker and with safety equipment present. There are many great videos on Youtube to help your learning including one from Carrie Anne at the Raspberry Pi Foundation

You can wind the wire around the terminals of the button for a temporary "no solder" test

 

pushbutton.png

 

15265233526_0b4f26e803_z_d.jpg

 

Pythons

 

Board Square  Broadcom GPIO Numbering
3824
4725
688
997

 

Resistors

 

Board SquareBroadcom GPIO Numbering
1314
3915
6718
7223

 

GPIO.png

Wiring up our dice

Rather than use a traditional dice, we will build our own dice using 6 LED connected to the Raspberry Pi GPIO. The LED will light up to signify the roll of our dice, so if I roll a 3 then 3 of the LED will light up. The Raspberry Pi outputs 3.3v per GPIO pin which flows to the LED and will light it up rather brightly, but just like Roy Batty from Blade Runner "The light that burns twice as bright, lasts half as long" so we need to drop the voltage down using a resistor. For this project I chose to use 82 ohm resistors which run in line from the GPIO pin to the LED, dropping the voltage before it reaches the LED.

 

dice.png

 

For each of the LED that make up our dice, we need to complete the above connection, using a breadboard.

 

dice_LED.png

To connect each of the dice LED, use the above diagram as a guide, your wiring may vary depending on your breadboard.

The pins for each of the dice LED are as follows.

 

DiceBroadcom GPIO Numbering

1

12
216
320
421
55
66

Configure the software

For this project we are using Python a robust and easy to learn language that is well suited to the Raspberry Pi. Python enables our project to use the GPIO pins which connect to the components on the game board and this is achieved via an external library, one of a few that will be used in this project.

 

Libraries

A library is a collection of code that can be included inside of our project. Typically a library is one of the many thousands that have been written, tested and approved by the Python community, but you can easily make your own library for personal use. Using a library is achieved by importing the contents of the library into the application, and this happens as so.


 

 

Typically you will use libraries that are already installed with your version of Python, but in this project we will be using a library that is not installed as standard. Which is pygame.

 

Pygame is a library of functions that can be used to build games in Python. It includes functions to handle sprites, sounds, images and keyboard events. In this project we will use it to play sounds for the pythons and resistors.

 

In order to use this library we need to install it on our Raspberry Pi, and for that we need to install the Python package manager, called PIP. PIP will have the latest versions of the libraries but it does not come as standard on a fresh Raspbian install. To install PIP, open a new terminal by double clicking on the LXTerminal desktop icon, or navigating to the LXMenu > Accessories > LXTerminal.

 

In the terminal issue the following command and press enter


 

When prompted for a password type it in and press enter. It will take a few moments for pip to be installed on your system. When completed keep the terminal window open and enter the following command.

 

 

Pip will now install the pygame library for this project and once complete you are now free to close the terminal window. With all of the software dependencies met we can now focus on the Python code that controls our game.

 

Python Code

When working in Python I like to use a set format for my code and that is as follows

 

Imports

Variables

Configurations

Functions (if any)

Main body of the code

 

And for this project I have followed that format.

 

Imports

Importing libraries is a vital skill to learn. It enables code written by others to be easily used in our projects. Giving us the convenience of growing our code with out the need to build concepts such as random numbers, GPIO functionality and GUI interfaces.

In the code we firstly import the libraries that are needed, and in the code snippet below I have added comments to explain what each import achieves.

 

 

With these imports completed we now need to create the variables that will contain the position of the resistors and Pythons on the board and their GPIO pin reference, the sounds used in the game , the GPIO pins used for each of the LED for our dice and also the GPIO pin used for the push button that triggers our dice.

 

 

Next we configure both Pygame and the GPIO pins that are used in the game. Pygame requires us to initialise both the actual library and the mixer functions and it looks like this

 

 

The GPIO configuration needs us to set the board layout, we can use the physical pin layout, where pin 1 is at the top left of the board, next to the micro SD slot. This is an easy layout to use and is great for beginners. For this article we will use the official Broadcom pin mapping, which is not a logical numbering system but is easy to use and is my preferred choice. To do this code.

 

 

Using the variables for the resistors and pythons that we created earlier we will now configure each of the pins to be an input, by which I mean that they will receive current when the switch is triggered. In order to protect the Raspberry Pi rather delicate GPIO we will be using an internal pull down resistor which buffers the pins to prevent any accidental damage.

 

 

With the inputs configured, we now do the same to the pins that make our digital dice, of which they are all output devices that receive power from the GPIO pins to make them light up.

 

 

Lastly on the setup we tell the pin used for d2 to turn off, as by default it is active and sending power out to any devices attached, we do this by doing the following.

 

 

Next we create a function which will handle the playback of the audio files used in the game. Our function takes an argument, which is the filename of the audio file. Once triggered the function loads the audio file into memory, and then plays the audio once per trigger. While the audio is playing the function checks to see if the audio is still playing and if so it waits until complete, before triggering again if needed.

 

 

Next we have a function which handles the roll of our digital dice. Once triggered it uses the random int function from the random library to pick a number between 1 and 6. Then using a series of conditional logic the number rolled is compared to each number 1 to 6 and when a match is found the corresponding LED are lit up, so if I roll a 5, 5 of the LED will light up.

 

 

Now we move to the final part of our code, this is the main body that is a series of if and else if conditional statements that look to see if any squares have been triggered or that the dice has been rolled. Once the trigger occurs, either the dice roll or audio file playback function is called and output via the Raspberry Pi.

 

 

And now we reach the end of this project. I hope that you have enjoyed yourself and learnt a little more about what the new B+ is capable of with just a few easy and cheap to purchase components.

The full code for this project, along with the image file for the game board is available via Github.

GERTBOARDS 25% OFF FOR A LIMITED TIME - BUY YOURS NOW! GERTBOARDS 25% OFF FOR A LIMITED TIME - BUY YOURS NOW!




Back in April, I wrote about how we build a job lot of Gertboard Experimenter Kits for the Design West exhibition and conference. In case you are interested in building the Experimenter Kit, I've put together this tutorial to help.

 

carefully-attaching-microswitches.jpg

 

Overview


The idea of the Experimenter Kit is that it expands the hardware on the Gertboard by giving young engineers a digitally controlled linear actuator, which responds to actions from a slider via software running on the Raspberry Pi. The setup is designed to be a basic version of a real life control system that you might find in an industrial environment. The software is largely based on the test programs written for the Gertboard and hence building this project helps you to learn about the Gertboard itself. Since this was built for an exhibition we added a nice laser cut box for the assembly to sit on, but of course you could just grab the components and wire them together. Building the kit is part of the fun, so I'd suggest having a go! If you are teaching a class, this is definitely a group project, as even though the setup is fairly simple, it would take one person quite a while...

 

I've included the actual CAD files for the box and I would encourage you to head to your local Hackerspace and get familiar with the laser cutter (the heroes at the Leeds Hackspace were very patient in helping me and my brother set up the cutter).

 

What you need


Gertboard

Raspberry Pi

SD card with Raspbian OS

Linear Actuator

Replacement Motors

Long Throw MicroswitchesLong Throw Microswitches

9V Battery

Battery Holder

PVC Tubing

Wire (the Gertboard comes with straps, but you may need extra to wire up the motor)

Slide Potentiometer

Nylon Standoff Spacers

3 mm & 5 mm bolts, washers & nuts

3 mm ply (I used 3.6 mm since that was all I could find at short notice. Most good hobby shops sell 3 mm birch ply which is of a good quality and doesn't tend to have so many knots)

 

Wiring

 

As an initial wiring setup you can follow this diagram, though please refer to Gert's user manual as different programs will require different wiring.

 

gertboard-wiring-diagram.jpg


Drawing the Box Template


You are more than welcome to use my drawings and improve upon or modify them as much as you want. I used Adobe Illustrator for the design, which was the only program I had access to which had the required accuracy.

I spent a lot of time getting the exact measurements from various datasheets for the footprint of components such as the slider and therefore they fit fairly precisely. However, we did need the occasional woodscrew in places. If you swap out components then you'll need to revise the design, but this might be a good chance to do a little bit of CAD!

 

You may have to change the size of the ramparts so that they match the thickness of the wood (or acrylic) you are using so that the pieces fit flush together. You can grab a free trial of Adobe Illustrator or use a free program such as Inkscape to edit the drawing.

If you want to just use my files, then you can find them in the attached .zip file:

 

laser_cut_gertboard_FINAL_back.ai

laser_cut_gertboard_FINAL_frontplate.ai

laser_cut_gertboard_FINAL_sides.ai

 

Laser Cutter Considerations


Some aspects of the box, such as labelling and logos are designed to be engraved rather than cut. In this mode, the laser will "scan" the surface much like a printer, engraving in a very precise way. However, this takes a significant amount of time, so depending on the required accuracy it can sometimes be better just to cut at a lower power. If you are building a one-off then a 30 minute wait isn't too bad, but otherwise it is worth thinking about this before you start. Another consideration is which way to orientate the wood in the cutter, so as to minimise the distance the laser travels on each run.

 

The early prototypes of the Experimenter Kit were designed to be cut on the HPC Laser LS-3020 which has a roughly A4 size cutting area. Depending on the size of the cutter you are using, you will need to spin the drawing around or separate it into different sections. The HPC used a proprietary piece of CAD software which required .dwg files. Exporting from Illustrator into this format loses the information about line thickness, so we had to reselect the areas to be cut or scanned. You can find information on the laser power and cutting speed here on the Leeds Hackspace Wiki. Later versions of the Kit were manufactured using the Epilog Helix 24 Laser Engraver at Fab Lab Airedale. Other than the larger cutting area (and its Terminator-esque 40 W range), the Epilog handily reads from a .pdf file so you are less limited by your CAD software. Simply changing the colour of the lines in the .pdf helps the laser cutter to identify which areas are to be scanned or cut.

 

Depending on the make, model and age of your cutter, a little trial and error is necessary, though here are some suggested settings from the Leeds Hackspace. Don't simply decrease the speed of the laser if it is not cutting as it tends to set fire to the wood which ranges from looking unsightly to being a serious fire hazard. Never leave the laser cutter unattended either for this reason.

 

N.B. If the cutter seems to be getting worse and worse at cutting, it is likely that the smoke from the wood has started to build up a residue on the mirror which reflects the laser beam downwards. This can be cleaned with a specialist solvent. Ask for help!

 

Here's one of our early versions being laser cut. Notice how we haven't quite got the power and speed right yet, as the "14" of element14 is pretty charred!

 

gert-kit-prototype-1.jpg

 

Assembly

 

Once you have managed to laser cut a baseboard for the kit, it should be fairly self-explanatory how the pieces fit together. I designed the box so that it could be slotted together simply and then glued, rather than a solution that held itself together naturally. This was because the kits had to travel across the Atlantic and then survive the classes. However, once you have the box assembled, attach the Raspberry Pi, using the 3 mm bolts, washers and nuts. It only really needs one central bolt to keep it in place as the next thing to do is attach the Gertboard, which stands up on nylon spacers. It should line up with the holes in the wood!

 

Now you need to modify the motor which drives the linear actuator. The motor which comes as standard drives the plastic actuator far too quickly and won't be very forgiving if your code is wrong! What you need to do instead is cut the shaft to free the motor and then attach the replacement, which is a geared motor and moves much more slowly, but with higher torque.

 

Be careful when you cut the shaft from the motor, as it can be pretty tough. Use a hacksaw (we used an angle grinder!). The best way to attach the new motor to the shaft is to use a short length of PVC pipe (or similar) and dab of superglue. Don't worry if it doesn't look totally aligned, the pipe will allow for some flexibility and the frame of the actuator will hold it steady. Before you reassemble the actuator, allow the glue to dry and then drill two new holes in the aluminium frame to line up with the bolt holes of the motor (roughly diagonally opposite each other).See the before and after pics below:

 

line-of-disassembled-motors.jpgmotor-glued.jpg

 

Next, attach the battery holder. Before going any further, solder as much of the hardware together as possible as shown in the diagram above without, for example, bolting down the switches. By doing this, you don't then have to fiddle about with a soldering iron in a tight space. If you need some tips on soldering, then Gert has made a video here which you can glean some tips from.

 

Once you have the microswitches wired up, bolt them in place and make the final connections to the Gertboard, motor and battery.

 

Finally, wire in the slider as shown in the diagram. Here it is best to solder the wires to the legs of the slider first and then thread them through the wood, pulling the wires back through the extra holes before attaching them to the Gertboard.


Test Software

 

Since the original kit was intended to be part of an interactive lesson, Gert put together a course document which provides "question" software and complete "answer" software which I've included in the attached file. However, you can also download the software for the Gertboard "as is" here.

 

His code allows you to program the motor, take readings from the position of the slider through the ADC and control the system in this way.

 

Connect up your Raspberry Pi to a monitor, Ethernet, mouse and keyboard and then power it up. You should be able to tidy the wires away into the holes which are positioned carefully on the box and feed them out the back of the kit to make the workspace a bit neater. Once your Pi has booted up, transfer the files to it. You could do this a couple of ways, but via a computer and an SSH connection is probably the easiest in this case. Once you have done this, run the examples as executables and open them up in an editor so that you can view the code at the same time. You can do this either from the desktop or from the command line.

 

The next step is to explore the demo code and attempt to fix the "questions"! Good luck.

Filter Blog

By date: By tag: