The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

148 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


def pressed(button):
print(str(button.pin.number) + " won the game")

Remember that Python uses indentation to know which lines are part of your function;
Thonny will automatically indent the second line for you. Finally, add the following two lines
to detect the players pressing the buttons – remembering that they must not be indented, or
Python will treat them as part of your function.

right_button.when_pressed = pressed
left_button.when_pressed = pressed

Run your program, and this time try to press one of the two buttons as soon as the LED goes
out. You’ll see a message for the first button to be pushed printed to the Python shell at the
bottom of the Thonny window. Unfortunately, you’ll also see messages for each time either
button is pushed – and they use the pin number rather than a friendly name for the button.
To fix that, start by asking the players for their names. Underneath the line from random
import uniform, type the following:

left_name = input("Left player name is ")
right_name = input("Right player name is ")

Go back to your function and replace the line print(str(button.pin.number) + "
won the game") with:

if button.pin.number == 14 :
print (left_name + " won the game")
else:
print(right_name + " won the game")

Click the Run button, then type the names of both players into the Python shell area. When
you press the button this time, remembering to do it as quickly as you can after the LED goes
out, you’ll see that the player name is printed instead of the pin number.
To fix the problem of all button presses being reported as having won, you’ll need to add
a new function from the sys – short for system – library: exit. Under the last import line,
type the following:

from os import _exit

Then at the end of your function, under the line print(right_name + " won the
game"), type the following:
Free download pdf