import display
from color import Color
import os

white = Color.from_hex( 0xffffff )
black = Color.from_hex( 0x000000 )
red = Color.from_hex( 0xff0000 )
yellow = Color.from_hex( 0xffff00 )
cyan = Color.from_hex( 0x00ffff )
magenta = Color.from_hex( 0xff00ff )

#set your favourite colors here 
color1 = red
color2 = cyan

display_width = 160
display_height = 80
disp = display.open()
disp.clear().update()
ground = []


        
def copyGroundToDisplay():
    disp.clear()
    for x in range( 0, display_width ):
        for y in range( 0, display_height ):
            value = ground[x][y]
            if value == True:
                disp.pixel( x, y, col=color1 )
            else:
                disp.pixel( x, y, col=color2 )
    disp.update()

def initGame():
    for x in range( 0, display_width ):
        temp = []
        for y in range( 0, display_height ):
            randomNumber = int.from_bytes( os.urandom( 1 ), "big" )
            if randomNumber <= 127:
                temp.append( True )
            else:
                temp.append( False )
        ground.append( temp )
    copyGroundToDisplay()

def clearGround():
    for x in range( 0, 159 ):
        for y in range( 0, 79 ):
            ground[x][y] = False

def setValueTo( in_x, in_y, in_value ):
    if in_x >= 0 and in_x < display_width and in_y >= 0 and in_y < display_height:
        ground[in_x][in_y] = in_value
        if in_value == True:
            clr = color1
        else:
            clr = color2
        disp.pixel( in_x, in_y, col=clr )

def changeNeighboursToValue( in_x, in_y, in_value ):
    x = in_x - 1
    y = in_y - 1
    setValueTo( x, y, in_value )
    x = in_x
    setValueTo( x, y, in_value )
    x = in_x + 1
    setValueTo( x, y, in_value )
    x = in_x - 1
    y = in_y
    setValueTo( x, y, in_value )
    x = in_x + 1
    setValueTo( x, y, in_value )
    x = in_x - 1
    y = in_y + 1
    setValueTo( x, y, in_value )
    x = in_x
    setValueTo( x, y, in_value )
    x = in_x + 1
    setValueTo( x, y, in_value )
    disp.update()
    
def getRandomX():
    x_found = False
    while x_found == False:
        random_x = int.from_bytes( os.urandom( 1 ), "big" )
        if random_x < display_width-1:
            x_found = True
    return random_x

def getRandomY(): 
    y_found = False
    while y_found == False:
        random_y = int.from_bytes( os.urandom( 1 ), "big" )
        if random_y < display_height-1:
            y_found = True
    return random_y

def play():
    while 42 == 42:
        x = getRandomX()    #pick a pixel
        y = getRandomY()
        currentValue = ground[x][y] #get it's color
        changeNeighboursToValue( x, y, currentValue ) #set the neighbours to same color

initGame()
play()