// Draw a Mondrian-inspired image using recursion
void piet(int x0, int y0, int x1, int y1, int N) {
if (N == 0) {
// Base case -- draw a colorful rectangle with a thick black border
int sw = 3; //this is the stroke width for the rectangle's border
color c[] = { #ff0000, #00ff00, #0000ff, #ffff00, #ffffff}; //Mondrian color palatte
fill(c[int(random(c.length))]);
strokeWeight(sw);
rect (x0,y0,x1-x0-sw,y1-y0-sw);
} else {
//Recursive step -- break the current rectangle into 4 new random rectangles
int i = int(random(x0,x1));
int j = int(random(y0,y1));
piet(x0,y0,i,j,N-1); // upper left rectangle
piet(i,y0,x1,j,N-1); // upper right rectangle
piet(x0,j,i,y1,N-1); // lower left rectangle
piet(i,j,x1,y1,N-1); // lower right rectangle
}
}
The function accepts 5 arguments: the coordinates of the upper left hand corner of a rectangle (x0 and y0), the coordinates of the lower right hand corner (x1 and x2), and the current recursive depth (N). The function does two basic things. First, it tests to see if it’s reached the “base case,” when N = 0. If so, then all it does is draw a rectangle that is randomly colored from the basic Mondrian palette of colors (red, greed, blue, yellow, and white). If it’s not the base case, then it selects a random point (i,j) inside the current rectangle, and then calls piet() 4 more times, passing in the various coordinates that form the 4 new interior rectangles. This “divide and conquer” approach of having a function that calls itself is the hallmark of recursion.
댓글 없음:
댓글 쓰기