from MineField import *
from Mine import *

## MineSweeper main program
## ========================
## 
## Display the board and flag or test a square
## Game ends either when player tests a mine or
##  when all squares have been tested or flagged.
##

def turn(f, nc, nf):
    dt = ""
    while dt not in ['F', 'T']:
        dt = input("Toggle flag(F) or Test(T)? ").upper()
    
    col = int(input("Which column> "))
    row = int(input("Which row> "))

    m = f.getMine(row, col)
    if m == None:
        print("No cell at", row, col)
        return (False, nc, nf)

    if dt == 'T':
        if m.clear():
            if m.getPlant():
                print("B O O O O M...", "Mine at", row, col)
                return (True, nc, nf) 
            c2 = f.scoreNeighboursAndClear(row, col)
            print(c2)
            return (False, nc+1+c2, nf)
        else:
            if m.getClear():
                print("Cell at", row, col, "already cleared")
            else:
                print("Cell at", row, col, "already flagged")
            return (False, nc, nf)

    else:
        if m.flag():
            if m.getFlag():
                return (False, nc, nf+1)
            else:
                return (False, nc, nf-1)
        else:
            print("Cell at", row, col, "already cleared")
            return (False, nc, nf)

# Set the size and initialise the minefield
SIZE = 10
f = MineField(SIZE, 0.9, SIZE**2//10)
#f.revealField() ## uncomment this for cheating

# Initialise the vaiable to detect completion 
numCleared = 0
numFlagged = 0
boom = False

# Take turns until the game ends
while numCleared + numFlagged < SIZE**2 and not boom:
    f.showField()
    boom, numCleared, numFlagged = turn(f, numCleared, numFlagged)
    print("  Cleared:", numCleared, "  Flagged:", numFlagged)
    
# Reveal the minefield at the end
f.revealField()
if not boom:
    print("Game over. How did you do?")

