Need help for a simple Grid

Hello ppl,

i don’t get the failure in my code. I just want to draw a simple grid out of rectangles.

My Code:

void settings(){
  size(800, 800);
}

void setup(){
  int blockSize = 30;
  int hBlocks = 10;
  int wBlocks = 10;
  
  for(int col = 0; col <= wBlocks; col++){
      for(int row = 0; row <= hBlocks; row++){
        int x1 = col*blockSize;
        int x2 = col*blockSize + blockSize;
        
        int y1 = row*blockSize;
        int y2 = row*blockSize + blockSize;
        if((x2 - x1)>blockSize){
            println("BigFatError");
        }
          rect(x1, y1, x2, y2);
      }
  }
}

the output:

Can anyone help me with this? In my opinion, all block should be the same size…

Thank you very much for your help.

rect:

3rd and 4th parameter: blockSize

It’s the size, not an absolute screen coordinate

see reference

not an answer but a note. when you draw a grid with rectangles you overdraw many lines and many rectangles can be taxing to draw. a faster version is to draw the grid with lines instead.

int gridResolution;
int gridColumns;
int gridRows;

void setup() {
  size(512, 512, P2D);
  
  gridResolution = 32;
  gridColumns = width / gridResolution;
  gridRows = height / gridResolution;
}

void draw() {
  drawGrid();
}

void drawGrid() {
  stroke(0);
  for(int y = 0; y <= gridRows; y++) {
    line(0, y * gridResolution, width, y * gridResolution);
  }
  for(int x = 0; x <= gridColumns; x++) {
    line(x * gridResolution, 0, x * gridResolution, height);
  }
}

lines alone don’t let you change the color of one cell:



void settings() {
  size(800, 800);
}

void setup() {
  int blockSize = 30;
  int hBlocks = 10;
  int wBlocks = 10;

  for (int col = 0; col <= wBlocks; col++) {
    for (int row = 0; row <= hBlocks; row++) {
      int x1 = col*(blockSize+2) + 30;
      int y1 = row*(blockSize+2) + 30;

      fill(255); 
      if (col%2==0 && row%2==0)
        fill(1112);

      rect(x1, y1, 
        blockSize, blockSize);
    }//for
  }//for
}
//

or optional:

// smart grid of rectangles,
int x = 10, y = x, w = 27, h = w, off = 5, grid = 13, many = grid*grid;

color col1 = color(62, 219, 59);
color col2 = color(33, 181, 72);
boolean switchcol = true;

void setup() {
  size(440, 440);
  println("x "+x+" y "+y+" w "+w+" h "+h+" offset "+off+" grid "+grid+" many "+many);
}

void draw() {
  drawGrid();
}

void selcol() {
  if ( switchcol ) fill(col1);
  else fill(col2);
  switchcol = ! switchcol;
}

void drawGrid() {
  switchcol = true;
  for (int i = 0; i < many; i++) {
    selcol();
    rect(x+(i%grid)*(w+off), y+(floor(i/grid))*(h+off), w, h);   // or any other shape/text on that position
  }
}