Clicking a square in a matrix of squares - does not work consistently
in
Programming Questions
•
3 months ago
Hi - I am pretty new to processing and am learning as I am going. I am working on a small project and am stuck on one thing. I am displaying a matrix of squares, all colored differently using a formula based on their position. When I click on a square, I want it to turn blue and retain that color until I click on it again. I also want to be able to select multiple squares. Sometimes it works (a square is selected, but it is not colored blue - but a different color) sometimes it does not and I can't figure out the problem. Any help, tips, or pointers would be appreciated. Here is my code:
- int canvasWidth = 500;
- int canvasHeight = 500;
- int matrixSize = 6;
- boolean[][] squaresArray = new boolean[matrixSize][matrixSize];
- void setup() {
- int i = 0;
- int j = 0;
- size(canvasWidth, canvasHeight);
- noStroke();
- smooth();
- for (i=0; i < matrixSize; i++)
- for(j=0; j < matrixSize; j++)
- squaresArray[i][j] = false;
- }
- boolean mouseOverRect(int x, int y, int w, int h) {
- return (mouseX >= x && mouseX <= x+w && mouseY >= y && mouseY <= y+h);
- }
- void draw() {
- background(100);
- int rX = 0;
- int rY = 0;
- int rW = 30;
- int rH = 30;
- int i = 0;
- int j = 0;
- for (i=0; i < matrixSize; i++)
- {
- rY += 50;
- for(j=0; j < matrixSize; j++)
- {
- rX += 50;
- if (mouseOverRect(rX, rY, rW, rH))
- {
- if (mousePressed)
- {
- squaresArray[i][j] = !squaresArray[i][j]; // change state of square
- if ( squaresArray[i][j] )
- {
- fill(0, 0, 255); // square has been clicked and is now True - fill with blue
- }
- else
- {
- // revert to unclicked color:
- fill( map(rX,0,canvasWidth,0,255), map(rY,0,canvasHeight,0,255), 100);
- }
- }
- }
- else {
- if ( !squaresArray[i][j] )
- {
- // square is false, so fill with unclicked color
- fill( map(rX,0,canvasWidth,0,255), map(rY,0,canvasHeight,0,255), 100);
- }
- }
- rect(rX, rY, rW, rH);
- }
- rX = 0;
- }
- }
1