回归时间!!!
请原谅我的热情,但我喜欢递归,而且我没有很多机会使用它(主要是因为它大部分时间都可以避免,也因为在错误的时间使用它是白痴)。
按照我的理解,你可以用下面的伪代码来实现:
Draw a rectangle
Draw 2 smaller rectangles underneath the last one
Use this logic on each of the smaller rectangles
现在,递归最重要的事情是您需要一个退出条件。在这里,我想你可以输入你想要的“线”的数量,或者当它们太小而不能被视为矩形时停止编写矩形。为什么不兼得?让我们写两个:
void setup() {
size(800, 600);
background(0);
stroke(255);
noFill();
// drawing a couple lines of squares
DrawRectangles(new PVector(0,0), 200, width, 6); // for 6 lines of rectangles
// if you try it with a stupid number, like 600 iterations, it'll stop anyway when the rectangles are so small that they can't be seen
}
void draw() {}
void DrawRectangles(PVector position, int squareHeight, int squareWidth, int iterations) {
// if you can draw more rectangles it'll continue, else it stops
// a recursive method MUST have a stop condition, or else it becomes an infinite loop!
if (squareHeight > 0 && iterations > 0) {
// draw a rectangle and call this method twice for the next line
rect(position.x, position.y, squareWidth, squareHeight);
DrawRectangles(new PVector(position.x, position.y + squareHeight), (int)(squareHeight/2), (int)(squareWidth/2), iterations-1);
DrawRectangles(new PVector(position.x + squareWidth/2, position.y + squareHeight), (int)(squareHeight/2), (int)(squareWidth/2), iterations-1);
}
}
就是这样。有很多方法可以做你想做的事,所以其他答案可能和这个一样好,但是......我喜欢这个。如果您对 cmets 中的此代码有任何疑问,我会随时待命。
玩得开心!