RandomSquare

JohnC


Based on: Random Squares by Charles Csuri, 1976

Category: direct


Description:

No description provided This sketch is running in the browser.






/* 
Part of the ReCode Project (http://recodeproject.com)
Based on "Random Squares" by Charles Csuri
Originally published in "Computer Graphics and Art" v1n2, 1976
Copyright (c) 2023 JohnC - OSI/MIT license (http://recodeproject/license).
*/

/* @pjs pauseOnBlur="true"; */

void setup() {
  size(600, 600);
  background(255);
  rectMode(CENTER);
  int gridSize = 50;
  int colNo = width / gridSize;
  int rowNo = height / gridSize;
  noFill();
  //fill(0);
  strokeWeight(1.5);
  float sideMargin = 5;
  for (int i = 0; i < colNo; i ++) {
    for (int j = 0; j < rowNo; j ++) {
      if (i == 0 || j == 0 || i == colNo - 1 || j == rowNo - 1) continue; // edge cell should be blank
      float distToCenter = max(abs((float) i - float(colNo - 1) / 2), abs((float) j - float(rowNo - 1) / 2)) ; // check if the cell is near to edge
      float x = gridSize * i + gridSize / 2; // center for this cell
      float y = gridSize * j + gridSize / 2; // center for this cell
      //text(distToCenter, x,y);
      //println(colNo/2 - 2);
      boolean hasLSq = random(1) > 0.75; // does this cell contain a large square?
      boolean hasMSq = random(1) > 0.25; // does this cell contain a medium square?
      int sSqNo = floor(random(7 - score(distToCenter, colNo/2 - 2))); // number of small squares
      if (hasLSq) {
        float sz = random(gridSize * 1.5, gridSize * 2);
        float xx = x + random(-gridSize/2, gridSize/2); // x coordinate for the square
        float yy = y + random(-gridSize/2, gridSize/2); // y coordinate for the square
        if (xx - sz/2 < sideMargin) xx = sz/2 + sideMargin;
        if (yy - sz/2 < sideMargin) yy = sz/2 + sideMargin;
        if (xx + sz/2 > width - sideMargin) xx = width - sideMargin - sz/2;
        if (yy + sz/2 > height - sideMargin) yy = height - sideMargin - sz/2;
        // make sure square is inside the canvas
        rect(xx, yy, sz, sz, 2);
      }
      if (hasMSq) {
        float sz = random(gridSize * 0.8, gridSize);
        float xx = x + random(-gridSize/4, gridSize/4);
        float yy = y + random(-gridSize/4, gridSize/4);
        if (xx - sz/2 < sideMargin) xx = sz/2 + sideMargin;
        if (yy - sz/2 < sideMargin) yy = sz/2 + sideMargin;
        if (xx + sz/2 > width - sideMargin) xx = width - sideMargin - sz/2;
        if (yy + sz/2 > height - sideMargin) yy = height - sideMargin - sz/2;
        rect(xx, yy, sz, sz, 2);
      }
      for (int k = 0; k < sSqNo; k ++){
        float sz = random(gridSize * 0.3, gridSize * 0.4);
        rect(x + random(-gridSize/2, gridSize/2), y + random(-gridSize/2, gridSize/2), sz, sz, 1);
      }
    }
  }
}

float score(float in, float threshold){
  if (in < threshold) return 0;
  return in - threshold;
}