Open In App

Sierpinski Triangle using Graphics

Improve
Improve
Like Article
Like
Save
Share
Report

Sierpinski triangle is a fractal and attractive fixed set with the overall shape of an equilateral triangle. It subdivides recursively into smaller triangles.

Approach:

  • In the given segment of codes, a triangle is made and then draws out three other adjacent small triangles till the terminating condition which checks out whether the height of the triangle is less than 5 pixels returns true.
  • We only need to verify whether a given triangle is smaller than 5 pixels since beyond that the triangles would start converging at fixed points.
  • A counter colorVal is defined for in response to the aesthetic need of the triangle and in all, it cycles through all the available colours by iterating every triangle set.
  • Using this methodology we can also further implement a fractal zoom and hypothetically provide an infinite zoom later.

Below is the implementation of the above approach:

C++
// C++ code to implement
// Sierpinski Triangle using Graphics
#include <math.h>
#include <stdlib.h>
#include <winbgim.h>

#define Y 900
#define X 1600

// Defining a function to draw a triangle
// with thickness 'delta'
void triangle(float x, float y,
              float h, int colorVal)
{
    setcolor(colorVal % 15 + 1);

    for (float delta = 0; delta > -5; delta -= 1) {
        line(x - (h + delta) / sqrt(3),
             y - (h + delta) / 3,
             x + (h + delta) / sqrt(3),
             y - (h + delta) / 3);
        line(x - (h + delta) / sqrt(3),
             y - (h + delta) / 3,
             x,
             y + 2 * (h + delta) / 3);
        line(x,
             y + 2 * (h + delta) / 3,
             x + (h + delta) / sqrt(3),
             y - (h + delta) / 3);
    }
}

// Defining a function to draw
// an inverted triangle
// with thickness 'delta'
void trianglev2(float x, float y,
                float h, int colorVal)
{
    setcolor(colorVal % 15 + 1);

    for (float delta = 0; delta > -1 + 5; delta -= 1) {

        line(x - (h + delta) / sqrt(3),
             y + (h + delta) / 3,
             x + (h + delta) / sqrt(3),
             y + (h + delta) / 3);
        line(x - (h + delta) / sqrt(3),
             y + (h + delta) / 3,
             x,
             y - 2 * (h + delta) / 3);
        line(x,
             y - 2 * (h + delta) / 3,
             x + (h + delta) / sqrt(3),
             y + (h + delta) / 3);
    }
}

// A recursive function to draw out
// three adjacent smaller triangles
// while the height is greater than 5 pixels.
int drawTriangles(float x = X / 2,
                  float y = 2 * Y / 3,
                  float h = Y / 2,
                  int colorVal = 0)
{

    if (h < 5) {
        return 0;
    }

    if (x > 0 && y > 0 && x < X && y < Y) {
        triangle(x, y, h, colorVal);
    }

    drawTriangles(x,
                  y - 2 * h / 3,
                  h / 2,
                  colorVal + 1);
    drawTriangles(x - h / sqrt(3),
                  y + h / 3,
                  h / 2,
                  colorVal + 1);
    drawTriangles(x + h / sqrt(3),
                  y + h / 3,
                  h / 2,
                  colorVal + 1);

    return 0;
}

// Driver code
int main()
{
    initwindow(X, Y);
    trianglev2(X / 2, 2 * Y / 3, Y, 2);

    drawTriangles();
    getch();
    closegraph();

    return 0;
}
Java
// Java code to implement
// Sierpinski Triangle using Graphics

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

// Class to create a JFrame and draw the Sierpinski Triangle
public class SierpinskiTriangle extends JPanel {

    // Method to draw a triangle with thickness 'delta'
    private void drawTriangle(Graphics g, int x, int y,
                              int h, int colorVal)
    {
        g.setColor(new Color(colorVal % 15 + 1));

        for (int delta = 0; delta > -5; delta--) {
            g.drawLine(x - (h + delta) / (int)Math.sqrt(3),
                       y - (h + delta) / 3,
                       x + (h + delta) / (int)Math.sqrt(3),
                       y - (h + delta) / 3);
            g.drawLine(x - (h + delta) / (int)Math.sqrt(3),
                       y - (h + delta) / 3, x,
                       y + 2 * (h + delta) / 3);
            g.drawLine(x, y + 2 * (h + delta) / 3,
                       x + (h + delta) / (int)Math.sqrt(3),
                       y - (h + delta) / 3);
        }
    }

    // Method to draw an inverted triangle with thickness
    // 'delta'
    private void drawInvertedTriangle(Graphics g, int x,
                                      int y, int h,
                                      int colorVal)
    {
        g.setColor(new Color(colorVal % 15 + 1));

        for (int delta = 0; delta > -1 + 5; delta--) {
            g.drawLine(x - (h + delta) / (int)Math.sqrt(3),
                       y + (h + delta) / 3,
                       x + (h + delta) / (int)Math.sqrt(3),
                       y + (h + delta) / 3);
            g.drawLine(x - (h + delta) / (int)Math.sqrt(3),
                       y + (h + delta) / 3, x,
                       y - 2 * (h + delta) / 3);
            g.drawLine(x, y - 2 * (h + delta) / 3,
                       x + (h + delta) / (int)Math.sqrt(3),
                       y + (h + delta) / 3);
        }
    }

    // Recursive method to draw three adjacent smaller
    // triangles while the height is greater than 5 pixels
    private void drawTriangles(Graphics g, int x, int y,
                               int h, int colorVal)
    {
        if (h < 5) {
            return;
        }

        if (x > 0 && y > 0 && x < getWidth()
            && y < getHeight()) {
            drawTriangle(g, x, y, h, colorVal);
        }

        drawTriangles(g, x, y - 2 * h / 3, h / 2,
                      colorVal + 1);
        drawTriangles(g, x - h / (int)Math.sqrt(3),
                      y + h / 3, h / 2, colorVal + 1);
        drawTriangles(g, x + h / (int)Math.sqrt(3),
                      y + h / 3, h / 2, colorVal + 1);
    }

    // Paint method to handle drawing
    @Override protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        drawInvertedTriangle(g, getWidth() / 2,
                             2 * getHeight() / 3,
                             getHeight(), 2);
        drawTriangles(g, getWidth() / 2,
                      2 * getHeight() / 3, getHeight(), 0);
    }

    // Driver code
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Sierpinski Triangle");
        frame.setDefaultCloseOperation(
            JFrame.EXIT_ON_CLOSE);
        frame.setSize(1600, 900);
        frame.setContentPane(new SierpinskiTriangle());
        frame.setVisible(true);
    }
}
Python3
import turtle

def sierpinski(points, depth):
    # Draw a triangle with the points provided
    turtle.penup()
    turtle.goto(points[0][0], points[0][1])
    turtle.pendown()
    turtle.goto(points[1][0], points[1][1])
    turtle.goto(points[2][0], points[2][1])
    turtle.goto(points[0][0], points[0][1])

    # If depth is greater than 0, recursively draw smaller triangles
    if depth > 0:
        sierpinski([points[0], get_mid(points[0], points[1]), get_mid(points[0], points[2])], depth - 1)
        sierpinski([points[1], get_mid(points[0], points[1]), get_mid(points[1], points[2])], depth - 1)
        sierpinski([points[2], get_mid(points[2], points[1]), get_mid(points[0], points[2])], depth - 1)

def get_mid(p1, p2):
    # Return the midpoint of two points
    return [(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2]

# Initial triangle points
points = [[-200, -100], [0, 200], [200, -100]]

# Set the recursion depth
depth = 5

turtle.speed(0)  # Fastest speed
sierpinski(points, depth)
turtle.done()

Output:



Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads