Chaos Game

Generate the Sierpinski triangle by the chaos game method


This p5.js sketch plots a fractal shape called the Sierpinski triangle (or Sierpinski sponge, or Sierpinski gasket). There are several possible ways to construct the triangle; this sketch uses one called the chaos game, which defines the corner points of the triangles as attractors, then repeatedly plots points that lie within the shape defined by those attractors.

The algorithm works by choosing a random starting point, moving it half of the distance toward one of the attractors chosen at random, plotting it, and then choosing a new random attractor to move toward, moving the point, plotting it, and so on for some fixed number of iterations. This produces the characteristic shape of the triangle.

You can choose how many points to plot; smaller numbers demonstrate the randomness of the way that the shape is built up, larger numbers generate a more complete shape.