from machine import Pin
import time
import random
# Define GPIO pins for LEDs and buttons
led_pins = [0, 1, 2, 3] # Example pins, adjust as needed
button_pins = [4, 5, 6, 7] # Example pins, adjust as needed
# Initialize LED pins as outputs
leds = [Pin(pin, Pin.OUT) for pin in led_pins]
# Initialize button pins as inputs with pull-up resistors
buttons = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in button_pins]
# Define colors
colors = ['red', 'green', 'blue', 'yellow']
# Function to light up LED and wait for a short duration
def light_up(index):
leds[index].on()
time.sleep(0.5)
leds[index].off()
time.sleep(0.1)
# Function to play a round of Simon Says
def play_round():
sequence = []
for _ in range(5): # Repeat 5 times for a 5-step sequence
sequence.append(random.choice(colors))
print(sequence)
# Display the sequence
for color in sequence:
index = colors.index(color)
light_up(index)
'''
# Check player input
for color in sequence:
index = colors.index(color)
while True:
if not buttons[index].value(): # If button is pressed
print("Button",index)
while not buttons[index].value(): # Wait for button release
pass
break
time.sleep(0.1)
'''
# Check player's input against the sequence
for color in sequence:
index = colors.index(color)
matched = 0
print("Sequence color", color)
while True:
for btpin in button_pins:
btindex = button_pins.index(btpin)
if not buttons[btindex].value(): # If button is pressed
while not buttons[btindex].value(): # Wait for button release
print("Button release", colors[btindex],color)
if(colors[btindex] == color):
print("Matched")
matched = 1
break
else:
print("Game Over!")
return
if(matched == 1):
time.sleep(0.5)
break
'''
if colors[index] != sequence.index(color):
print(colors.index(color),sequence.index(color))
print("Game Over!")
return
'''
print("Round complete!")
# Main loop
while True:
play_round()
time.sleep(1) # Pause before starting the next round