Building a Dice Game
Turning our rudimentary die into a full-blown game requires adding another
pushbutton. With the first one we can still roll the die, and with the second
one we can program a guess. When we roll the die again and the current
result equals our guess, the three LEDs on the die will blink. Otherwise, they
will remain dark.
To enter a guess, press the guess button the correct number of times. If you
think the next result will be a 3, press the guess button three times and then
press the start button.
To add another button to the circuit, do exactly the same thing as you did
for the first one. Figure 13, Our binary die now has a guess button, on page
56 shows that we have added yet another button circuit to the breadboard.
This time we’ve connected it to pin 5.
Now we need some code to control the new button. You might be tempted to
copy it from the previous program—after all, we copied the hardware design,
right? In the real world, some redundancy is totally acceptable, because you
actually need two physical buttons, even if they are the same in principle. In
the world of software, redundancy is a no-go, though, because it quickly leads
to maintenance hell. You should always make sure that every important piece
of information is represented only once in your program. Instead of copying
numbers, you should use constants. Instead of copying code, you should use
functions or classes. This way your code will become more compact and more
readable. As a bonus, it will be much easier to change your code, because
when you copy code you have to remember all the places you’ve copied it to
when you have to make a change. If you’ve isolated the code in a single place,
you have to change it only once.
So, we won’t copy our debounce logic, but we’ll use the Bounce2 library
1
that
was written for this purpose. Download the library
2
and unpack its contents
into
~/Documents/Arduino/libraries
(on a Mac) or
My Documents\Arduino\libraries
(on a
Windows machine). Usually that’s all you have to do, but it never hurts to
read the installation instructions and documentation on the web page.
Now that’s all done, our dice game is complete. Here’s the code of the final
version:
1.
https://github.com/thomasfredericks/Bounce-Arduino-Wiring
2.
https://github.com/thomasfredericks/Bounce-Arduino-Wiring/archive/master.zip
report erratum • discuss
Building a Dice Game • 55
www.it-ebooks.info