Sierpinski

  • Mouse (tasto): aumenta la ricorsione
  • Mouse (Ctrl+tasto): diminuisce la ricorsione
  • Applicazione Java
final int numMax=8;

int   num=3;   
float X1, Y1,
      X2, Y2,
      X3, Y3;

boolean scende=false;

void setup()
{
   size(500, 500);
   smooth();
   noStroke();
   fill(0); 

   X1=0;       Y1=height-1;
   X2=width-1; Y2=height-1;
   X3=width/2; Y3=0;   

   noLoop();
}

void keyPressed()
{
   scende=true;
}
void keyReleased()
{
   scende=false;
}
void mousePressed()
{
   if(scende && num > 1)
	  num--;
   else if(!scende && num < numMax)  
	  num++;
   redraw();
}

void draw()
{
   background(255);
   sierpinski(num, X1, Y1, X2, Y2, X3, Y3);
}

void sierpinski(int n, float x1, float y1,
		       float x2, float y2,
              	       float x3, float y3)
{
   if(n == 1)
	  triangle(x1, y1, x2, y2, x3, y3);
   else
   {
	  float x12=(x1+x2)/2; float y12=(y1+y2)/2;
	  float x23=(x2+x3)/2; float y23=(y2+y3)/2;
	  float x13=(x1+x3)/2; float y13=(y1+y3)/2;

	  sierpinski(n-1, x1,  y1,  x12, y12, x13, y13);
	  sierpinski(n-1, x2,  y2,  x12, y12, x23, y23);
	  sierpinski(n-1, x3,  y3,  x23, y23, x13, y13);
   }
}