from machine import Pin, PWM
import urandom
import time
# LEDs
leds = [Pin(2, Pin.OUT), Pin(3, Pin.OUT), Pin(4, Pin.OUT)]
# Buttons
buttons = [
Pin(16, Pin.IN, Pin.PULL_UP),
Pin(17, Pin.IN, Pin.PULL_UP),
Pin(18, Pin.IN, Pin.PULL_UP)
]
# Buzzer
buzzer = PWM(Pin(15))
buzzer.duty_u16(0)
score = 0
level = 1
reaction_time = 1500 # ms
def all_off():
for l in leds:
l.off()
def beep(freq, dur):
buzzer.freq(freq)
buzzer.duty_u16(30000)
time.sleep(dur)
buzzer.duty_u16(0)
print("Whack-a-Mole with Levels & Sound!")
while True:
mole = urandom.randint(0, 2)
all_off()
leds[mole].on()
start = time.ticks_ms()
hit = False
while time.ticks_diff(time.ticks_ms(), start) < reaction_time:
for i, btn in enumerate(buttons):
if btn.value() == 0:
if i == mole:
score += 1
beep(1000, 0.1) # correct
print("Hit! Score:", score)
else:
beep(300, 0.3) # wrong
print("Wrong button!")
hit = True
break
if hit:
break
all_off()
if score > 0 and score % 3 == 0:
level += 1
reaction_time = max(400, reaction_time - 200)
print("LEVEL UP! Level:", level)
time.sleep(0.4)
explain the entire code in depth