# Imported the same libraries as used in the Blink example + randint to randomize the LED blinking order.
from machine import Pin
from utime import sleep
from random import randint

sleep(0.01) # Wait for USB to connect

# Configure the pins separately in case I need to change them at some point 
RED_LED = 3
YELLOW_LED = 4 
GREEN_LED = 2
BLUE_LED = 1

RED_BTN = 26
YELLOW_BTN = 27 
GREEN_BTN = 28
BLUE_BTN = 29


# Initiate and create variables for the LED pins to be used in the code 
redled = Pin(RED_LED, Pin.OUT)
yellowled = Pin(YELLOW_LED, Pin.OUT)
greenled = Pin(GREEN_LED, Pin.OUT)
blueled = Pin(BLUE_LED, Pin.OUT)

# Initiate and create variables for the button pins to be used in the code 
redbtn = Pin(2, Pin.IN, Pin.PULL_UP)
yellowbtn = Pin(6, Pin.IN, Pin.PULL_UP)
greenbtn = Pin(10, Pin.IN, Pin.PULL_UP)
bluebtn = Pin(14, Pin.IN, Pin.PULL_UP)

# Define game setup
game_on = True
speed = 2
counter = 0
lights_order = []
button_order = [] 

# Function to check if a corresponding button has been presssed 
def check(): 
    global game_on 
    if len(lights_order) == len(button_order):
        if lights_order[-1] != button_order[-1]:
            game_over()
    else:
        game_over()
    return

def game_over():
    game_on = False
    print("Game over")
    redled.value(1)
    yellowled.value(1)
    greenled.value(1) 
    blueled.value(1)
    sleep(2)
    redled.value(0)
    yellowled.value(0)
    greenled.value(0) 
    blueled.value(0)

# Game loops until check()-function switches game_on to False
while game_on == True:

# Random number represent a specific LED and is added to lights-list 
round_num = randint(1,4)
lights_order.append(round_num)

# Making a corresponding LED to light up for 1/4 of the speed
if round_num == 1: 
    redled.value(1)
    sleep(speed/4)
    redled.value(0)
if round_num == 2: 
    yellowled.value(1)
    sleep(speed/4)
    yellowled.value(0)
if round_num == 3: 
    greenled.value(1) 
    sleep(speed/4)
    greenled.value(0) 
if round_num == 4: 
    blueled.value(1)
    sleep(speed/4)
    blueled.value(0)

# Waiting for user to push a (correct) button, 
# For loop ensures enough time and pressed-button adds only on number to buttons-list 
for i in range (9):
    if redbtn.value() == 0:
        button_pressed = 1
    if yellowbtn.value() == 0:
        button_pressed = 2
    if greenbtn.value() == 0:
        button_pressed = 3
    if bluebtn.value() == 0:
        button_pressed = 4
        sleep(speed/9) 

# Update game setup
button_order.append(button_pressed)
speed -= 0.02
check()
if game_on:
    counter += 1
    print(counter)
    
    