from graphics import *
from random import *

def newgrid(title, numrows, numcols):
    cellsize = 600 / max(numrows, numcols)
    window = GraphWin(title, cellsize * numcols, cellsize * numrows)
    r = Rectangle(Point(0, 0), Point(cellsize * numcols, cellsize * numrows))
    r.setFill("black")
    r.draw(window)
    colors = []
    images = []
    for row in range(numrows):
        colors.append(["black"] * numcols)
    grid = {}
    grid["window"] = window
    grid["colors"] = colors
    grid["cellsize"] = cellsize
    return grid

def setcolor(grid, row, col, color):
    if not isvalid(grid, row, col):
        raise Exception("Cannot set color of invalid location", row, col)
    grid["colors"][row][col] = color
    cellsize = grid["cellsize"]
    x = col * cellsize
    y = row * cellsize
    r = Rectangle(Point(x, y), Point(x + cellsize, y + cellsize))
    r.setFill(color)
    window = grid["window"]
    r.draw(window)

def getnumrows(grid):
    return len(grid["colors"])

def getnumcols(grid):
    return len(grid["colors"][0])

def getcolor(grid, row, col):
    if not isvalid(grid, row, col):
        raise Exception("Cannot get color of invalid location", row, col)
    return grid["colors"][row][col]

def isvalid(grid, row, col):
    numrows = getnumrows(grid)
    numcols = getnumcols(grid)
    return row >= 0 and row < numrows and col >= 0 and col < numcols

def wait_for_click(grid):
    p = grid["window"].getMouse()
    cellsize = grid["cellsize"]
    grid["clickcol"] = p.x / cellsize
    grid["clickrow"] = p.y / cellsize

def getclickrow(grid):
    return grid["clickrow"]

def getclickcol(grid):
    return grid["clickcol"]

def main():
    n = 15
    grid = newgrid("Forest", n, n)
    for row in range(n):
        for col in range(n):
            if random() > 0.5:
                setcolor(grid, row, col, "green")
    while True:
        wait_for_click(grid)
        burn(grid, getclickrow(grid), getclickcol(grid))

def burn(grid, row, col):
    if isvalid(grid, row, col):
        if getcolor(grid, row, col) == "green":
            setcolor(grid, row, col, "red")
            burn(grid, row - 1, col)
            burn(grid, row, col - 1)
            burn(grid, row, col + 1)
            burn(grid, row + 1, col)

main()