%implementation of chaos game
%PC MA 302
%03/07/2019

%define polygon
v1=0.5;
v2=-0.5;
v3=(0.5*tan(pi/3));

z1 = complex(v1,0);
z2 = complex(v2,0);
z3 = complex(0,v3);

hold on
plot(z1);
plot(z2);
plot(z3);

%plot polygon
plot([z1 z2],'LineWidth',2,'color','k');
plot([z2 z3],'LineWidth',2,'color','k');
plot([z1 z3],'LineWidth',2,'color','k');


%start with any point inside the triangle
x=rand;
y=rand;
in = inpolygon(x,y,[-0.5,0.5,0],[0,0,0.5*tan(pi/3)]);

while(~in)
    x=rand;
    y=rand;
    in = inpolygon(x,y,[-0.5,0.5,0],[0,0,0.5*tan(pi/3)]);
end
zrand = complex(x,y);


plot(z1,'r.','MarkerSize',20)
plot(z2,'b.','MarkerSize',20)
plot(z3,'g.','MarkerSize',20)

%plot(zrand,'k.','MarkerSize',20);
znew = zrand;
N = 5000;
for i=1:N
    %roll dice
    roll = randi([1 6]);
    
    %random assignments of the 3 colors
    switch(roll)
        case {1,2}
            znew = znew+0.5*(z1-znew);
            plot(znew,'r.','MarkerSize',15)
            title(['N = ',num2str(i)]);
            drawnow
        case{3,4}
            znew = znew+0.5*(z2-znew);            
            plot(znew,'b.','MarkerSize',15)
            title(['N = ',num2str(i)]);
            drawnow
        case{5,6}
            znew = znew+0.5*(z3-znew);    
            plot(znew,'g.','MarkerSize',15)
            title(['N = ',num2str(i)]);
            drawnow
        otherwise
            error('Not a six sided die');
    end  
end

hold off