Skip to content

Commit bf4b6bf

Browse files
authored
Create code file for CPX Simon Guide
1 parent dd884f4 commit bf4b6bf

1 file changed

Lines changed: 106 additions & 0 deletions

File tree

CPX_Simon_Game/code.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import time
2+
import random
3+
from adafruit_circuitplayground.express import cpx
4+
5+
cpx.pixels.brightness = 0.1 # adjust NeoPixel brightness to your liking
6+
7+
REGION_LEDS = [
8+
[5, 6, 7], # yellow region
9+
[2, 3, 4], # blue region
10+
[7, 8, 9], # red region
11+
[0, 1, 2], # green region
12+
]
13+
14+
REGION_COLOR = [
15+
(255, 255, 0), # yellow region
16+
(0, 0, 255), # blue region
17+
(255, 0, 0), # red region
18+
(0, 255, 0), # green region
19+
]
20+
21+
REGION_TONE = [
22+
252, # yellow region
23+
209, # blue region
24+
310, # red region
25+
415, # green region
26+
]
27+
28+
PAD_REGION = {
29+
'A1': 0, # yellow region
30+
'A2': 2, # red region
31+
'A3': 2, # red region
32+
'A4': 3, # green region
33+
'A5': 3, # green region
34+
'A6': 1, # blue region
35+
'A7': 1, # blue region
36+
}
37+
38+
def light_region(region, duration=1):
39+
# turn the LEDs for the selected region on
40+
for led in REGION_LEDS[region]:
41+
cpx.pixels[led] = REGION_COLOR[region]
42+
43+
# play a tone for the selected region
44+
cpx.start_tone(REGION_TONE[region]);
45+
46+
# wait the requested amount of time
47+
time.sleep(duration)
48+
49+
# stop the tone
50+
cpx.stop_tone()
51+
52+
# turn the LEDs for the selected region off
53+
for led in REGION_LEDS[region]:
54+
cpx.pixels[led] = (0, 0, 0)
55+
56+
def read_region(timeout=30):
57+
start_time = time.time()
58+
while time.time() - start_time < timeout:
59+
if cpx.touch_A1:
60+
return PAD_REGION['A1']
61+
elif cpx.touch_A2:
62+
return PAD_REGION['A2']
63+
elif cpx.touch_A3:
64+
return PAD_REGION['A3']
65+
elif cpx.touch_A4:
66+
return PAD_REGION['A4']
67+
elif cpx.touch_A5:
68+
return PAD_REGION['A5']
69+
elif cpx.touch_A6:
70+
return PAD_REGION['A6']
71+
elif cpx.touch_A7:
72+
return PAD_REGION['A7']
73+
74+
def play_sequence(sequence):
75+
duration = 1 - len(sequence) * 0.05
76+
if duration < 0.1:
77+
duration = 0.1
78+
for region in sequence:
79+
light_region(region, duration)
80+
81+
def read_sequence(sequence):
82+
for region in sequence:
83+
if read_region() != region:
84+
# the player made a mistake!
85+
return False
86+
light_region(region, 0.25)
87+
return True
88+
89+
def play_error():
90+
cpx.start_tone(160)
91+
time.sleep(1)
92+
cpx.stop_tone()
93+
94+
def play_game():
95+
sequence = []
96+
while True:
97+
sequence.append(random.randint(0, 3))
98+
play_sequence(sequence)
99+
if not read_sequence(sequence):
100+
# game over
101+
play_error()
102+
break
103+
time.sleep(1)
104+
105+
while True:
106+
play_game()

0 commit comments

Comments
 (0)