# Two-player reaction race: a free micro:bit lesson from Maze Education
# https://maze.education/microbit/lessons/reaction-race
# MicroPython for the micro:bit Python Editor: https://python.microbit.org

# Two-player reaction race: B starts a race on both boards, A stops your clock, and the boards compare times.
from microbit import *
import radio
import random

radio.on()
radio.config(group=21)
racing = False
start = 0
mine = 0
theirs = 0


def go():
    global racing, start, mine, theirs
    mine = 0
    theirs = 0
    racing = True
    button_a.was_pressed()
    display.show(Image.TARGET)
    start = running_time()


while True:
    if button_b.was_pressed():
        display.clear()
        sleep(random.randint(2000, 5000))
        radio.send("GO")
        go()
    message = radio.receive()
    if message == "GO":
        go()
    elif message and message.isdigit():
        theirs = int(message)
    if racing and button_a.was_pressed():
        racing = False
        mine = running_time() - start
        radio.send(str(mine))
    if mine > 0 and theirs > 0:
        if mine < theirs:
            display.show(Image.HAPPY)
        elif mine > theirs:
            display.show(Image.SAD)
        else:
            display.show("=")
        sleep(1000)
        display.scroll(str(mine))
        mine = 0
        theirs = 0
    sleep(5)
