Thursday, 2 July 2015

Simon Says with Pimoroni ExplorerHat

The ExplorerHat was one of those impulse purchases from Pimoroni that I added to my basket when shopping for something else that I actually needed.  It has sat in my to-do box for a few weeks but recently I've found the time to have a play (I've been a bit busy coordinating my CodeClub's AstroPi project).

The ExplorerHat is a great test-bed for prototyping - having four buttons and LEDs all readily available means it's easy to knock together a test circuit without fiddling around  to wire up these simple and versatile components.

As a first project I thought I'd put together a Simon Says game.



The big LEDs flash in a sequence that gets longer and faster every time you successfully duplicate it by pressing the corresponding buttons on the ExplorerHat. If you get a sequence correct, all the lights flash in celebration!



Here's the wiring diagram:


And here's the (slightly rough and ready) code:

import explorerhat as eh
import time, random

target_seq = []
global user_seq 
user_seq = []
user_seq = []
leds_list = [1,2,3,4]


def wait_for_press(c,e):

if c > 4:
led = c - 5
else:
led = c - 1
if e == 'press':
eh.light[led].on()
else:
eh.light[led].off()
user_seq.append(led + 1)

print 'Starting. Copy the sequence.'
level = 0
GameOn = True
gap = 0.8
while GameOn:

user_seq = []

level+=1
count = 1
print 'Starting Level ' + str(level)
for i in  range(count):
led = random.choice(leds_list)
target_seq.append(led)

for seq_n in target_seq:
eh.output[seq_n-1].on()
time.sleep(gap)
eh.output[seq_n-1].off()
time.sleep(gap)

eh.touch.pressed(wait_for_press)
eh.touch.released(wait_for_press)
countdown = 20
waiting = True
while waiting:
if (len(user_seq) == len(target_seq)) or (countdown == 0):
if user_seq == target_seq:
waiting = False
#print user_seq, target_seq
time.sleep(0.5)
print 'Correct'
for x in range(0,4):
eh.output[x].on()
eh.light[x].on()
time.sleep(0.5)
for x in range(0,4):
eh.output[x].off()
eh.light[x].off()
gap = gap* 0.8
else:
waiting = False
GameOn = False
print 'Fail'
print 'You reached level:' + str(level) 

eh.pause()
time.sleep(1)
countdown-=1

time.sleep(2)


No comments:

Post a Comment