# Reaction Time Lab — Microbit firmware
#
# How a round works:
#   1. Press B to start.
#   2. The display shows an arrow, then goes blank.
#   3. After a random 2–5s wait, a happy face appears.
#   4. Press A as fast as you can.
#   5. The time (in ms) is shown on the LEDs and sent over USB serial
#      to the companion web app, which handles names and the leaderboard.
#
# Press A during the wait = "too soon" (sad face, no score).
# No press within 3s of the smile = "miss".

from microbit import *
import random


def ready():
    display.show(Image.YES)


ready()

while True:
    if button_b.was_pressed():
        display.show(Image.ARROW_E)
        print("READY")
        sleep(800)
        display.clear()

        delay = random.randint(2000, 5000)
        start = running_time()
        jumped_early = False

        while running_time() - start < delay:
            if button_a.is_pressed():
                jumped_early = True
                break
            sleep(5)

        if jumped_early:
            display.show(Image.SAD)
            print("EARLY")
            sleep(1500)
            ready()
            continue

        display.show(Image.HAPPY)
        stim = running_time()

        while not button_a.is_pressed():
            if running_time() - stim > 3000:
                break
            sleep(1)

        rt = running_time() - stim
        if rt > 3000:
            display.show(Image.NO)
            print("MISS")
            sleep(1500)
        else:
            print("TIME:{}".format(rt))
            display.scroll(str(rt), delay=60)

        ready()

    sleep(20)
