Complete the code which generates the following pattern (Note: the solution uses lines, although it would also be possible to create the image using rotated rectangles, which is covered in Chapter 14).

void setup()  {   
  size(400,200);  
  smooth();
}   

void draw()  {   
  background(255);  
  stroke(0);  
  branch(width/2,height,100);  
}   

void branch(float x, float y, float h)  {   
  ________________________________________;  
  ________________________________________;  
  if (__________________)  {   
    ________________________________________;  
    ________________________________________;  
  }   
}    
Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Exercise 13-9:  Complete the code which generates the following pattern (Note: the solution 
// uses lines, although it would also be possible to create the image using rotated rectangles, 
// which is covered in Chapter 14).         

void setup()  {   
  size(400,200);  
  smooth();
}   

void draw()  {   
  background(255);  
  stroke(0);  
  branch(width/2,height,100);  
}   

void branch(float x, float y, float h)  {   
  line(x,y,x-h,y-h);
  line(x,y,x+h,y-h);
  if (h > 2) {
    branch(x-h,y-h,h/2);
    branch(x+h,y-h,h/2);
  }   
}
  • ww

    Finally, I have to understand the code by a stupid way (draw each points then connect them on paper), and I think it’s obviously not an advanced way of thinking, so, could you please show me a smarter way of thinking the code above? Thank you.

  • ww

    oh, I see, the structure is something like this?

    v v v v
    V V
    V

  • admin

    exactly right!

  • Anders

    Phew it makes sense now! I had started down the wrong path of drawing

    line(x,y, x *1.5, h);
    line(x,y, x *0.5, h);

    Thanks,

    Excellent book by the way!

  • Jon

    // Great example! Thanks
    // I modified slightly to make a circle based fractal

    void setup() {
    size(400,400);
    smooth();
    }

    void draw() {
    background(255);
    stroke(0);
    branch(width/2, height/2, 400);
    }

    void branch(float x, float y, float dia) {
    ellipse(x,y,dia,dia);
    if(dia > 2) {
    branch(x,y-dia/4, dia/2);
    branch(x,y+dia/4, dia/2);
    }
    }

  • min a

    I  enjoy this exercise!!!

  • Ross McQueen

    Add noLoop() to setup to prevent endless loop.

    http://processing.org/learning/basics/recursion.html

  • spendy

    spendy