Book Image

Raspberry Pi Projects for Kids (Second Edition)

By : Daniel Leonard Bates
Book Image

Raspberry Pi Projects for Kids (Second Edition)

By: Daniel Leonard Bates

Overview of this book

Table of Contents (14 chapters)

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...