如何对 p5.js 金字塔使用嵌套循环?
How to use nested loops for a p5.js pyramid?
我是 javascript 的新手,我对嵌套循环感到困惑 我设法得到了我想要的结果,但我知道必须有一个更简化的版本。或者更可能只是一个更好的版本。
function setup() {
createCanvas(800, 600);
}
function draw() {
background(200);
fill(255, 0, 0);
for (let i = 0; i <= 3; i++) {
square(i * 50, i * 50, 50);
for (let i = 0; i <= 3; i++) {
square(i * 50 - 50, i * 50, 50);
for (let i = 0; i <= 3; i++) {
square(i * 50 - 100, i * 50, 50);
for (let i = 0; i <= 3; i++) {
square(i * 50 - 150, i * 50, 50);
}
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
您只需要 2 个嵌套循环。外部的是从 0 到行数的行。内部的是广告从 0 到当前行的编号(索引)的列。
int 下面的例子no_of_rows
指定行数,可以设置为任意值:
let no_of_rows = 3;
function setup() {
createCanvas(800, 600);
}
function draw() {
background(200);
fill(255, 0, 0);
// for each row
for (let row = 0; row <= no_of_rows; row++) {
// for each column in the row
for (let column = 0; column <= row ; column ++) {
square(column * 50, row * 50, 50);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
我是 javascript 的新手,我对嵌套循环感到困惑 我设法得到了我想要的结果,但我知道必须有一个更简化的版本。或者更可能只是一个更好的版本。
function setup() {
createCanvas(800, 600);
}
function draw() {
background(200);
fill(255, 0, 0);
for (let i = 0; i <= 3; i++) {
square(i * 50, i * 50, 50);
for (let i = 0; i <= 3; i++) {
square(i * 50 - 50, i * 50, 50);
for (let i = 0; i <= 3; i++) {
square(i * 50 - 100, i * 50, 50);
for (let i = 0; i <= 3; i++) {
square(i * 50 - 150, i * 50, 50);
}
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
您只需要 2 个嵌套循环。外部的是从 0 到行数的行。内部的是广告从 0 到当前行的编号(索引)的列。
int 下面的例子no_of_rows
指定行数,可以设置为任意值:
let no_of_rows = 3;
function setup() {
createCanvas(800, 600);
}
function draw() {
background(200);
fill(255, 0, 0);
// for each row
for (let row = 0; row <= no_of_rows; row++) {
// for each column in the row
for (let column = 0; column <= row ; column ++) {
square(column * 50, row * 50, 50);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>