Advertisement
belrey10

5 – Simon Says Memory Game

Nov 7th, 2024 (edited)
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. import machine
  2. import utime
  3. import urandom
  4.  
  5. # Initialize LEDs
  6. led_pins = [12, 13]
  7. leds = [machine.Pin(pin, machine.Pin.OUT) for pin in led_pins]
  8.  
  9. # Initialize buttons
  10. button_pins = [14, 15]
  11. buttons = [machine.Pin(pin, machine.Pin.IN, machine.Pin.PULL_UP) for pin in button_pins]
  12.  
  13. # This function will flash the given LED number
  14. def flash_led(led_number, duration=0.5):
  15.     leds[led_number].value(1)
  16.     utime.sleep(duration)
  17.     leds[led_number].value(0)
  18.     utime.sleep(duration)
  19.  
  20. # This function waits for a button press and returns the button number
  21. def wait_for_button():
  22.     while True:
  23.         for i, button in enumerate(buttons):
  24.             if button.value() == 0:
  25.                 # Debounce the button press
  26.                 utime.sleep_ms(20)
  27.                 while button.value() == 0:
  28.                     pass
  29.                 return i
  30.  
  31. # Main game loop
  32. sequence = []
  33. while True:
  34.     print("\nNew round! Watch the LED sequence...")
  35.    
  36.     # Add a new step to the sequence
  37.     sequence.append(urandom.randint(0, 1))
  38.    
  39.     # Show the sequence to the player
  40.     for led_number in sequence:
  41.         flash_led(led_number)
  42.    
  43.     print("Now, replicate the sequence using the buttons!")
  44.    
  45.     # Wait for player's input and check if it's correct
  46.     for led_number in sequence:
  47.         button_number = wait_for_button()
  48.         if button_number != led_number:
  49.             # Wrong sequence, flash both LEDs as an error signal and restart the game
  50.             flash_led(0, 0.2)
  51.             flash_led(1, 0.2)
  52.             print("Wrong sequence! Let's start over.")
  53.             sequence = []
  54.             break
  55.         else:
  56.             print(f"Correct button {button_number+1}!")
  57.    
  58.     # Inform player about the correct sequence input
  59.     if len(sequence) > 0 and button_number == led_number:
  60.         print(f"Good job! Sequence length is now {len(sequence)}")
  61.    
  62.     # Small delay before next sequence
  63.     utime.sleep(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement