Sierpinski's Triangle (Chaos Game)
This example discusses the implementation of an algorithm for constructing a Sierpinski triangle in Julia using the Luxor graphics library for visualization.
Introduction
The Sierpinski triangle algorithm is a simple iterative process that is used to generate fractals. Despite its apparent simplicity, this method allows you to create complex and beautiful geometric structures. The algorithm is based on the random selection of one of the predefined points (vertices) and the subsequent construction of a new point at a certain distance from the current position. By repeating this process many times, we get a visualization of the fractal set.
The main part
Installing an external Luxor package, if it is not already installed
import Pkg; Pkg.add("Luxor")
Connecting the Luxor library for working with graphics
using Luxor
Definition of the function implementing the Chaos game algorithm
function chaos()
    # Задаем размер изображения (ширина и высота в пикселях)
    width  = 1000
    height = 1000
    # Создаем новый чертеж с заданными размерами и именем файла
    Drawing(width, height, "./chaos.png")
    # Создаем "черепашку" (объект Turtle), которая будет рисовать точки
    # Параметры: начальные координаты (0, 0), видимость (true), направление (0 градусов), цвет (черный)
    t = Turtle(0, 0, true, 0, (0., 0., 0.))
    # Случайным образом задаем начальные координаты точки
    x = rand(1:width)
    y = rand(1:height)
    # Цикл итераций: чем больше, тем точнее формируется фрактал
    for l in 1:30_000
        # Случайный выбор одной из трех возможных вершин (1, 2 или 3)
        v = rand(1:3)
        # В зависимости от выбранной вершины, пересчитываем координаты точки
        if v == 1
            # Первая вершина находится в начале координат (0,0) — точка "стягивается" к началу координат
            x /= 2
            y /= 2
        elseif v == 2
            # Вторая вершина находится в правом верхнем углу — точка сдвигается туда
            x = width/2 + (width/2 - x)/2
            y = height - (height - y)/2
        else
            # Третья вершина в правом нижнем углу — точка сдвигается туда
            x = width - (width - x)/2
            y = y / 2
        end
        # Перемещаем черепашку в новые координаты (ось Y инвертирована из-за системы координат картинки)
        Reposition(t, x, height-y)
        # Рисуем маленький кружок (точку) радиусом 3 пикселя
        Circle(t, 3)
    end
end
Calling the function and completing the drawing
Calling the main function that executes the algorithm, completing the drawing, saving and opening the created file
chaos()
finish()
preview()
Conclusion
In this example, we implemented an algorithm for constructing the Sierpinski triangle using the Luxor library in the Julia programming language. We have generated a random set of points, which gradually forms a fractal. This implementation demonstrates the power of simple iterative methods and makes it possible to visually see the emergence of complex geometric structures from chaotic actions. This example can be useful as a demonstration of the basics of fractal graphics, Julia programming, and working with graphics.
The example was developed using materials from Rosetta Code
