SIERPINSKI JAVAFX

A Sierpinski triangle Algorithm

Begin with an equilateral triangle, which is considered to be a Sierpinski fractal of order 0.
Connect the midpoints of the sides of the triangle of order 0 to create a Sierpinski triangle of order 1
Leave the center triangle intact. Connect the midpoints of the sides of the three other triangles to create a Sierpinski triangle of order 2

I will just show the code of drawing the pattern.

The sourceCode

    Line l1,l2,l3;
    Point2D p1,p2,p3;
    AnchorPane root;
    @Override
    public void start(Stage primaryStage) {

         root = new AnchorPane();
       
        Scene scene = new Scene(root, 300, 250);

        p1=new Point2D((scene.getWidth()-10)/2,10);
        p2=new Point2D(10,scene.getHeight()-10);
        p3=new Point2D((scene.getWidth()-10)-10,scene.getHeight()-10);
        run(3,p1,p2,p3);
       
        primaryStage.setTitle("Sierpinski");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
  public void run(int order,Point2D p1,Point2D p2,Point2D p3){

      if(order==0){

        l1=new Line(p1.getX(),p1.getY(),p2.getX(),p2.getY());
        l2=new Line(p1.getX(),p1.getY(),p3.getX(),p3.getY());
        l3=new Line(p2.getX(),p2.getY(),p3.getX(),p3.getY());

        root.getChildren().addAll(l1,l2,l3);  
 
     }else{

         Point2D p12=midpoint(p1,p2);
         Point2D p23=midpoint(p2,p3);
         Point2D p31=midpoint(p3,p1);
   
        l1=new Line(p1.getX(),p1.getY(),p2.getX(),p2.getY());
        l2=new Line(p1.getX(),p1.getY(),p3.getX(),p3.getY());
        l3=new Line(p2.getX(),p2.getY(),p3.getX(),p3.getY());

        root.getChildren().addAll(l1,l2,l3);

        run(order-1,p1,p12,p31);
        run(order-1,p12,p2,p23);
        run(order-1,p31,p23,p3);
     }
 }
   public Point2D midpoint(Point2D pp1, Point2D pp2) {
      return new Point2D((pp1.getX() + pp2.getX()) / 2, (pp1.getY() + pp2.getY()) / 2);
 }
And with a little more styling  .i.e Transition,stroke width, and different fills.
Results
Main

Colorfull Samples







Comments

Popular Posts