Sierpinski interattivo

  • Mouse (posizione): posizione del vertice
  • Mouse (tasto): aumenta la ricorsione
  • Mouse (Ctrl+tasto): diminuisce la ricorsione
  • Applicazione Java
final int numMax=8;
final int GAP=100;
int   num=3;   
float X1, Y1,
	  X2, Y2,
	  X3, Y3;

boolean scende=false;

void setup()
{
   size(500, 500);
   smooth();
   noStroke();
   fill(0); 
   
   X1=GAP;       Y1=height/2;
   X2=width-GAP; Y2=height/2;
   X3=width/2; Y3=width/2;   
   
   noLoop();
}

void keyPressed()
{
   scende=true;
}
void keyReleased()
{
   scende=false;
}
void mouseMoved()
{
   X3=mouseX;
   Y3=mouseY;

   redraw();
}
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);
   }
}