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()
        elif button != None:
            score = score - 1
            print "Wrong!"
        time.sleep(0.1)

    print "Your final score is", score

options = {22:"A", 23:"B", 24:"C", 25:"D"}

if __name__ == "__main__":
    play(30)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.216.254