Skip to content

Instantly share code, notes, and snippets.

@rezof
Created December 29, 2022 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rezof/ed00abdf04dc24abcc48f5bffcf9f892 to your computer and use it in GitHub Desktop.
Save rezof/ed00abdf04dc24abcc48f5bffcf9f892 to your computer and use it in GitHub Desktop.
generate a grid made of randomly sized rectangles
const grid = {};
const rectangles = [];
const rows = 50;
const cols = 50;
// mark all columns as un-claimed
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
grid[`${r}-${c}`] = { claimed: false };
}
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (grid[`${row}-${col}`].claimed === false) {
const w = Math.max(3, Math.min(8, Math.floor(Math.random() * 10)));
const h = Math.max(3, Math.min(5, Math.floor(Math.random() * 10)));
let columnsAvailable = 1;
Array.from({ length: Math.min(w, cols - (w - col)) })
.every((_, i) => {
// 'every' will stop once one item returns false
// so we track how many free column are free with it
if (grid[`${row}-${col + i}`]?.claimed === false) {
columnsAvailable = i + 1;
grid[`${row}-${col + i}`].claimed = true;
return true;
}
return false;
});
let rowsAvailable = 1;
Array.from({ length: Math.min(h, rows - (row + h)) })
.every((_, i) => {
if(i === 0){
// this column has been check & claimed above
return true;
}
const rowIndex = row + i;
if (grid[`${rowIndex}-${col}`]?.claimed === false) {
rowsAvailable = i + 1;
grid[`${rowIndex}-${col}`].claimed = true;
return true;
}
return false;
});
for (let i = 0; i < rowsAvailable; i++) {
for (let j = 0; j < columnsAvailable; j++) {
grid[`${row + i}-${col + j}`].claimed = true;
}
}
rectangles.push({
x: col,
y: row,
width: columnsAvailable,
height: rowsAvailable,
});
}
}
}
const xPercentage = 100 / cols;
const yPercentage = 100 / rows;
const container = document.querySelector("#container");
rectangles.forEach((rectangle) => {
const div = document.createElement("div");
div.classList.add("rectangle");
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
div.style.backgroundColor = "#" + randomColor;
div.style.left = rectangle.x * xPercentage + "%";
div.style.top = rectangle.y * yPercentage + "%";
div.style.height = rectangle.height * yPercentage + "%";
div.style.width = rectangle.width * xPercentage + "%";
// div.textContent = `${rectangle.width} - ${rectangle.height}`;
if (container) {
container.append(div);
}
});
@rezof
Copy link
Author

rezof commented Dec 29, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment