from machine import Pin
from utime import sleep_ms, ticks_ms, ticks_diff
import random
# Define button and LED pins
button_pins = [16, 17, 18, 19]
led_pins = [15, 14, 13, 12]
# Initialize button and LED objects
buttons = [Pin(pin, Pin.IN, Pin.PULL_DOWN) for pin in button_pins]
leds = [Pin(pin, Pin.OUT) for pin in led_pins]
# Function to debounce a button
def debounce_button(button):
debounce_delay = 20 # Adjust the delay as needed
current_value = button.value()
sleep_ms(debounce_delay)
return current_value == button.value()
# Function to flash a specific LED
def flash_led(led_pin, duration=500):
leds[led_pins.index(led_pin)].on()
sleep_ms(duration)
leds[led_pins.index(led_pin)].off()
# Function to turn on a specific LED
def turn_on_led(led_pin):
led_index = led_pins.index(led_pin) if led_pin in led_pins else -1
if led_index != -1:
leds[led_index].on()
# Function to turn off all LEDs
def turn_off_all_leds():
for led_pin in led_pins:
leds[led_pins.index(led_pin)].off()
# Function to shuffle a list using Fisher-Yates algorithm
def fisher_yates_shuffle(lst):
for i in range(len(lst) - 1, 0, -1):
j = random.randint(0, i)
lst[i], lst[j] = lst[j], lst[i]
# Function to play a round of Simon Says
def simon_says_round(sequence):
for led_pin in sequence:
flash_led(led_pin)
sleep_ms(500)
user_sequence = []
for _ in range(len(sequence)):
while True:
for button_pin in button_pins:
if debounce_button(buttons[button_pins.index(button_pin)]) and buttons[button_pins.index(button_pin)].value() == 1:
turn_on_led(button_pin) # Turn on corresponding LED when button is pressed
user_sequence.append(button_pin)
sleep_ms(500)
turn_off_all_leds() # Turn off all LEDs after showing the pressed one
break
return user_sequence == sequence
# Function to handle game over
def game_over():
print("Incorrect! Game over.")
for _ in range(3):
flash_led(led_pins[0], duration=500) # Flash red LED three times
sleep_ms(500)
# Main game loop
while True:
print("Press any button to start Simon Says!")
# Wait for any button press to start the game
while all(button.value() == 0 for button in buttons):
pass
print("Starting in 5 seconds...")
sleep_ms(5000) # 5-second delay before starting the first round
print("Simon Says: Watch the sequence and repeat it!")
# Generate a random sequence of LED flashes using Fisher-Yates shuffle
simon_sequence = [led_pins[i] for i in range(4)]
fisher_yates_shuffle(simon_sequence)
simon_sequence = simon_sequence[:5] # Take the first 5 elements
# Play a round of Simon Says
if simon_says_round(simon_sequence):
print("Correct! Next round.")
else:
game_over() # Handle game over
# Optional: Blink all LEDs to indicate the end of the round
for led_pin in led_pins:
flash_led(led_pin, duration=200)
sleep_ms(2000) # Pause for 2 seconds before starting a new round