import os
import display
import utime
import buttons
import light_sensor
import math
import urandom

WIDTH=160
HEIGHT=80
RADIUS=3
cave_top = []
cave_top.insert(0,35)
cave_bottom = []
cave_bottom.insert(0, 64)
start_value = 0
pos_y = 50
score = 0


disp = display.open()
light_sensor.start()


def reset_values(top, bottom, sv, y, sc):
    top = []
    top.insert(0,35)
    bottom = []
    bottom.insert(0, 64)
    sv = light_sensor.get_reading()
    y = 50
    sc = 0

    return top, bottom, sv, y, sc


def draw_cave(top, bottom):
    if len(top) > 159:
        top.pop()
        bottom.pop()

    while len(top) < 160:
        r = urandom.randint(-2,2)
        r = top[0] + r
        if r < 25:
            r = 25
        if r > 45:
            r = 45
        top.insert(0,r)
        r = urandom.randint(-2,2)
        r = bottom[0] + r
        if r > 75:
            r = 75
        if r < 55:
            r = 55
        bottom.insert(0,r)

    for i in range(0, len(top)-1):
        disp.pixel(WIDTH-i, top[i])
        disp.pixel(WIDTH-i, bottom[i])

    return top, bottom


def draw_score(old):
    disp.print("score:%i"%old)
    old = old + 1
    return old


def draw_ship(y, sv):
    value = light_sensor.get_reading()
    if value < math.floor(sv*0.8):
        y = y + 2
    else:
        y = y - 2
    disp.circ(40,y,RADIUS)
    
    return y


def collision(top, bottom, y):
    if (y < top[120]+RADIUS) or (y > bottom[120]-RADIUS):
        disp.print("CRASH!")
        disp.update()
        utime.sleep(2)
        return True
    return False  


cave_top, cave_bottom, start_value, pos_y, score = reset_values(cave_top, cave_bottom, start_value, pos_y, score)

while True:
    disp.clear()

    cave_top, cave_bottom = draw_cave(cave_top, cave_bottom)
    pos_y = draw_ship(pos_y, start_value)

    score = draw_score(score)
    if collision(cave_top, cave_bottom, pos_y):
        cave_top, cave_bottom, start_value, pos_y, score = reset_values(cave_top, cave_bottom, start_value, pos_y, score)        

    disp.update()