#
# Wokwi | questions
# Memory Game help
# user90108020 — 6/8/24 at 7:43 PM
# Project Link: https://wokwi.com/projects/400168594573904897?gh=1
#
import machine
import utime
import random
class LEDMemoryGame:
def __init__(self, led_pins, button_pins):
self.led_pins = led_pins
self.button_pins = button_pins
self.leds = [machine.Pin(pin, machine.Pin.OUT) for pin in self.led_pins]
self.buttons = [machine.Pin(pin, machine.Pin.IN, machine.Pin.PULL_UP) for pin in self.button_pins]
def flash_all_leds(self):
for _ in range(3): # Flash for 3 cycles
for led in self.leds:
led.on()
utime.sleep_ms(200)
for led in self.leds:
led.off()
utime.sleep_ms(200)
def play_game(self):
sequence = [random.choice(range(len(self.leds))) for _ in range(4)] # Generate random sequence
for idx in sequence:
self.leds[idx].on()
utime.sleep_ms(500) # Display each LED for 500ms
self.leds[idx].off()
utime.sleep_ms(200) # Pause between LEDs
# Check player input
for idx in sequence:
while True:
button_pressed = None
for i, button in enumerate(self.buttons):
if not button.value():
button_pressed = i
break
if button_pressed is not None:
if button_pressed == idx:
break
else:
self.flash_all_leds()
return False
utime.sleep(0.1)
self.leds[idx].on()
utime.sleep_ms(500) # Display the correct LED for 500ms
self.leds[idx].off()
return True
def start(self):
print("Welcome to LED Memory Game!")
while True:
if self.play_game():
print("Congratulations! You won this round.")
else:
print("Oops! You made a mistake.")
utime.sleep(3) # Pause for 3 seconds before starting the next round
# Define pin numbers
LED_PINS = [14, 12, 10, 8] # Change these pin numbers according to your wiring
BUTTON_PINS = [15, 13, 11, 9] # Change these pin numbers according to your wiring
# Create the game instance
game = LEDMemoryGame(LED_PINS, BUTTON_PINS)
# Start the game
game.start()