

Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.

sierpinskiSquareCurve(4) : turtle(_);
 
fcn sierpinskiSquareCurve(n){	// Lindenmayer system --> Data of As
   var [const] A="AF-F+F-AF+F+AF-F+F-A", B="";  // Production rules
   var [const] Axiom="F+AF+F+AF";
   buf1,buf2 := Data(Void,Axiom).howza(3), Data().howza(3);  // characters
   do(n){
      buf1.pump(buf2.clear(),fcn(c){ if(c=="A") A else if(c=="B") B else c });
      t:=buf1; buf1=buf2; buf2=t;	// swap buffers
   }
   buf1		// n=4 --> 3,239 characters
}
 
fcn turtle(curve){	// a "square" turtle, directions are +-90*
   const D=10;
   ds,dir := T( T(D,0), T(0,-D), T(-D,0), T(0,D) ), 2; // turtle offsets
   dx,dy := ds[dir];
   img,color := PPM(650,650), 0x00ff00;  // green on black
   x,y := img.w/2, 10;
   curve.replace("A","").replace("B","");  // A & B are no-op during drawing
   foreach c in (curve){
      switch(c){
	 case("F"){ img.line(x,y, (x+=dx),(y+=dy), color) }  // draw forward
	 case("+"){ dir=(dir+1)%4; dx,dy = ds[dir] } // turn right 90*
	 case("-"){ dir=(dir-1)%4; dx,dy = ds[dir] } // turn left 90*
      }
   }
   img.writeJPGFile("sierpinskiSquareCurve.zkl.jpg");
}