Skip to content

Instantly share code, notes, and snippets.

@ippsketch
Created September 1, 2021 03:13
Show Gist options
  • Save ippsketch/56b30ce2a20098d26381cf15ddcb21ef to your computer and use it in GitHub Desktop.
Save ippsketch/56b30ce2a20098d26381cf15ddcb21ef to your computer and use it in GitHub Desktop.
Grid pack
let gridFlag = []; //array of underlying grid flags (true==filled)
let shapes = []; //array of shape objects
let dx,dy; // grid spacing
function setup() {
createCanvas(1000,1000);
iNum = 20;
jNum = 20;
dx = width/iNum;;
dy = height/jNum;
for (let i=0; i<iNum*jNum; i++){
gridFlag.push(false);
}
background(0)
// drawGrid
noFill();
stroke(100)
for (let i=0; i<iNum; i++){
for (let j=0; j<jNum; j++){
rect(i*dx,j*dy,dx,dy)
}
}
}
function draw() {
let placedFlag = false;
let count = 0;
let maxCount = 1000000
while (!placedFlag && count<maxCount){
let randi = ~~random(iNum);
let randj = ~~random(jNum);
let randh = random([1,2,4,8]);
let randw = randh*2;
if (checkGrid(randi,randj,randw,randh)){
shapes.push(new Shape(randi,randj,randw,randh));
placedFlag = true;
}
count++;
if (count==maxCount) noLoop()
}
// draw the shape that was just placed
shapes[shapes.length-1].draw();
}
function checkGrid(iStart,jStart,w,h){
for (let i=iStart; i<iStart+w; i++){
for (let j=jStart;j<jStart+h;j++){
if (i<0 || i>=iNum || j<0 || j>=jNum) return false;
let gridIndex = j*iNum+i;
if (gridFlag[gridIndex]) return false;
}
}
// if you're here, all spots on grid were clear
// go back through and save all those spots as filled (true)
for (let i=iStart;i<iStart+w;i++){
for (let j=jStart;j<jStart+h;j++){
let gridIndex = j*iNum+i;
gridFlag[gridIndex] = true;
}
}
return true;
}
class Shape {
constructor(i,j,width,height) {
this.i = i;
this.j = j;
this.width = width;
this.height = height;
}
draw(){
fill(255)
rect(this.i*dx+dx/4,this.j*dy+dx/4,this.width*dx-dx/2,this.height*dy-dy/2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment