Skip to content

Instantly share code, notes, and snippets.

@JeffersGlass

JeffersGlass/reaction_game.py Secret

Created Aug 30, 2020
Embed
What would you like to do?
from gpiozero import Button, LED
from time import sleep, time
from random import random, seed
from sys import exit
seed()
greenLed = LED(12)
greenLed.off()
yellowLed = LED(21)
yellowLed.off()
redLed = LED(20)
redLed.off()
myButton = Button(16)
#-----Behavior Variables----
minPauseTime = 1.5
maxPauseTime = 6
maxTriggerTime = 2
#-----Stats Variables------
roundsCompleted = 0
#----------
def allOff():
redLed.off()
yellowLed.off()
greenLed.off()
def gameOver(msg = None):
print ("You completed " + str(roundsCompleted) + " rounds. Congrats!")
if msg != None: print(str(msg))
sleep(1)
allOff()
exit()
allOff()
print ("Welcome to the game!")
print ("When you see the GREEN LED turn on, press your button!")
print ("If you take too long, or press the button for any other LED, you lose!")
print ("-")
print ("Press the button when you're ready to begin")
while not myButton.is_pressed:
pass
print ("Starting in 3...")
sleep(1)
print ("2...")
sleep(1)
print ("1...")
sleep(1)
print ("GO!")
while True:
startTime = time()
pauseTime = random() * (maxPauseTime - minPauseTime) + minPauseTime
allOff()
roundWon = False
#watch for a button press in case the user presses th ebutton too early)
while (time() < startTime + pauseTime):
if myButton.is_pressed: gameOver("Pressed button too soon")
onTime = time()
#Green button lights up:
if random() < .33:
greenLed.on()
while (time() < onTime + maxTriggerTime):
if myButton.is_pressed:
roundsCompleted += 1
roundWon = True
break
if roundWon == False:
gameOver("Missed the green LED")
#some other LED lights up:
else:
if random() < .5:
led = yellowLed
else:
led = redLed
led.on()
while (time() < onTime + maxTriggerTime):
if myButton.is_pressed: gameOver("Wrong LED Color")
roundsCompleted += 1
roundWon = True
print("End of Game")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.