import pyxel
from minesweeper import *

# Initialize the window
pyxel.init(128, 128, title="Nuit du Code")

# Initialize a grid, its bombs and the digits
grid = emptyGrid(9, 9)
plantBombs(grid, 10)
computeDigit(grid)

# cursor position to be able to select cells
cursor_x, cursor_y = 0, 0

# If either on them is True, then the game has ended. Otherwise, it's still on 
bWin, bLose = False, False


def draw_grid(grid):
    y = 0
    for row in grid:
        x = 0
        for cell in row:
            # Empty visible cell 
            if cell == '_': 
                pyxel.rect(10*x, 10*y, 10, 10, 3)
            # Visible cell with a digit
            elif type(cell) == int and cell > 0: # nombre
                pyxel.text(10*x+2, 10*y+2, str(cell), 2)
            # non visible cell
            else:
                pyxel.rect(10*x, 10*y, 10, 10, 1)
            x += 1
        y += 1


def update():
    global cursor_x, cursor_y, bWin, bLose 
    if pyxel.btnp(pyxel.KEY_Q):
        pyxel.quit()
    
    # Cursor movements, up down, left and right
    if pyxel.btnp(pyxel.KEY_RIGHT):
        cursor_x += 1
    if pyxel.btnp(pyxel.KEY_LEFT):
        cursor_x -= 1
    if pyxel.btnp(pyxel.KEY_UP):
        cursor_y -= 1
    if pyxel.btnp(pyxel.KEY_DOWN):
        cursor_y += 1
    
    # Spacebar to make a cell visible 
    if pyxel.btnp(pyxel.KEY_SPACE):
        r = play(grid, cursor_y, cursor_x)
        if r == 'b':
            bWin = True
        else:
            bLose = hasWon(grid)
            

def draw():
    global bWin, bLose
    pyxel.cls(0)
    
    # Special message in case of win or lose, otherwise the game is still on
    if bWin:
        pyxel.text(10, 10, "YOU LOSE", 2)
        return
    elif bLose:
        pyxel.text(10, 10, "YOU WIN", 2)
        return
    else: 
        draw_grid(grid)
    
    # Draw the cursor
    pyxel.rectb(10*cursor_x, 10*cursor_y, 10, 10, 11)
    
pyxel.run(update, draw)
