import processing.core.PApplet;

public class GridDemo extends PApplet
{
    private static final int TOP_OFFSET = 20;
    private static final int LEFT_OFFSET = 15;
    private static final int BOX_WIDTH = 75;
    private static final int BOX_HEIGHT = 50;
    private static final int ROWS = 5;
    private static final int COLUMNS = 8;
    
    public static void main(String[] args)
    {
        PApplet.main("GridDemo");
    }
    
    public void settings()
    {
        final int SCREEN_WIDTH = (LEFT_OFFSET * 2) + (COLUMNS * BOX_WIDTH);
        final int SCREEN_HEIGHT = (TOP_OFFSET * 2) + (ROWS * BOX_HEIGHT);
        size(SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    
    public void setup()
    {
        
    }
    
    public void draw()
    {
        background(0);
        drawGrid();
        labelGridSpots();
    }
    
    public void mousePressed()
    {
        println("(" + getRow(mouseY) + ", " + getColumn(mouseX) + ")");
    }
    
    // returns row corresponding to y or -1 if not an existing row
    public int getRow(int y)
    {
        if(y < getTopY(0) || y >= getTopY(ROWS))
            return -1;
        
        return (y - TOP_OFFSET) / BOX_HEIGHT;
    }
    
    // returns column corresponding to x or -1 if not an existing column
    public int getColumn(int x)
    {
        if(x < getLeftX(0) || x >= getLeftX(COLUMNS))
            return -1;
        
        return (x - LEFT_OFFSET) / BOX_WIDTH;
    }
    
    public int getTopY(int row)
    {
        return TOP_OFFSET + (row * BOX_HEIGHT);
    }
    
    public int getLeftX(int column)
    {
        return LEFT_OFFSET + (column * BOX_WIDTH);
    }
    
    public void drawGrid()
    {
        rectMode(CORNER);
        noFill();
        strokeWeight(1);
        stroke(255);
        
        for(int row = 0; row < ROWS; row++)
        {
            for(int col = 0; col < COLUMNS; col++)
            {
                rect(getLeftX(col), getTopY(row), BOX_WIDTH, BOX_HEIGHT);
            }
        }
    }
    
    public void labelGridSpots()
    {
        textAlign(CENTER, CENTER);
        textSize(15);
        stroke(255);
        
        for(int row = 0; row < ROWS; row++)
        {
            for(int col = 0; col < COLUMNS; col++)
            {
                final int CENTER_X = getLeftX(col) + (BOX_WIDTH / 2);
                final int CENTER_Y = getTopY(row) + (BOX_HEIGHT / 2);
                text("(" + row + ", " + col + ")",
                        CENTER_X, CENTER_Y);
            }
        }
    }
}
