在 p5.js 中嵌套 for 循环的重复正方形/angular 螺旋?

Duplicate square / angular spiral with nested for loops in p5.js?

我正在尝试用 angular 螺旋线制作网格。螺旋线本身由 for 循环中的单行组成。当我沿一个轴(x 或 y)复制和移动(平移)螺旋原点时,它起作用了。但是沿着(x和y)移动,为了使它成为一个网格,如果不分解螺旋是行不通的。

如果有人能帮助我解决我的编码难题,我将不胜感激。顺便说一句,我对任何提示都非常开放,并有助于提高我的代码编写技能。那里肯定有很多冗余和冗长的表达...... 到目前为止,这是我的代码:

function drawSpiral() {
  let count = 8;
  let stepX = 8;
  let stepY = 8;
  let tileSize = 100;
  let pixelX = tileSize;
  let pixelY = tileSize;
  for (let j = 0; j < 5; j++) {
    let x1 = 0;
    let y1 = 0;
    let x2 = 0;
    let y2 = 0;
    let x3 = 0;
    let y3 = 0;
    let x4 = 0;
    let y4 = 0;
    for (let i = 0; i < count; i++) {
      x1 += stepX;
      x2 -= stepX;
      x3 -= stepX;
      x4 += stepX;
      y1 += stepY;
      y2 += stepY;
      y3 -= stepY;
      y4 -= stepY;
      push();
      translate(pixelX, pixelY);
      line(x1, y1, x2 - stepX, y2)
      line(x2 - stepX, y2, x3 - stepX, y3 - stepY);
      line(x3 - stepX, y3 - stepY, x4 + stepX, y4 - stepY);
      line(x4 + stepX, y4 - stepY, x1 + stepX, y1 + stepY);
      pop();
      
    }
    pixelX += tileSize * 2; //shifting either along x-axis
  }
}

多漂亮啊?是的,您猜对了 – 我是编码行业的新手 ;)

如果您正在尝试制作一个螺旋网格,看起来您只需要在当前 for (let j = 0; j < 5; j++) { 处使用一对 for 循环。几乎任何时候你想要创建一个网格你都需要一对嵌套的 for 循环。

function setup() {
  createCanvas(800, 800);
}

function draw() {
  background(100);
  drawSpiral();
}

function drawSpiral() {
  let count = 8;
  let stepX = 8;
  let stepY = 8;
  let tileSize = 100;
  let pixelX = tileSize;
  let pixelY = tileSize;
  // Make a 5x5 grid of spirals
  for (let row = 0; row < 5; row++) {
    for (let col = 0; col < 5; col++) {
      let x1 = 0;
      let y1 = 0;
      let x2 = 0;
      let y2 = 0;
      let x3 = 0;
      let y3 = 0;
      let x4 = 0;
      let y4 = 0;
      for (let i = 0; i < count; i++) {
        x1 += stepX;
        x2 -= stepX;
        x3 -= stepX;
        x4 += stepX;
        y1 += stepY;
        y2 += stepY;
        y3 -= stepY;
        y4 -= stepY;
        push();
        translate(pixelX, pixelY);
        line(x1, y1, x2 - stepX, y2)
        line(x2 - stepX, y2, x3 - stepX, y3 - stepY);
        line(x3 - stepX, y3 - stepY, x4 + stepX, y4 - stepY);
        line(x4 + stepX, y4 - stepY, x1 + stepX, y1 + stepY);
        pop();

      }
      // Sift right for each col
      pixelX += tileSize * 2;
    }
    // Shift down for each row
    pixelY += tileSize * 2;
    // And reset the horizontal position at the end of each row
    pixelX = tileSize;
  }
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.3.1/lib/p5.js"></script>