Update: Solved! I reposted the working code as the answer. Thanks u/marcusround
A problem that I cannot figure out: “Wrapping shapes across a screen”. (Iterative math and loops problem.)
This sounds like a very easy problem, but ive spent the past 3 hours not being able to figure it out. Let me describe the problem in more detail. I’m hopeful that someone here can help me figure it out.
Description: Write an algorithm so that you have a variable number of squares with a variable size extending across the screen from left to right, where if a box crosses over the righthand side of the screen it starts back at the left on a new line.
Conditions: For simplicity, lets say that the width and height of each box as well as the space between each block, as well as the margins in which these blocks are contained is all equal, and all equals 100 pixels. I want an algorithm that will wrap these blocks/squares across the visible screen, and not break regardless of the size of the box or the number thereof (unless i exceed the canvas size of course).
Let me give you an example of some starting code: (UPDATED)
class Webpage {
constructor(){
this.slots = [];
this.count = 10;
this.slotWidth = 100;
this.slotHeight = 100;
this.paddingWidth = 100;
this.paddingHeight = 100;
this.columnWidth = this.slotWidth + this.paddingWidth;
this.rowHeight = this.slotHeight + this.paddingHeight;
this.numColumns = Math.floor(windowWidth/this.columnWidth);
for (var i = 0; i < this.count; i++){
this.slots[i] = {
x: this.paddingWidth,
y: this.paddingHeight,
column: i % this.numColumns,
row: Math.floor(i/this.numColumns),
id: 0
}
}
}
display(){
background(0);
fill(255);
this.columnWidth = this.slotWidth + this.paddingWidth;
this.rowHeight = this.slotHeight + this.paddingHeight;
this.numColumns = Math.floor(windowWidth/this.columnWidth);
for (var i = 0; i < this.count; i++) {
this.slots[i].column = i % this.numColumns;
this.slots[i].row = Math.floor(i/this.numColumns);
this.slots[i].x = this.columnWidth * this.slots[i].column;
this.slots[i].y = this.rowHeight * this.slots[i].row;
rect(this.slots[i].x, this.slots[i].y, this.slotWidth, this.slotHeight);
console.log("iteration: ", i, ", x :", this.slots[i].x, ", y ", this.slots[i].y)
}
}
}
Crossposted: A problem that I cannot figure out: "Wrapping shapes across a screen". (Iterative math and loops problem.)
Edit 1: Clarification: I need a single-iteration loop. I understand this is easy to do with double-iteration (a nested loop). But i want these boxes to be hierarchically serialized from left to right, and then down a row after it runs off a screen (like a word/text -wrap).
Edit 2: Here is a visual example. I hope this helps explain what I am trying to create.
Edit 3: Solved! The answer was kinda complicated and even used a modulus, but it seems to work beautifully.