Sierpinski curve: Difference between revisions

Content added Content deleted
m (→‎{{header|zkl}}: added code)
m (→‎{{header|zkl}}: generalize)
Line 427: Line 427:
Uses Image Magick and
Uses Image Magick and
the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<lang zkl>sierpinskiArrowheadCurve(5) : turtle(_);
<lang zkl>sierpinskiCurve(5) : turtle(_,45,45); // n=5 --> 11,606 characters


fcn sierpinskiCurve(order){
fcn sierpinskiArrowheadCurve(n){ // Lindenmayer system --> Data of As & Bs
LSystem("F--XF--F--XF",Dictionary("X","XF+G+XF--F--XF+G+X"), order)
var [const] A="AF+G+AF--F--AF+G+A", B=""; // Production rules
}
var [const] Axiom="F--AF--F--AF";
fcn LSystem(axiom,rules,order){ // Lindenmayer system
buf1,buf2 := Data(Void,Axiom).howza(3), Data().howza(3); // characters
buf1,buf2 := Data(Void,axiom).howza(3), Data().howza(3); // characters
do(n){
do(order){
buf1.pump(buf2.clear(),fcn(c){ if(c=="A") A else if(c=="B") B else c });
buf1.pump(buf2.clear(),'wrap(c){ if(a:=rules.find(c)) a else c });
t:=buf1; buf1=buf2; buf2=t; // swap buffers
t:=buf1; buf1=buf2; buf2=t; // swap buffers
}
}
buf1
buf1 // n=5 --> 11,606 characters
}
}


fcn turtle(curve){ // Turtle with that can turn +-45*
fcn turtle(curve,angle,startAngle){ // angles in degrees
const D=10.0, a45=45;
const D=10.0;
dir:=startAngle;
dir:=a45; // start direction depends on order
img,color := PPM(800,800), 0x00ff00; // green on black
img,color := PPM(800,800), 0x00ff00; // green on black
x,y := 15, img.h - x;
x,y := 15, img.h - x;
foreach c in (curve){ // A & B are no-op during drawing
foreach c in (curve){
switch(c){
switch(c){
case("F","G"){ // draw forward
case("F","G"){ // draw forward
Line 451: Line 452:
img.line(x,y, (x+=a.round()),(y+=b.round()), color)
img.line(x,y, (x+=a.round()),(y+=b.round()), color)
}
}
case("+"){ dir=(dir + a45)%360; } // turn left 45*
case("+"){ dir=(dir + angle)%360; } // turn left angle
case("-"){ dir=(dir - a45)%360; } // turn right 45*
case("-"){ dir=(dir - angle)%360; } // turn right angle
}
}
}
}