Subdivision #2

Created with P5.js

let cells = [];

function setup() {
  createCanvas(600, 600);
  cells.push(new Cell(0, 0, width));
}

function draw() {
  background(250);
  for (let cell of cells) {
    cell.display();
  }
}

function mousePressed() {
  for (let i = cells.length - 1; i >= 0; i--) {
    if (cells[i].contains(mouseX, mouseY)) {
      const subdivisions = ["4", "16", "64"];
      const subdivisionCount = subdivisions[random([0, 1, 2])];
      cells.push(...cells[i].subdivide(subdivisionCount));
      break;
    }
  }
}

function mouseDragged() {
  for (let i = cells.length - 1; i >= 0; i--) {
    if (cells[i].contains(mouseX, mouseY)) {
      const subdivisions = ["4", "16", "64"];
      const subdivisionCount = subdivisions[random([0, 1, 2])];
      cells.push(...cells[i].subdivide(subdivisionCount));
      break;
    }
  }
}

class Cell {
  constructor(x, y, size) {
    this.x = x;
    this.y = y;
    this.size = size;
  }

  contains(x, y) {
    return (
      x > this.x &&
      x < this.x + this.size &&
      y > this.y &&
      y < this.y + this.size
    );
  }

  subdivide(count) {
    let newCells = [];
    let sqrtCount = Math.sqrt(count);
    let rows = Math.floor(sqrtCount);
    let cols = Math.ceil(count / rows);
    let newSize = this.size / sqrtCount;

    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
        let offsetX = this.x + j * newSize;
        let offsetY = this.y + i * newSize;
        newCells.push(new Cell(offsetX, offsetY, newSize));
      }
    }

    return newCells;
  }

  display() {
    noFill();
    stroke(0);
    rect(this.x, this.y, this.size, this.size);
  }
}

Try yourself now