The Chaos Game is a method of generating the attractor of an iterated function system (IFS).

One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.



Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random.

After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.



See also
 The Game of Chaos


//Input
n_sides = 3;
side_length = 1;
ratio = 0.5;
n_steps = 1.0d5;
first_step = 0;
 
if n_sides<3 then
    error("n_sides should be at least 3.");
end
 
//Calculating vertices' positions
theta = (2 * %pi) / n_sides;
alpha = (180 - (360/n_sides)) / 2 * (%pi/180);
radius = (sin(theta) / side_length) / sin(alpha);
vertices = zeros(1,n_sides);
for i=1:n_sides
    vertices(i) = radius * exp( %i * theta * (i-1) ); //equally spaced vertices over a circumference
                                                      //centered on 0 + 0i, or (0,0)
end
clear theta alpha radius i
 
 
//Iterations
tic();
points = zeros(1,n_steps);
points(1) = first_step;
i = 2;
while i <= n_steps
    random=grand(1,'prm',[1:n_sides]'); //sort vertices randomly
    random=random(1);                   //choose the first random vertices
 
    points(i) = ( vertices(random) - points(i-1) ) * (1-ratio) + points(i-1);
 
    i = i + 1;  
end
time=toc();
disp('Time: '+string(time)+'s.');
 
//Ploting
scf(0); clf();
xname('Chaos game: '+string(n_sides)+'-sides polygon');
plot2d(real(points),imag(points),0)
plot2d(real(vertices),imag(vertices),-3);
set(gca(),'isoview','on');