Reader small image

You're reading from  Raspberry Pi Projects for Kids (Second Edition)

Product typeBook
Published inApr 2015
Reading LevelBeginner
Publisher
ISBN-139781785281525
Edition1st Edition
Languages
Right arrow
Author (1)
Daniel Leonard Bates
Daniel Leonard Bates
author image
Daniel Leonard Bates

Daniel Bates is a computer science researcher at the University of Cambridge. His day job involves inventing designs for future mobile phone processors and when he gets home, he likes playing games or working on one of his coding projects (or both!). Daniel has been a volunteer for the Raspberry Pi Foundation since 2011 and is enthusiastic about introducing new people to computing. He has previously written Instant Minecraft: Pi Edition Coding How-to and Raspberry Pi Projects for Kids (First Edition), both published by Packt Publishing.
Read more about Daniel Leonard Bates

Right arrow

Chapter 5. Testing Your Speed

In this chapter, we're going to create a new game that will test how quickly the player can react. To do this, we will create our own game controller—something you can't easily do on a normal computer—and write a program that tells the Pi what to do when the controller's buttons are pressed.

If you do not have the components required to create the controller, an alternative program that uses the keyboard instead is provided at the end of the chapter. It is very similar to the default program, so it is still worth reading through this chapter to learn how everything works.

Materials needed to make your own controller


The materials that are required to make your own controller are shown in the following figure. Think about what you would like your controller to look like and how many buttons it should have, as this will determine how many of each item you will need:

The preceding figure shows the items we need to create a controller and the details are as follows:

  • Card (1) (as large as you want the controller to be)

  • Wires (2)

  • Paper fasteners (3) (2 x number of buttons)

  • Paper clips (4) (1 x number of buttons; each clip should be in plain metal with no coating around it)

  • Sticky tape (5)

  • Pens/pencils for decoration (6)

If you already have some electric switches you'd like to use, you will not need the paper fasteners, paper clips, or sticky tape, but I think it's more fun to make everything from scratch!

We also need a safe way to connect the wires to the Raspberry Pi. One approach is to use special male to female wires, which behave like normal wires at one end, but can...

Creating the game controller


In order to design a controller, we first need to know what sort of game is going to be played. I am going to explain how to make a game where the player is given a letter and they have to press the button of that letter as quickly as possible. They are then told another letter. The player has to hit as many buttons correctly as they can in a 30-second time limit.

There are many ways in which this game can be varied; instead of ordering the player to press a particular button, the game could ask the player a multiple-choice question, and instead of letters, the buttons could be labeled with Yes, No, Maybe, or different colors. You could give the player multiple commands in a sequence and make sure that they press all the buttons in the right order. It would even be possible to make a huge controller and treat it as more of a board game. I will leave the game design up to you, but I recommend that you follow the instructions in this chapter until the end and then...

Coding the game


Here's a quick recap of how this example game is going to work. The Raspberry Pi will choose a random button and ask the player to press it. Every time the player presses the correct button, they get a point, and every time they press a wrong button, they lose a point. Once the correct button has been pressed, the Raspberry Pi selects a new button as the target. The aim is to score as many points as possible in 30 seconds.

In Python 2, navigate to File | New Window. This will bring up a new empty Code Editor window, which is where all our code will go.

Random behavior

The first job, then, is to write some code that will choose a random button for the player to press. Take a look at the following code snippet:

import random
options = [22, 23, 24, 25]

def nexttarget():
    target = random.choice(options)
    print target
    return target

In the first line of the code, we import the random module, which we saw in the previous chapter, Chapter 4, Creating Random Insults.

In the second...

Complete code listing


The complete code listing section shows the complete program. This may be useful if you're not sure where the different code snippets should go, or if your program isn't working and you want to compare it to something that works:

import RPi.GPIO as GPIO
import random
import time

def preparepins():
    GPIO.setmode(GPIO.BCM)
    for pin in options.keys():
        GPIO.setup(pin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)

def nexttarget():
    target = random.choice(options.keys())
    print options[target]
    return target

def buttonpressed():
    for pin in options.keys():
        if GPIO.input(pin) == GPIO.HIGH:
            return pin
    else:
        return None

def play(duration):
    preparepins()

    start = time.time()
    end = start + duration
    score = 0

    target = nexttarget()
    while time.time() < end:
        button = buttonpressed()
        if button == target:
            score = score + 1
            print "Correct!"
            target = nexttarget...

The keyboard version


If you do not have access to the components necessary to create your own controller, here is a slightly modified program that uses the keyboard instead. You might notice that its structure is exactly the same as the previous program. Separating tasks into different functions allows us to make changes like these quickly and easily:

import pygame, pygame.event, pygame.key
from pygame.locals import *
import random
import time

def prepare():
    pygame.init()
    screen = pygame.display.set_mode((250, 1))
    pygame.display.set_caption("Test your speed!")

def nexttarget():
    target = random.choice(options.keys())
    print options[target]
    return target

def keypressed():
    pygame.event.pump()
    keyspressed = pygame.key.get_pressed()
    for key in options.keys():
        if keyspressed[key]:
            return key
    else:
        return None

def play(duration):
    prepare()

    start = time.time()
    end = start + duration
    score = 0

    target = nexttarget...

What's next?


Now that your game is working, you might like to try using most of the same code to create different games (I suggest that if you make changes, save it to a different file, so that you don't lose your current game). In particular, you could change nexttarget() so that it asks a question and gives some possible answers, and the player has to choose an answer as quickly as possible. Alternatively, you could create a Simon Says style game, where the game gives a sequence of buttons that must be pressed and the player tries to repeat it.

If you have an Internet connection and are feeling adventurous, you could try using your controller to play your Angry Birds game, as shown in Chapter 3, Making Your Own Angry Birds Game. Search the Internet for ScratchGPIO to download an enhanced version of Scratch, and try to explore how it can interact with the Raspberry Pi's GPIO pins.

If you're interested in learning more about electronics and what you can do with GPIO, take a look at Adafruit...

Summary


In this chapter, we used the Python programming language to create a game. We created an electronic circuit to act as the game controller, and used code to detect when the buttons were being pressed. We revisited the basics of the Python language, and saw how separating the code into multiple functions makes it more flexible and easier to manage.

In the next chapter, we will build on this Python knowledge to create an interactive map.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Raspberry Pi Projects for Kids (Second Edition)
Published in: Apr 2015Publisher: ISBN-13: 9781785281525
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Daniel Leonard Bates

Daniel Bates is a computer science researcher at the University of Cambridge. His day job involves inventing designs for future mobile phone processors and when he gets home, he likes playing games or working on one of his coding projects (or both!). Daniel has been a volunteer for the Raspberry Pi Foundation since 2011 and is enthusiastic about introducing new people to computing. He has previously written Instant Minecraft: Pi Edition Coding How-to and Raspberry Pi Projects for Kids (First Edition), both published by Packt Publishing.
Read more about Daniel Leonard Bates