Koch curve: Difference between revisions

82,607 bytes added ,  1 month ago
m
m (→‎{{header|Processing Python mode}}: make subhead of Processing)
 
(77 intermediate revisions by 28 users not shown)
Line 2:
 
Draw a Koch curve. See details: [https://en.wikipedia.org/wiki/Koch_snowflake Koch curve]
 
=={{header|Action!}}==
Action! language does not support recursion. Therefore an iterative approach with a stack has been proposed.
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"
 
DEFINE MAXSIZE="20"
 
INT ARRAY SinTab=[
0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83
88 92 96 100 104 108 112 116 120 124 128 132 136 139 143
147 150 154 158 161 165 168 171 175 178 181 184 187 190
193 196 199 202 204 207 210 212 215 217 219 222 224 226
228 230 232 234 236 237 239 241 242 243 245 246 247 248
249 250 251 252 253 254 254 255 255 255 256 256 256 256]
 
BYTE ARRAY
depthStack(MAXSIZE),stageStack(MAXSIZE)
BYTE stacksize=[0]
 
INT FUNC Sin(INT a)
WHILE a<0 DO a==+360 OD
WHILE a>360 DO a==-360 OD
IF a<=90 THEN
RETURN (SinTab(a))
ELSEIF a<=180 THEN
RETURN (SinTab(180-a))
ELSEIF a<=270 THEN
RETURN (-SinTab(a-180))
ELSE
RETURN (-SinTab(360-a))
FI
RETURN (0)
 
INT FUNC Cos(INT a)
RETURN (Sin(a-90))
 
BYTE FUNC IsEmpty()
IF stacksize=0 THEN RETURN (1) FI
RETURN (0)
 
BYTE FUNC IsFull()
IF stacksize=MAXSIZE THEN RETURN (1) FI
RETURN (0)
 
PROC Push(BYTE depth,stage)
IF IsFull() THEN Break() FI
depthStack(stacksize)=depth
stageStack(stackSize)=stage
stacksize==+1
RETURN
 
PROC Pop(BYTE POINTER depth,stage)
IF IsEmpty() THEN Break() FI
stacksize==-1
depth^=depthStack(stacksize)
stage^=stageStack(stacksize)
RETURN
 
PROC DrawKoch(INT x,y REAL POINTER len BYTE depth)
BYTE stage
INT angle=[180],c
REAL rx,ry,r256,tmp1,tmp2
 
IntToReal(x,rx)
IntToReal(y,ry)
IntToReal(256,r256)
Push(depth,0)
 
WHILE IsEmpty()=0
DO
Pop(@depth,@stage)
IF depth=0 THEN
Plot(x,y)
;x==+Cos(angle)*len/256
c=Cos(angle)
IntToRealForNeg(c,tmp1)
RealDiv(tmp1,r256,tmp2)
RealMult(tmp2,len,tmp1)
RealAdd(rx,tmp1,tmp2)
RealAssign(tmp2,rx)
x=RealToInt(rx)
;y==-Sin(angle)*len/256
c=Sin(angle)
IntToRealForNeg(c,tmp1)
RealDiv(tmp1,r256,tmp2)
RealMult(tmp2,len,tmp1)
RealSub(ry,tmp1,tmp2)
RealAssign(tmp2,ry)
y=RealToInt(ry)
DrawTo(x,y)
ELSE
IF stage=1 THEN
angle==-60
ELSEIF stage=2 THEN
angle==+120
ELSEIF stage=3 THEN
angle==-60
FI
IF stage<=3 THEN
Push(depth,stage+1)
Push(depth-1,0)
FI
FI
OD
RETURN
 
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
REAL len
 
Graphics(8+16)
Color=1
COLOR1=$0C
COLOR2=$02
 
ValR("3.7",len)
DrawKoch(10,140,len,4)
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Koch_curve.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
{{libheader|APDF}}
<syntaxhighlight lang="ada">with Ada.Command_Line;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Text_IO;
with PDF_Out;
 
procedure Koch_Curve is
 
package Real_Math is
new Ada.Numerics.Generic_Elementary_Functions (PDF_Out.Real);
use Real_Math, PDF_Out, Ada.Command_Line, Ada.Text_IO;
 
subtype Angle_Deg is Real;
type Level_Type is range 0 .. 7;
 
Purple : constant Color_Type := (0.7, 0.0, 0.5);
Length : constant Real := 400.0;
Corner : constant Point := (90.0, 580.0);
 
Level : Level_Type;
Current : Point := (0.0, 0.0);
Direction : Angle_Deg := Angle_Deg'(60.0);
Doc : PDF_Out_File;
 
procedure Koch (Level : Level_Type; Length : Real) is
begin
if Level = 0 then
Current := Current + Length * Point'(Sin (Direction, 360.0),
Cos (Direction, 360.0));
Doc.Line (Corner + Current);
else
Koch (Level - 1, Length / 3.0); Direction := Direction - 60.0;
Koch (Level - 1, Length / 3.0); Direction := Direction + 120.0;
Koch (Level - 1, Length / 3.0); Direction := Direction - 60.0;
Koch (Level - 1, Length / 3.0);
end if;
end Koch;
 
begin
if Argument_Count /= 1 then
Put_Line ("koch_curve <level>");
Put_Line (" <level> 0 .. 7");
Put_Line ("open koch.pdf to view ouput");
return;
end if;
Level := Level_Type'Value (Argument (1));
 
Doc.Create ("koch.pdf");
Doc.Page_Setup (A4_Portrait);
Doc.Margins (Margins_Type'(Left => Cm_2_5,
others => One_cm));
Doc.Color (Purple);
Doc.Move (Corner);
for A in 1 .. 3 loop
Koch (Level, Length);
Direction := Direction + 120.0;
end loop;
Doc.Finish_Path (Close_Path => True,
Rendering => Fill,
Rule => Even_Odd);
Doc.Close;
end Koch_Curve;</syntaxhighlight>
 
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-l-system}}
Generates an SVG file containing the curve using the L-System. Very similar to the Algol 68 [[Sierpinski square curve]] sample.
<br/>
Note the Algol 68 L-System library source code is on a separate page on Rosetta Code - follow the above link and then to the Talk page.
<syntaxhighlight lang="algol68">
BEGIN # Koch Curve in SVG #
# uses the RC Algol 68 L-System library for the L-System evaluation & #
# interpretation #
 
PR read "lsystem.incl.a68" PR # include L-System utilities #
 
PROC koch curve = ( STRING fname, INT size, length, order, init x, init y )VOID:
IF FILE svg file;
BOOL open error := IF open( svg file, fname, stand out channel ) = 0
THEN
# opened OK - file already exists and #
# will be overwritten #
FALSE
ELSE
# failed to open the file #
# - try creating a new file #
establish( svg file, fname, stand out channel ) /= 0
FI;
open error
THEN # failed to open the file #
print( ( "Unable to open ", fname, newline ) );
stop
ELSE # file opened OK #
 
REAL x := init x;
REAL y := init y;
INT angle := 0;
put( svg file, ( "<svg xmlns='http://www.w3.org/2000/svg' width='"
, whole( size, 0 ), "' height='", whole( size, 0 ), "'>"
, newline, "<rect width='100%' height='100%' fill='white'/>"
, newline, "<path stroke-width='1' stroke='black' fill='none' d='"
, newline, "M", whole( x, 0 ), ",", whole( y, 0 ), newline
)
);
 
LSYSTEM ssc = ( "F++F++F"
, ( "F" -> "F-F++F-F"
)
);
STRING curve = ssc EVAL order;
curve INTERPRET ( ( CHAR c )VOID:
IF c = "F" THEN
x +:= length * cos( angle * pi / 180 );
y +:= length * sin( angle * pi / 180 );
put( svg file, ( " L", whole( x, 0 ), ",", whole( y, 0 ), newline ) )
ELIF c = "+" THEN
angle +:= 60 MODAB 360
ELIF c = "-" THEN
angle -:= 60 MODAB 360
FI
);
put( svg file, ( "'/>", newline, "</svg>", newline ) );
close( svg file )
FI # sierpinski square # ;
 
koch curve( "koch.svg", 600, 5, 4, 150, 150 )
 
END
</syntaxhighlight>
 
=={{header|Amazing Hopper}}==
Based on C++ code.
Execute:
hopper src/kock_curve.com > kockcurve.svg
or
./src/kock_curve.com > kockcurve.svg
<syntaxhighlight lang="amazing hopper">
#!/usr/bin/hopper
 
#include <hopper.h>
 
#proto generateKockCurve(_S_,_I_)
#proto kochPoints(_S_,_I_)
#proto kochNext(_P_)
 
main:
SQRT3_2 = 0.86602540378444
_generate Kock Curve (600, 5)
exit(0)
 
.locals
generate Kock Curve (_SIZE_, _ITERATIONS_)
{"<svg xmlns='http://www.w3.org/2000/svg' width='"}
{_SIZE_,"' height='",_SIZE_,"'>\n"}
{"<rect width='100%' height='100%' fill='black'/>\n"}
{"<path stroke-width='1' stroke='white' fill='none' d='"} print
points=0, let( points := _koch Points(_SIZE_, _ITERATIONS_) )
vSize=0,size(points),mov(vSize),rows(vSize,nRows)
for (i = 1; n= nRows, {i}lethan(n), ++i)
iif( {i,1} eq?, {"M"} , {"L"}), [i,1]get(points), {","}, [i,2]get(points), {"\n"},print
next
{"z'/>\n</svg>\n"}print
back
 
koch Points(_SIZE_, _ITERATIONS_)
#hl {
Length = ((_SIZE_ * SQRT3_2) * 0.95)
x = (_SIZE_ - Length)/2
y = ((_SIZE_/2) - (Length * SQRT3_2 / 3))
}
points={}
{x, y},addrow(points)
{x} PLUS ( {Length}div by(2) ), {y} PLUS ( {Length} mul by ( SQRT3_2)), addrow(points)
{x} plus ( Length), {y},addrow(points)
{x, y},addrow(points)
 
for ( i = 1, {i} lethan ( _ITERATIONS_), ++i)
let clear( points := _koch Next(points))
next
{points}
back
 
koch Next(points)
vSize=0,size(points),mov(vSize)
rows(vSize,nRows)
 
output={}
 
x0 = 0,y0=0, x1=0, y1=0
 
for ( i = 1, {i}plus(1) lethan( nRows ), ++i)
#hl{
x0 = points[i,1]
y0 = points[i,2]
x1 = points[(i + 1),1]
y1 = points[(i + 1),2]
dy = y1 - y0
dx = x1 - x0
}
{x0, y0} addrow(output)
#hl{
x0 + (dx/3)
y0 + (dy/3)
}, addrow(output)
#hl{
x0 + (dx/2) - (dy * (SQRT3_2/3))
y0 + (dy/2) + (dx * (SQRT3_2/3))
},addrow(output)
#hl{
x0 + (2 * (dx/3))
y0 + (2 * (dy/3))
},addrow(output)
 
next
#hl{
x1
y1
},addrow(output)
{output}
back
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
{{trans|Go}}
Requires [https://www.autohotkey.com/boards/viewtopic.php?t=6517 Gdip Library]
<syntaxhighlight lang="autohotkey">gdip1()
KochX := 0, KochY := 0
Koch(0, 0, A_ScreenWidth, A_ScreenHeight, 4, Arr:=[])
xmin := xmax := ymin := ymax := 0
for i, point in Arr
{
xmin := A_Index = 1 ? point.x : xmin < point.x ? xmin : point.x
xmax := point.x > xmax ? point.x : xmax
ymin := A_Index = 1 ? point.y : ymin < point.y ? ymin : point.y
ymax := point.y > ymax ? point.y : ymax
}
for i, point in Arr
points .= point.x - xmin + KochX "," point.y - ymin + KochY "|"
points := Trim(points, "|")
Gdip_DrawLines(G, pPen, Points)
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
return
; ---------------------------------------------------------------
 
Koch(x1, y1, x2, y2, iter, Arr) {
Pi := 3.141592653589793
angle := Pi / 3 ; 60 degrees
x3 := (x1*2 + x2) / 3
y3 := (y1*2 + y2) / 3
x4 := (x1 + x2*2) / 3
y4 := (y1 + y2*2) / 3
x5 := x3 + (x4-x3)*Cos(angle) + (y4-y3)*Sin(angle)
y5 := y3 - (x4-x3)*Sin(angle) + (y4-y3)*Cos(angle)
if (iter > 0)
{
iter--
koch(x1, y1, x3, y3, iter, Arr)
koch(x3, y3, x5, y5, iter, Arr)
koch(x5, y5, x4, y4, iter, Arr)
koch(x4, y4, x2, y2, iter, Arr)
}
else
{
Arr[Arr.count()+1, "x"] := x1, Arr[Arr.count(), "y"] := y1
Arr[Arr.count()+1, "x"] := x3, Arr[Arr.count(), "y"] := y3
Arr[Arr.count()+1, "x"] := x5, Arr[Arr.count(), "y"] := y5
Arr[Arr.count()+1, "x"] := x4, Arr[Arr.count(), "y"] := y4
Arr[Arr.count()+1, "x"] := x2, Arr[Arr.count(), "y"] := y2
}
}
; ---------------------------------------------------------------
gdip1(){
global
If !pToken := Gdip_Startup()
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, Exit
Width := A_ScreenWidth, Height := A_ScreenHeight
Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
Gui, 1: Show, NA
hwnd1 := WinExist()
hbm := CreateDIBSection(Width, Height)
hdc := CreateCompatibleDC()
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
Gdip_SetSmoothingMode(G, 4)
pPen := Gdip_CreatePen(0xFFFF0000, 2)
}
; ---------------------------------------------------------------
gdip2(){
global
Gdip_DeleteBrush(pBrush)
Gdip_DeletePen(pPen)
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
}
; ---------------------------------------------------------------
Exit:
gdip2()
Gdip_Shutdown(pToken)
ExitApp
Return</syntaxhighlight>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">global RtoD, DtoR
<lang BASIC256>
global RtoD, DtoR
RtoD = 180 / Pi
DtoR = Pi / 180
Line 53 ⟶ 490:
 
imgsave "Koch_curve.jpg", "jpg"
end</syntaxhighlight>
end
</lang>
 
=={{header|C}}==
Interactive program which takes the width, height (of the Graphics window) and recursion level of the Koch curve as inputs, prints out usage on incorrect invocation. Requires the [http://www.cs.colorado.edu/~main/bgi/cs1300/ WinBGIm] library.
<syntaxhighlight lang="c">
<lang C>
#include<graphics.h>
#include<stdlib.h>
Line 119 ⟶ 555:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
The output of this program is an SVG file depicting a Koch snowflake.
<syntaxhighlight lang="cpp">// See https://en.wikipedia.org/wiki/Koch_snowflake
#include <fstream>
#include <iostream>
#include <vector>
 
constexpr double sqrt3_2 = 0.86602540378444; // sqrt(3)/2
 
struct point {
double x;
double y;
};
 
std::vector<point> koch_next(const std::vector<point>& points) {
size_t size = points.size();
std::vector<point> output(4*(size - 1) + 1);
double x0, y0, x1, y1;
size_t j = 0;
for (size_t i = 0; i + 1 < size; ++i) {
x0 = points[i].x;
y0 = points[i].y;
x1 = points[i + 1].x;
y1 = points[i + 1].y;
double dy = y1 - y0;
double dx = x1 - x0;
output[j++] = {x0, y0};
output[j++] = {x0 + dx/3, y0 + dy/3};
output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};
output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};
}
output[j] = {x1, y1};
return output;
}
 
std::vector<point> koch_points(int size, int iterations) {
double length = size * sqrt3_2 * 0.95;
double x = (size - length)/2;
double y = size/2 - length * sqrt3_2/3;
std::vector<point> points{
{x, y},
{x + length/2, y + length * sqrt3_2},
{x + length, y},
{x, y}
};
for (int i = 0; i < iterations; ++i)
points = koch_next(points);
return points;
}
 
void koch_curve_svg(std::ostream& out, int size, int iterations) {
out << "<svg xmlns='http://www.w3.org/2000/svg' width='"
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='black'/>\n";
out << "<path stroke-width='1' stroke='white' fill='none' d='";
auto points(koch_points(size, iterations));
for (size_t i = 0, n = points.size(); i < n; ++i)
out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n';
out << "z'/>\n</svg>\n";
}
 
int main() {
std::ofstream out("koch_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
koch_curve_svg(out, 600, 5);
return EXIT_SUCCESS;
}</syntaxhighlight>
 
{{out}}
[[Media:Koch_curve_cpp.svg]]
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|Windows,Forms,SysUtils,Types,ExtCtrls,Graphics}}
Fancy version, shows six iterations of both single-line and triangle version drawn to graphics screen. Uses vector libraries to simplify the process
 
[[File:DelphiKochSNowflake2.png|thumb|none]]
 
<syntaxhighlight lang="Delphi">
{===== These routines would normally be in extermal ======}
{===== libraries, but they are presented here for clarity ======}
 
type T2DVector=packed record
X,Y: double;
end;
 
type T2DLine = packed record
P1,P2: T2DVector;
end;
 
procedure ClearImage(Image: TImage; Color: TColor);
var R: TRect;
begin
R:=Rect(0,0,Image.Picture.Bitmap.Width,Image.Picture.Bitmap.Height);
Image.Canvas.Brush.Color:=Color;
Image.Canvas.Brush.Style:=bsSolid;
Image.Canvas.Pen.Mode:=pmCopy;
Image.Canvas.Pen.Style:=psSolid;
Image.Canvas.Pen.Color:=Color;
Image.Canvas.Rectangle(R);
Image.Invalidate;
end;
 
 
 
procedure DrawLine2D(Canvas: TCanvas; L: T2DLine; C: TColor);
{Draw Line on specified canvas}
begin
Canvas.Pen.Color:=C;
Canvas.MoveTo(Trunc(L.P1.X),Trunc(L.P1.Y));
Canvas.LineTo(Trunc(L.P2.X),Trunc(L.P2.Y));
end;
 
 
 
function MakeVector2D(const X,Y: double): T2DVector;
{Create 2D Vector from X and Y}
begin
Result.X:=X;
Result.Y:=Y;
end;
 
 
function VectorAdd2D(const V1,V2: T2DVector): T2DVector;
{Add V1 and V2}
begin
Result.X:= V1.X + V2.X;
Result.Y:= V1.Y + V2.Y;
end;
 
 
function VectorSubtract2D(const V1,V2: T2DVector): T2DVector;
{Subtract V2 from V1}
begin
Result.X:= V1.X - V2.X;
Result.Y:= V1.Y - V2.Y;
end;
 
 
function VectorABS2D(const V: T2DVector): double;
{Find ABS of vector}
begin
Result:=Sqrt(Sqr(V.X) + Sqr(V.Y));
end;
 
 
function LineLength2D(const L: T2DLine) : double; overload;
{ Find length of a line defined by P1 and P2 }
begin
Result:=VectorABS2D(VectorSubtract2D(L.P2,L.P1));
end;
 
 
 
function ScalarDivide2D(const V: T2DVector; const S: double): T2DVector;
{Divide vector by scalar}
begin
Result.X:=V.X / S;
Result.Y:=V.Y / S;
end;
 
 
 
function ScalarProduct2D(const V: T2DVector; const S: double): T2DVector;
{Multiply vector by scalar}
begin
Result.X:=V.X * S;
Result.Y:=V.Y * S;
end;
 
 
function UnitVector2D(const V: T2DVector): T2DVector;
{Return unit vector}
var L: double;
begin
L:=VectorABS2D(V);
if L=0.0 then L:=1E-99;
Result.X:=V.X / L;
Result.Y:=V.Y / L;
end;
 
 
function GetUnitNormal2D(const V: T2DVector): T2DVector; overload;
{Returns perpendicular unit vector}
begin
Result:=UnitVector2D(MakeVector2D(-V.Y, V.X));
end;
 
 
function ExtendLine2D(const L1: T2DLine; const Len: double): T2DVector;
{ Return a point that extends line L1 by Len }
var Len1,UX,UY : double;
begin
Len1 := LineLength2D(L1)+1E-9;
UX := (L1.P2.X - L1.P1.X)/Len1;
UY := (L1.P2.Y - L1.P1.Y)/Len1;
Result.X := L1.P2.X +(UX *Len);
Result.Y := L1.P2.Y+(UY *Len);
end;
 
 
 
{---------------------------------------------------------------------------}
 
{Array of lines to contain the snow flake}
 
type TLineArray = array of T2DLine;
 
{Screen and display parameters}
 
var ScreenSize: TPoint;
var SquareBox: TRect;
var BoxSize: integer;
 
procedure ConfigureScreen(Image: TImage);
{Setup screen parameters based Image component}
begin
ScreenSize:=Point(Image.Width, Image.Height);
if ScreenSize.X<ScreenSize.Y then BoxSize:=ScreenSize.X
else BoxSize:=ScreenSize.Y;
SquareBox:=Rect(0,0,BoxSize,BoxSize);
OffsetRect(SquareBox,(ScreenSize.X-BoxSize) div 2,(ScreenSize.Y-BoxSize) div 2);
end;
 
 
procedure DrawLines(Canvas: TCanvas; Lines: TLineArray);
{Draw all the lines in the snow flake}
var I: integer;
begin
for I:=0 to High(Lines) do
DrawLine2D(Canvas,Lines[I],clRed);
end;
 
 
procedure BreakLine(L: T2DLine; var L1,L2,L3,L4: T2DLine);
{Break one line into the four new lines of the next iteration}
var Len,Len3,O: double;
var Delta: TPoint;
var P1,P2,P3,P4,P5,Half: T2DVector;
begin
Len:=LineLength2D(L);
Len3:=Len/3;
O:= Sqrt(sqr(Len3)-sqr(Len3/2));
P1:=L.P1;
P2:=ExtendLine2D(L,-Len3*2);
P4:=ExtendLine2D(L,-Len3);
P5:=L.P2;
Half:=ScalarDivide2D(VectorAdd2D(P4,P2),2);
P3:=GetUnitNormal2D(VectorSubtract2D(P4,P2));
P3:=ScalarProduct2D(P3,O);
P3:=VectorAdd2D(P3,Half);
L1.P1:=P1; L1.P2:=P2;
L2.P1:=P2; L2.P2:=P3;
L3.P1:=P3; L3.P2:=P4;
L4.P1:=P4; L4.P2:=P5;
end;
 
 
 
procedure BreakAndStoreLines(Line: T2DLine; var Lines: TLineArray);
{Break one line and store the resulting four in array}
var Len: integer;
begin
Len:=Length(Lines);
SetLength(Lines,Len+4);
BreakLine(Line, Lines[Len+0],Lines[Len+1],Lines[Len+2],Lines[Len+3]);
end;
 
 
procedure BreakArray(var Lines: TLineArray);
{Break all the lines in an array and replace them with new lines}
var I: integer;
var AT: TLineArray;
begin
AT:=Lines;
SetLength(Lines,0);
for I:=0 to High(AT) do
BreakAndStoreLines(AT[I], Lines);
end;
 
procedure LineSeed(var Lines: TLineArray);
{Put single line seed in array}
var Border: integer;
begin
Border:=MulDiv(BoxSize,10,100);
SetLength(Lines,1);
Lines[0].P1:=MakeVector2D(SquareBox.Left + Border, SquareBox.Top + Border);
Lines[0].P2:=MakeVector2D(SquareBox.Right - Border, SquareBox.Top + Border);
end;
 
 
procedure TriangleSeed(var Lines: TLineArray);
{Put triangle seed in array}
const Border = 15;
var R: TRect;
var PixelBorder: integer;
var H: double;
begin
SetLength(Lines,3);
PixelBorder:=MulDiv(BoxSize,Border,100);
R.Left:=SquareBox.Left + PixelBorder;
R.Right:=SquareBox.Right - PixelBorder;
R.Top:=SquareBox.Top + MulDiv(PixelBorder,1414,1000);
R.Bottom:=SquareBox.Bottom - PixelBorder;
OffsetRect(R,0,-MulDiv(BoxSize,15,100));
 
Lines[0].P1:=MakeVector2D(R.Left, R.Bottom);
Lines[0].P2:=MakeVector2D(R.Right, R.Bottom);
 
Lines[1].P1:=Lines[0].P2;
Lines[1].P2:=MakeVector2D((R.Right+R.Left) div 2,R.Top);
 
Lines[2].P1:=Lines[1].P2;
Lines[2].P2:=Lines[0].P1;
end;
 
 
 
procedure DoKochSnowFlake(Image: TImage);
{Construct and display various Koch snow flakes}
var Lines: TLineArray;
 
procedure IterateSnowflakes;
{Iterate through six phases of snow flakes}
var I,J: integer;
begin
for I:=1 to 6 do
begin
ClearImage(Image,clWhite);
Image.Canvas.Pen.Color:=clBlack;
Image.Canvas.Rectangle(SquareBox);
Image.Canvas.TextOut(10, 15, IntToStr(I)+' '+IntToStr(Length(Lines)));
DrawLines(Image.Canvas,Lines);
Image.Repaint;
Sleep(2000);
BreakArray(Lines);
end;
end;
 
 
begin
ConfigureScreen(Image);
{Iterate snow flake line}
LineSeed(Lines);
IterateSnowflakes;
{Iterate snow flake triangle}
TriangleSeed(Lines);
IterateSnowflakes;
end;
 
</syntaxhighlight>
{{out}}
[[File:DelphiKochSNowflake1.png|thumb|none]]
<pre>
</pre>
 
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=ZZLdUoMwEIXv8xTn0tohhp/WK3wXB6llrKQDjCZv754lFWOvIOfbs3uycJ18hw/fnRFKxBKhQqwwLP0EC2sAhBotHoQ+osJeCnZ4Qk0SlcQbiRsJTfKwnnjzNMnD+oyEgxAZthdjg0Jed8I7P+PoKEaKUcV5GEXUdjRJjiIzrfyfae1E03BaL/gCPVLhsWhRpvPfhdTsz4KMqSqRJcAdU1XiyPA7puq2ZLL+Mvep5jKM/To3EzgsEzghE9g2EziBgjXWUPke3pYznK2NtJeLHkzks3bm03/dZp78hNfxXXSHeemvKCuHxaNqdFHStIV+1GeXFirV+hlI4i/h/hO5+7U0pmYIGlBjSFZrfgA= Run it]
 
<syntaxhighlight lang="easylang">
proc koch x1 y1 x2 y2 iter . .
x3 = (x1 * 2 + x2) / 3
y3 = (y1 * 2 + y2) / 3
x4 = (x1 + x2 * 2) / 3
y4 = (y1 + y2 * 2) / 3
x5 = x3 + (x4 - x3) * cos 60 + (y4 - y3) * sin 60
y5 = y3 - (x4 - x3) * sin 60 + (y4 - y3) * cos 60
if iter > 0
iter -= 1
koch x1 y1 x3 y3 iter
koch x3 y3 x5 y5 iter
koch x5 y5 x4 y4 iter
koch x4 y4 x2 y2 iter
else
line x1 y1
line x3 y3
line x5 y5
line x4 y4
line x2 y2
.
.
linewidth 0.3
x1 = 15
y1 = 30
move x1 y1
for ang = 0 step 120 to 240
x2 = x1 + 70 * cos ang
y2 = y1 + 70 * sin ang
koch x1 y1 x2 y2 4
x1 = x2
y1 = y2
.
</syntaxhighlight>
 
=={{header|Factor}}==
The approach taken is to generate a [[Thue-Morse]] sequence. Using turtle graphics, move forward for each 0 encountered and rotate 60 degrees for each 1 encountered. Remarkably, this produces a Koch curve.
<langsyntaxhighlight lang="factor">USING: accessors images images.testing images.viewer kernel
literals math math.constants math.functions sequences ;
IN: rosetta-code.koch-curve
Line 163 ⟶ 997:
] 2with each image-window ;
 
MAIN: koch-curve</langsyntaxhighlight>
{{out}}
[https://i.imgur.com/MVS8QiS.png]
 
=={{header|Forth}}==
{{works with|4tH v3.64}}
<syntaxhighlight lang="text">include lib/graphics.4th
include lib/math.4th
include lib/enter.4th
 
: (p3&p5) 2* + 3 / ; ( n1 n2 -- n2+n2+n1/3)
: (p3) rot (p3&p5) >r swap (p3&p5) r> ;
: (p5) rot swap (p3&p5) >r (p3&p5) r> ;
: (*/10K) * 10K 2 / + 10K / ; ( n1 n2 -- n1*n2/10000)
 
: koch ( x1 y1 x2 y2 n --)
dup 0> if
1- >r 2over 2over (p5)
2>r 2over 2over (p3) 2r> ( x1 y1 x2 y2 x3 y3 x5 y5 )
PI*10K 3 / >r 2over 2over rot - >r swap - >r ( R: n theta y5-y3 x5-x3)
2over r@ r"@ (sin) (*/10K) - r'@ r"@ (cos) (*/10K) +
swap r@ r"@ (cos) (*/10K) + r'@ r"@ (sin) (*/10K) +
rdrop rdrop rdrop swap ( x1 y1 x2 y2 x3 y3 x5 y5 x4 y4 R: n)
2rot 2>r 2>r 2rot 2r> 2r> 2rot ( x2 y2 x5 y5 x4 y4 x3 y3 x1 y1 R: n)
2over r@ recurse ( x2 y2 x5 y5 x4 y4 x3 y3 R: n )
2over r@ recurse ( x2 y2 x5 y5 x4 y4 R: n )
2over r@ recurse ( x2 y2 x5 y5 R: n)
2swap r> recurse ( --)
;then drop line
;
 
600 pic_width ! 600 pic_height ! \ set canvas size
color_image 255 whiteout blue \ paint blue on white
 
." Level (0-4): " enter 0 max 4 min >r
 
450 100 450 500 r@ koch \ paint the snowflake
115 300 450 100 r@ koch
450 500 115 300 r> koch
 
s" gkoch.ppm" save_image \ save the image</syntaxhighlight>
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
Const Pi = 4 * Atn(1)
Const RtoD = 180 / Pi
Line 214 ⟶ 1,086:
Sleep
End
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/L-system}}
 
'''Solution'''
 
It can be done using an [[wp:L-system|L-system]]. There are generic functions written in Fōrmulæ to compute an L-system in the page [[L-system#Fōrmulæ | L-system]].
 
The program that creates a Koch curve is:
 
[[File:Fōrmulæ - L-system - Koch's snowflake 01.png]]
 
[[File:Fōrmulæ - L-system - Koch's snowflake 02.png]]
 
=={{header|Go}}==
{{libheader|Go Graphics}}
{{trans|Ring}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 259 ⟶ 1,145:
dc.Stroke()
dc.SavePNG("koch.png")
}</langsyntaxhighlight>
 
{{out}}
Line 270 ⟶ 1,156:
Generates SVG for a Koch snowflake. To view, save to a text file with an .svg extension, and open in a browser.
 
<syntaxhighlight lang ="haskell">import ControlData.ArrowBifunctor ((***)bimap)
import Text.Printf (printf)
 
------------------------ KOCH CURVE ----------------------
kochSnowflake :: Int -> (Float, Float) -> (Float, Float) -> [(Float, Float)]
kochSnowflake ::
Int ->
(Float, Float) ->
(Float, Float) ->
[(Float, Float)]
kochSnowflake n a b =
concat $
let points@(x:xs) = [a, equilateralApex a b, b]
in concat $ zipWith (kochCurve n) points (xs ++<> [x])
where
 
points@(x : xs) = [a, equilateralApex a b, b]
kochCurve :: Int -> (Float, Float) -> (Float, Float) -> [(Float, Float)]
kochCurve n ab xy =
let go 0 (_, xy) = [xy]
go n (ab, xy) =
let (mp, mq) = midThirdOfLine ab xy
points@(_:xs) = [ab, mp, equilateralApex mp mq, mq, xy]
in go (pred n) =<< zip points xs
in ab : go n (ab, xy)
 
kochCurve ::
Int ->
(Float, Float) ->
(Float, Float) ->
[(Float, Float)]
kochCurve n ab xy = ab : go n (ab, xy)
where
go 0 (_, xy) = [xy]
go n (ab, xy) =
let (mp, mq) = midThirdOfLine ab xy
points@(_ : xs) =
[ ab,
mp,
equilateralApex mp mq,
mq,
xy
]
in go (pred n) =<< zip points xs
 
equilateralApex :: (Float, Float) -> (Float, Float) -> (Float, Float)
(Float, Float) ->
(Float, Float) ->
(Float, Float)
equilateralApex = rotatedPoint (pi / 3)
 
rotatedPoint ::
rotatedPoint :: Float -> (Float, Float) -> (Float, Float) -> (Float, Float)
Float ->
rotatedPoint theta (ox, oy) (a, b) =
(Float, Float) ->
let (dx, dy) = rotatedVector theta (a - ox, oy - b)
in (ox + dxFloat, oyFloat) - dy)>
(Float, Float)
rotatedPoint theta (ox, oy) (a, b) = (ox + dx, oy - dy)
where
(dx, dy) = rotatedVector theta (a - ox, oy - b)
 
rotatedVector :: Float -> (Float, Float) -> (Float, Float)
rotatedVector angle (x, y) =
( x * cos angle - y * sin angle, x * sin angle + y * cos angle)
x * sin angle + y * cos angle
)
 
midThirdOfLine :: (Float, Float)
-> (Float, Float) ->
-> ((Float, Float), (Float, Float))->
((Float, Float), (Float, Float))
midThirdOfLine (a, b) (x, y) =
letmidThirdOfLine (dxa, dyb) = ((x, - ay) /= 3(p, (y - b) /f 3p)
where
f = (dx +) *** (dy +)
(dx, pdy) = f ((x - a) / 3, (y - b) / 3)
in (p, f p= bimap (dx +) (dy +)
p = f (a, b)
 
-------------------------- TEST ---------------------------
 
-- TEST ---------------------------------------------------
main :: IO ()
main =
main = putStrLn $ svgFromPoints 1024 $ kochSnowflake 4 (200, 600) (800, 600)
putStrLn $
svgFromPoints 1024 $
kochSnowflake 4 (200, 600) (800, 600)
 
-- SVG ------------------------ SVG ----------------------------
svgFromPoints :: Int -> [(Float, Float)] -> String
svgFromPoints w xys =
unlines
let sw = show w
[ "<svg xmlns=\"http://www.w3.org/2000/svg\"",
showN = printf "%.2g"
points =unwords
[ "width=\"512\" height=\"512\" viewBox=\"5 5",
(unwords . fmap (((++) . showN . fst) <*> ((' ' :) . showN . snd))) xys
sw,
in unlines
sw,
[ "<svg xmlns=\"http://www.w3.org/2000/svg\""
, unwords ["width=\"512\" height=\"512\" viewBox=\"5 5", sw, sw, "\"> "]
],
, "<path d=\"M" ++ points ++ "\" "
"<path , "stroke-widthd=\"2\M" stroke=\<> points <> "red\" fill=\"transparent\"/>",
unwords , "</svg>"[
]</lang> "stroke-width=\"2\"",
"stroke=\"red\"",
"fill=\"transparent\"/>"
],
"</svg>"
]
where
sw = show w
showN = printf "%.2g"
points =
( unwords
. fmap
( ((<>) . showN . fst)
<*> ((' ' :) . showN . snd)
)
)
xys</syntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Koch.bas"
110 OPTION ANGLE DEGREES
120 SET 22,1:SET 23,0:SET 24,42:SET 25,26
Line 351 ⟶ 1,281:
290 PLOT LEFT A;FORWARD D;
300 END IF
310 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">seg=: [ + [: +/\ (0,1r3*1,(^j.(,-)_2 o.1r2),1) * -~
koch=: [: ,/ 2 seg/\ ]
 
require'plot'
tri=: ^ j. 4r3 * (_2 o. 0) * i._4
plot koch ^: 5 tri</langsyntaxhighlight>
 
[[File:J-Koch-snowflake.png]]
 
The idea is to continually expand the segments between a list of points in the complex plane. Given consecutive x and y in the list, v = (y-x)/3 is a vector representing 1/3 of the trip from x to y. An iteration building the Koch curve starts at x, advances by v, advances by v rotated by 60 degrees, advances by v rotated -60 degrees, and finally advances by another v, reaching y. x seg y produces this expansion. koch takes a list of points and expands segments between consecutive ones, producing another list. koch ^: 5 does this 5 times, and plot shows the snowflake in a window.
 
=={{header|Java}}==
<syntaxhighlight lang="java">
 
import java.awt.Point;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
 
public final class KochCurve {
public static void main(String[] aArgs) throws IOException {
List<Point> points = initialEquilateralTriangle();
for ( int i = 1; i < 5; i++ ) {
points = nextIteration(points);
}
String text = kochCurveText(points, IMAGE_SIZE);
Files.write(Paths.get("C:/Users/psnow/Desktop/koch.svg"), text.getBytes());
}
private static List<Point> initialEquilateralTriangle() {
final int margin = 50;
final int boxSize = IMAGE_SIZE - margin;
final int sideLength = Math.round(boxSize * SIN_60_DEGREES);
final int x = ( boxSize + margin - sideLength ) / 2;
final int y = Math.round(( boxSize + margin ) / 2 - sideLength * SIN_60_DEGREES / 3);
List<Point> points = Arrays.asList(
new Point(x, y),
new Point(x + sideLength / 2, Math.round(y + sideLength * SIN_60_DEGREES)),
new Point(x + sideLength, y),
new Point(x, y)
);
return points;
}
private static List<Point> nextIteration(List<Point> aPoints) {
List<Point> result = new ArrayList<Point>();
for ( int i = 0; i < aPoints.size() - 1; i++ ) {
final int x0 = aPoints.get(i).x;
final int y0 = aPoints.get(i).y;
final int x1 = aPoints.get(i + 1).x;
final int y1 = aPoints.get(i + 1).y;
final int dy = y1 - y0;
final int dx = x1 - x0;
result.add(aPoints.get(i));
result.add( new Point(x0 + dx / 3, y0 + dy / 3) );
result.add( new Point(Math.round(x0 + dx / 2 - dy * SIN_60_DEGREES / 3),
Math.round(y0 + dy / 2 + dx * SIN_60_DEGREES / 3)) );
result.add( new Point(x0 + 2 * dx / 3, y0 + 2 * dy / 3) ) ;
}
result.add(aPoints.get(aPoints.size() - 1));
return result;
}
private static String kochCurveText(List<Point> aPoints, int aSize) {
StringBuilder text = new StringBuilder();
text.append("<svg xmlns='http://www.w3.org/2000/svg'");
text.append(" width='" + aSize + "' height='" + aSize + "'>\n");
text.append("<rect style='width:100%;height:100%;fill:cyan'/>\n");
text.append("<polygon points='");
for ( int i = 0; i < aPoints.size(); i++ ) {
text.append(aPoints.get(i).x + ", " + aPoints.get(i).y + " ");
}
text.append("' style='fill:pink;stroke:black;stroke-width:2'/>\n</svg>\n");
return text.toString();
}
private static final int IMAGE_SIZE = 700;
private static final float SIN_60_DEGREES = (float) Math.sin(Math.PI / 3.0);
}
</syntaxhighlight>
{{ out }}
[[Media:kochCurve.svg]]
 
=={{header|JavaScript}}==
Line 369 ⟶ 1,385:
 
{{Trans|Haskell}}{{Trans|Python}}
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 496 ⟶ 1,512:
// MAIN ---
return main();
})();</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
This entry uses an L-system and turtle graphics to generate an SVG
file which can be viewed using a web browser, at least if the file type is `.svg`.
 
See [[Category_talk:Jq-turtle]] for the turtle.jq module used here.
Please note that the `include` directive may need to be modified
depending on the location of the included file, and the command-line
options used.
<syntaxhighlight lang="jq">include "turtle" {search: "."};
 
def rules:
{ F: "F+F--F+F",
"": "F--F--F" };
 
def koch($count):
rules as $rules
| def repeat($count):
if $count <= 0 then .
else gsub("F"; $rules["F"])
| repeat($count-1)
end;
$rules[""] | repeat($count) ;
 
def interpret($x):
if $x == "+" then turtleRotate(60)
elif $x == "-" then turtleRotate(-60)
elif $x == "F" then turtleForward(4)
else .
end;
 
def koch_curve($n):
koch($n)
| split("")
| reduce .[] as $action (turtle([0,300]) | turtleDown;
interpret($action) ) ;
 
koch_curve(5)
| draw(1200)</syntaxhighlight>
 
 
=={{header|Julia}}==
Multiple snowflake plots. Copied from https://www.juliabloggers.com/koch-snowflakes-for-the-holidays/.
<langsyntaxhighlight Julialang="julia">using Plots
 
function pointskoch(points, maxk, α = sqrt(3)/2)
Line 670 ⟶ 1,729:
#large_koch()
koch_julia()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Ring}}
This incorporates code from other relevant tasks in order to provide a runnable example. The image produced is saved to disk where it can be viewed with a utility such as EOG.
<langsyntaxhighlight lang="scala">// Version 1.2.41
 
import java.awt.Color
Line 756 ⟶ 1,815:
ImageIO.write(image, "jpg", kFile)
}
}</langsyntaxhighlight>
 
{{output}}
Line 763 ⟶ 1,822:
</pre>
 
=={{header|MathematicaLambdatalk}}==
<syntaxhighlight lang="scheme">
<lang mathematica>Graphics[{GeometricTransformation[KochCurve[5], RotationTransform[Pi, {0.5, 0}]],
{def koch
{lambda {:d :n}
{if {< :n 1}
then M:d
else {koch {/ :d 3} {- :n 1}} T-60
{koch {/ :d 3} {- :n 1}} T120
{koch {/ :d 3} {- :n 1}} T-60
{koch {/ :d 3} {- :n 1}} }}}
-> koch
 
{def K {koch 300 4}}
-> K
 
{svg {@ width="580" height="580" style="box-shadow:0 0 8px #000;"}
{polyline {@ points="{turtle 140 140 0 {K}}"
stroke="#f00" fill="transparent"}}
{polyline {@ points="{turtle 140 440 90 {K}}"
stroke="#0f0" fill="transparent"}}
{polyline {@ points="{turtle 440 440 180 {K}}"
stroke="#00f" fill="transparent"}}
{polyline {@ points="{turtle 440 140 270 {K}}"
stroke="#ff0" fill="transparent"}}
}
 
The output is a "square of Koch" which can be seen in
http://lambdaway.free.fr/lambdawalks/?view=koch
</syntaxhighlight>
 
=={{header|Logo}}==
 
{{works with|FMSLogo}}
 
<syntaxhighlight lang="fmslogo">
to ff :l :i
cs
right 90
pd
pr [lenght] show form :l 4 0
pr [iterations] show form :i 4 0
koch :l :i
end
 
to koch :len :iterations
ifelse :iterations = 1 [fd :len] [
koch :len :iterations - 1
left 60
koch :len :iterations - 1
right 120
koch :len :iterations - 1
left 60
koch :len :iterations - 1]
end
 
to zzz
ifelse YesNoBox [Welcome] [YES=run it, NO=show me the code] [ff 22 3] [edall]
end
 
Make "startup [zzz]
</syntaxhighlight>
 
=={{header|Lua}}==
Using the Bitmap class [[Bitmap#Lua|here]], with an ASCII pixel representation, then extending with <code>line()</code> as [[Bitmap/Bresenham%27s_line_algorithm#Lua|here]], then extending further..
<syntaxhighlight lang="lua">local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi
 
function Bitmap:render()
for y = 1, self.height do
print(table.concat(self.pixels[y]))
end
end
 
function Bitmap:drawKochPath(path, x, y, angle, speed, color)
local rules = {
["+"] = function() angle = angle + pi/3 end,
["-"] = function() angle = angle - pi/3 end,
["F"] = function()
local nx, ny = x+speed*cos(angle), y+speed*sin(angle)
self:line(floor(x*2+0.5), floor(y+0.5), floor(nx*2+0.5), floor(ny+0.5), color)
x, y = nx, ny
end
}
path:gsub("(.)", function(c) rules[c]() end)
end
 
function LSystem(axiom, rules, reps)
for i = 1, reps do
axiom = axiom:gsub("(.)", function(c) return rules[c] or c end)
end
return axiom
end
function KochPath(reps) return LSystem("F--F--F--", { F = "F+F--F+F" }, reps) end
 
demos = {
{ n=0, w= 11, h= 6, x=1, y= 4 },
{ n=1, w= 22, h=14, x=1, y= 9 },
{ n=2, w= 60, h=34, x=1, y=24 },
{ n=3, w=168, h=96, x=1, y=71 }
}
for _,d in ipairs(demos) do
bitmap = Bitmap(d.w, d.h)
bitmap:clear(".")
bitmap:drawKochPath(KochPath(d.n), d.x, d.y, 0, 3, "@")
bitmap:render()
print()
end</syntaxhighlight>
{{out}}
<pre style="font-size:50%">...........
.....@.....
....@.@....
...@...@...
..@@@@@@@..
...........
 
......................
...........@..........
..........@.@.........
.........@...@........
..@@@@@@@.....@@@@@@@.
...@..............@...
....@@...........@....
....@.............@...
...@...............@..
..@@@@@@@.....@@@@@@@.
.........@...@........
..........@.@.........
...........@..........
......................
 
............................................................
.............................@@.............................
............................@..@............................
....................@@@@@@@@....@@@@@@@.....................
.....................@...............@......................
......................@.............@.......................
...........@@..........@...........@@..........@@...........
..........@..@........@..............@........@..@..........
..@@@@@@@@....@@@@@@@@................@@@@@@@@....@@@@@@@...
...@...................................................@....
....@.................................................@.....
.....@...............................................@......
....@.................................................@.....
...@...................................................@....
..@@@@@@@........................................@@@@@@@@...
.........@......................................@...........
..........@@...................................@............
..........@.....................................@...........
.........@.......................................@..........
..@@@@@@@.........................................@@@@@@@...
...@..................................................@.....
....@@...............................................@......
....@.................................................@.....
...@...................................................@....
..@@@@@@@.....@@@@@@@.................@@@@@@@.....@@@@@@@...
.........@...@.......@...............@.......@...@..........
..........@.@.........@.............@.........@.@...........
...........@...........@...........@@..........@............
......................@..............@......................
....................@@@@@@@.....@@@@@@@.....................
...........................@...@............................
............................@.@.............................
.............................@..............................
............................................................
 
........................................................................................................................................................................
...................................................................................@@...................................................................................
..................................................................................@..@..................................................................................
..........................................................................@@@@@@@@....@@@@@@@...........................................................................
...........................................................................@...............@............................................................................
............................................................................@.............@.............................................................................
.................................................................@...........@...........@...........@..................................................................
................................................................@.@.........@.............@.........@.@.................................................................
...............................................................@...@.......@...............@.......@...@................................................................
........................................................@@@@@@@.....@@@@@@@.................@@@@@@@.....@@@@@@@.........................................................
.........................................................@..................................................@...........................................................
..........................................................@@...............................................@............................................................
..........................................................@.................................................@...........................................................
.........................................................@...................................................@..........................................................
........................................................@@@@@@@........................................@@@@@@@@.........................................................
...............................................................@......................................@.................................................................
.............................@..................................@@...................................@...................................@..............................
............................@.@.................................@.....................................@.................................@.@.............................
...........................@...@...............................@.......................................@...............................@...@............................
....................@@@@@@@.....@@@@@@@.................@@@@@@@.........................................@@@@@@@.................@@@@@@@.....@@@@@@@.....................
.....................@...............@...................@...................................................@...................@...............@......................
......................@.............@.....................@.................................................@.....................@.............@.......................
...........@@..........@...........@@..........@@..........@...............................................@@..........@@..........@...........@@..........@@...........
..........@..@........@..............@........@..@........@..................................................@........@..@........@..............@........@..@..........
..@@@@@@@@....@@@@@@@@................@@@@@@@@....@@@@@@@@....................................................@@@@@@@@....@@@@@@@@................@@@@@@@@....@@@@@@@...
...@...............................................................................................................................................................@....
....@.............................................................................................................................................................@.....
.....@...........................................................................................................................................................@@.....
....@..............................................................................................................................................................@....
..@@@@@@@.....................................................................................................................................................@@@@@@@...
.........@...................................................................................................................................................@..........
..........@.................................................................................................................................................@...........
...........@...............................................................................................................................................@............
..........@.................................................................................................................................................@...........
.........@...................................................................................................................................................@..........
..@@@@@@@.....................................................................................................................................................@@@@@@@...
...@..............................................................................................................................................................@.....
....@@...........................................................................................................................................................@......
....@.............................................................................................................................................................@.....
...@...............................................................................................................................................................@....
..@@@@@@@....@@@@@@@@............................................................................................................................@@@@@@@@....@@@@@@@@...
.........@..@........@..........................................................................................................................@........@..@...........
..........@@..........@@.......................................................................................................................@..........@@............
......................@.........................................................................................................................@.......................
.....................@...........................................................................................................................@......................
....................@@@@@@@.................................................................................................................@@@@@@@.....................
...........................@...............................................................................................................@............................
............................@.............................................................................................................@.............................
.............................@...........................................................................................................@@.............................
............................@..............................................................................................................@............................
....................@@@@@@@@................................................................................................................@@@@@@@.....................
.....................@...........................................................................................................................@......................
......................@.........................................................................................................................@.......................
...........@@..........@.......................................................................................................................@@..........@@...........
..........@..@........@..........................................................................................................................@........@..@..........
..@@@@@@@@....@@@@@@@@............................................................................................................................@@@@@@@@....@@@@@@@...
...@...............................................................................................................................................................@....
....@.............................................................................................................................................................@.....
.....@...........................................................................................................................................................@......
....@.............................................................................................................................................................@.....
...@...............................................................................................................................................................@....
..@@@@@@@....................................................................................................................................................@@@@@@@@...
.........@..................................................................................................................................................@...........
..........@@...............................................................................................................................................@............
..........@.................................................................................................................................................@...........
.........@...................................................................................................................................................@..........
..@@@@@@@.....................................................................................................................................................@@@@@@@...
...@..............................................................................................................................................................@.....
....@@...........................................................................................................................................................@......
....@.............................................................................................................................................................@.....
...@...............................................................................................................................................................@....
..@@@@@@@.....@@@@@@@.................@@@@@@@.....@@@@@@@.....................................................@@@@@@@.....@@@@@@@.................@@@@@@@.....@@@@@@@...
.........@...@.......@...............@.......@...@.......@...................................................@.......@...@.......@...............@.......@...@..........
..........@.@.........@.............@.........@.@.........@.................................................@.........@.@.........@.............@.........@.@...........
...........@...........@...........@@..........@...........@...............................................@@..........@...........@...........@@..........@............
......................@..............@....................@..................................................@....................@..............@......................
....................@@@@@@@.....@@@@@@@.................@@@@@@@.........................................@@@@@@@.................@@@@@@@.....@@@@@@@.....................
...........................@...@...............................@.......................................@...............................@...@............................
............................@.@.................................@.....................................@.................................@.@.............................
.............................@...................................@...................................@@..................................@..............................
................................................................@......................................@................................................................
........................................................@@@@@@@@........................................@@@@@@@.........................................................
.........................................................@...................................................@..........................................................
..........................................................@.................................................@...........................................................
...........................................................@...............................................@............................................................
..........................................................@.................................................@...........................................................
.........................................................@...................................................@..........................................................
........................................................@@@@@@@....@@@@@@@@................@@@@@@@@....@@@@@@@@.........................................................
...............................................................@..@........@..............@........@..@.................................................................
................................................................@@..........@@...........@..........@@..................................................................
............................................................................@.............@.............................................................................
...........................................................................@...............@............................................................................
..........................................................................@@@@@@@....@@@@@@@@...........................................................................
.................................................................................@..@...................................................................................
..................................................................................@@....................................................................................
........................................................................................................................................................................</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Graphics[{GeometricTransformation[KochCurve[5], RotationTransform[Pi, {0.5, 0}]],
GeometricTransformation[KochCurve[5], RotationTransform[-Pi/3, {1, 0}]],
GeometricTransformation[KochCurve[5], RotationTransform[Pi/3, {0, 0}]]}]</langsyntaxhighlight>
 
=={{header|Maxima}}==
Using [https://riotorto.users.sourceforge.net/Maxima/gnuplot/turtle/turtle.mac turtle.mac] package for turtle graphics in Maxima.
<syntaxhighlight lang="maxima">
set_draw_defaults(
terminal = svg,
dimensions = [350,350],
proportional_axes = xy) $
 
wxdraw2d(
turtle(
to(koch_snowflake, [n, len],
ifelse(n = 0,
[forward(len)],
[koch_snowflake(n - 1, len),
right(60),
koch_snowflake(n - 1, len),
left(120),
koch_snowflake(n - 1, len),
right(60),
koch_snowflake(n - 1, len)]
)
),
repeat(6,
koch_snowflake(5, 300),
right(60)
)
)
);
</syntaxhighlight>
[[File:KochSnowflake.png|thumb|center]]
 
=={{header|Nim}}==
{{works with|nim|0.191.4.2}}
{{libheader|nim-libgd}}
<langsyntaxhighlight lang="nim">
from math import sin, cos, PI
import libgd
Line 813 ⟶ 2,164:
 
main()
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use SVG;
use List::Util qw(max min);
 
Line 852 ⟶ 2,203:
open $fh, '>', 'koch_curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh;</langsyntaxhighlight>
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/koch_curve.svg Koch curve] (offsite image)
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
<lang Phix>-- demo\rosetta\Koch_curve.exw
You can run this online [http://phix.x10.mx/p2js/koch.htm here].
include pGUI.e
<!--<syntaxhighlight lang="phix">(phixonline)-->
 
<span style="color: #000080;font-style:italic;">--
Ihandle dlg, canvas
-- demo\rosetta\Koch_curve.exw
cdCanvas cddbuffer, cdcanvas
-- ===========================
 
--</span>
procedure koch(atom x1, y1, x2, y2, integer iter)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
atom angle = -PI/3, -- -60 degrees
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
x3 := (x1*2 + x2) / 3,
y3 := (y1*2 + y2) / 3,
x4 := (x1 + x2*2) / 3,
y4 := (y1 + y2*2) / 3,
x5 := x3 + (x4-x3)*cos(angle) + (y4-y3)*sin(angle),
y5 := y3 - (x4-x3)*sin(angle) + (y4-y3)*cos(angle)
if iter>0 then
iter -= 1
koch(x1, y1, x3, y3, iter)
koch(x3, y3, x5, y5, iter)
koch(x5, y5, x4, y4, iter)
koch(x4, y4, x2, y2, iter)
else
cdCanvasVertex(cddbuffer, x1, y1)
cdCanvasVertex(cddbuffer, x3, y3)
cdCanvasVertex(cddbuffer, x5, y5)
cdCanvasVertex(cddbuffer, x4, y4)
cdCanvasVertex(cddbuffer, x2, y2)
end if
end procedure
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span>
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span>
atom {w,h} = IupGetIntInt(canvas, "DRAWSIZE")
if w>h then ox = floor((w-h)/2); w=h
<span style="color: #004080;">integer</span> <span style="color: #000000;">ox</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">oy</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
else oy = floor((h-w)/2); h=w end if
atom {x,y} = {w*0.05+w/6,h*0.05+h/4}
<span style="color: #008080;">procedure</span> <span style="color: #000000;">koch</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y2</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">iter</span><span style="color: #0000FF;">)</span>
{w,h} = {w*0.6,h*0.6}
<span style="color: #004080;">atom</span> <span style="color: #000000;">angle</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- -60 degrees</span>
cdCanvasActivate(cddbuffer)
<span style="color: #000000;">x3</span> <span style="color: #0000FF;">:=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">x1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">x2</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span>
cdCanvasBegin(cddbuffer, CD_OPEN_LINES)
<span style="color: #000000;">y3</span> <span style="color: #0000FF;">:=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">y1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">y2</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span>
koch(x,y,x+w/2,y+h,4)
<span style="color: #000000;">x4</span> <span style="color: #0000FF;">:=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">x1</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">x2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span>
koch(x+w/2,y+h,x+w,y,4)
<span style="color: #000000;">y4</span> <span style="color: #0000FF;">:=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">y1</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">y2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span>
koch(x+w,y,x,y,4)
<span style="color: #000000;">x5</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">x3</span> <span style="color: #0000FF;">+</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">x4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">x3</span><span style="color: #0000FF;">)*</span><span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">+</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">y4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">y3</span><span style="color: #0000FF;">)*</span><span style="color: #7060A8;">sin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">),</span>
cdCanvasEnd(cddbuffer)
<span style="color: #000000;">y5</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">y3</span> <span style="color: #0000FF;">-</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">x4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">x3</span><span style="color: #0000FF;">)*</span><span style="color: #7060A8;">sin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">+</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">y4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">y3</span><span style="color: #0000FF;">)*</span><span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">)</span>
cdCanvasFlush(cddbuffer)
<span style="color: #008080;">if</span> <span style="color: #000000;">iter</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
return IUP_DEFAULT
<span style="color: #000000;">iter</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
end function
<span style="color: #000000;">koch</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">iter</span><span style="color: #0000FF;">)</span>
 
<span style="color: #000000;">koch</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">iter</span><span style="color: #0000FF;">)</span>
function map_cb(Ihandle ih)
<span style="color: #000000;">koch</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">iter</span><span style="color: #0000FF;">)</span>
cdcanvas = cdCreateCanvas(CD_IUP, ih)
<span style="color: #000000;">koch</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">iter</span><span style="color: #0000FF;">)</span>
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
<span style="color: #008080;">else</span>
cdCanvasSetBackground(cddbuffer, CD_WHITE)
<span style="color: #7060A8;">cdCanvasVertex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ox</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">oy</span><span style="color: #0000FF;">)</span>
cdCanvasSetForeground(cddbuffer, CD_BLUE)
<span style="color: #7060A8;">cdCanvasVertex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x3</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ox</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y3</span><span style="color: #0000FF;">+</span><span style="color: #000000;">oy</span><span style="color: #0000FF;">)</span>
return IUP_DEFAULT
<span style="color: #7060A8;">cdCanvasVertex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x5</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ox</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y5</span><span style="color: #0000FF;">+</span><span style="color: #000000;">oy</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #7060A8;">cdCanvasVertex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x4</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ox</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y4</span><span style="color: #0000FF;">+</span><span style="color: #000000;">oy</span><span style="color: #0000FF;">)</span>
 
<span style="color: #7060A8;">cdCanvasVertex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ox</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">oy</span><span style="color: #0000FF;">)</span>
procedure main()
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
IupOpen()
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
canvas = IupCanvas(NULL)
<span style="color: #008080;">function</span> <span style="color: #000000;">redraw_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*posx*/</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">/*posy*/</span><span style="color: #0000FF;">)</span>
IupSetAttribute(canvas, "RASTERSIZE", "512x512") -- initial size
<span style="color: #004080;">atom</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">)</span>
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
<span style="color: #008080;">if</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">></span><span style="color: #000000;">h</span> <span style="color: #008080;">then</span> <span style="color: #000000;">ox</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">w</span><span style="color: #0000FF;">-</span><span style="color: #000000;">h</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">);</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">=</span><span style="color: #000000;">h</span>
 
<span style="color: #008080;">else</span> <span style="color: #000000;">oy</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">h</span><span style="color: #0000FF;">-</span><span style="color: #000000;">w</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">);</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">=</span><span style="color: #000000;">w</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
dlg = IupDialog(canvas)
<span style="color: #004080;">atom</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.05</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">/</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.05</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h</span><span style="color: #0000FF;">/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}</span>
IupSetAttribute(dlg, "TITLE", "Koch curve")
<span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.6</span><span style="color: #0000FF;">}</span>
IupCloseOnEscape(dlg)
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
<span style="color: #7060A8;">cdCanvasBegin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_OPEN_LINES</span><span style="color: #0000FF;">)</span>
 
<span style="color: #000000;">koch</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
IupMap(dlg)
<span style="color: #000000;">koch</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
<span style="color: #000000;">koch</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
IupShowXY(dlg,IUP_CENTER,IUP_CENTER)
<span style="color: #7060A8;">cdCanvasEnd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
IupMainLoop()
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
IupClose()
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
main()</lang>
<span style="color: #008080;">function</span> <span style="color: #000000;">map_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cdcanvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_IUP</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cddbuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_DBUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetBackground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_WHITE</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetForeground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_BLUE</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupCanvas</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"RASTERSIZE=512x512"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetCallbacks</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"MAP_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"map_cb"</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">"ACTION"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"redraw_cb"</span><span style="color: #0000FF;">)})</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="Koch curve"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- release the minimum limitation</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|Processing}}==
<langsyntaxhighlight lang="java">int l = 300;
 
void setup() {
Line 976 ⟶ 2,335:
kcurve(0, s);
popMatrix();
}</langsyntaxhighlight>'''The sketch can be run online''' :<BR> [https://www.openprocessing.org/sketch/848209 here.]
 
==={{header|Processing Python mode}}===
<langsyntaxhighlight lang="python">l = 300
 
def setup():
Line 1,021 ⟶ 2,380:
rotate(radians(-120))
kcurve(0, s)
popMatrix()</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
Produces an SVG file showing a Koch snowflake.
<syntaxhighlight lang="prolog">main:-
write_koch_snowflake('koch_snowflake.svg').
 
write_koch_snowflake(File):-
open(File, write, Stream),
koch_snowflake(Stream, 600, 5),
close(Stream).
 
koch_snowflake(Stream, Size, N):-
format(Stream, "<svg xmlns='http://www.w3.org/2000/svg' width='~d' height='~d'>\n",
[Size, Size]),
write(Stream, "<rect width='100%' height='100%' fill='black'/>\n"),
write(Stream, "<path stroke-width='1' stroke='white' fill='none' d='"),
Sqrt3_2 = 0.86602540378444,
Length is Size * Sqrt3_2 * 0.95,
X0 is (Size - Length)/2,
Y0 is Size/2 - Length * Sqrt3_2/3,
X1 is X0 + Length/2,
Y1 is Y0 + Length * Sqrt3_2,
X2 is X0 + Length,
format(Stream, 'M ~g,~g ', [X0, Y0]),
koch_curve(Stream, X0, Y0, X1, Y1, N),
koch_curve(Stream, X1, Y1, X2, Y0, N),
koch_curve(Stream, X2, Y0, X0, Y0, N),
write(Stream, "z'/>\n</svg>\n").
 
koch_curve(Stream, _, _, X1, Y1, 0):-
!,
format(Stream, 'L ~g,~g\n', [X1, Y1]).
koch_curve(Stream, X0, Y0, X1, Y1, N):-
N > 0,
Sqrt3_2 = 0.86602540378444,
N1 is N - 1,
Dx is X1 - X0,
Dy is Y1 - Y0,
X2 is X0 + Dx/3,
Y2 is Y0 + Dy/3,
X3 is X0 + Dx/2 - Dy * Sqrt3_2/3,
Y3 is Y0 + Dy/2 + Dx * Sqrt3_2/3,
X4 is X0 + 2 * Dx/3,
Y4 is Y0 + 2 * Dy/3,
koch_curve(Stream, X0, Y0, X2, Y2, N1),
koch_curve(Stream, X2, Y2, X3, Y3, N1),
koch_curve(Stream, X3, Y3, X4, Y4, N1),
koch_curve(Stream, X4, Y4, X1, Y1, N1).</syntaxhighlight>
 
{{out}}
[[Media:Koch_snowflake_prolog.svg]]
 
=={{header|Python}}==
Line 1,028 ⟶ 2,439:
 
{{Trans|Haskell}}
<langsyntaxhighlight lang="python">'''Koch curve'''
 
from math import cos, pi, sin
Line 1,041 ⟶ 2,452:
'''
points = [a, equilateralApex(a, b), b]
return chain.from_iterable(map(
map(kochCurve(n), points, points[1:] + [points[0]])
) points,
points[1:] + [points[0]]
))
 
 
# kochCurve :: Int -> (Float, Float) -> (Float, Float)
# -> [(Float, Float)]
def kochCurve(n):
'''List of points on a Koch curve of order n,
starting at point ab, and ending at point xy.
'''
def koch(n, abxy):
def goTuple(ab, xyabxy) = abxy:
if 0 = ab, xy = n:abxy
returnif [xy]0 == n:
else: return [xy]
(mp, mq) = midThirdOfLine(ab, xy)else:
points mp, mq = [midThirdOfLine(ab, xy)
ab,points = [
mp ab,
equilateralApex(mp, mq) mp,
equilateralApex(mp, mq),
xy mq,
] xy
return concatMap(curry(koch)(n - 1))( ]
zip(points,return points[1:])list(
) chain.from_iterable(map(
return lambda ab, xy: [ab] + koch(n, (ab,- xy)1),
zip(points, points[1:])
))
)
return goTuple
 
def go(ab, xy):
return [ab] + koch(n)((ab, xy))
return go
 
 
# equilateralApex :: (Float, Float) -> (Float, Float) -> (Float, Float)
def equilateralApex(p, q):
'''Apex of triangle with base p q.'''
'''
return rotatedPoint(pi / 3)(p, q)
 
Line 1,084 ⟶ 2,506:
'''
def go(xy, ab):
(ox, oy) = xy
(a, b) = ab
(dx, dy) = rotatedVector(theta, (a - ox, oy - b))
return (ox + dx, oy - dy)
return lambda xy, ab: go(xy, ab)
 
 
# rotatedVector :: Float -> (Float, Float) -> (Float, Float)
def rotatedVector(theta, xy):
'''The vector xy rotated by theta radians.'''
(x, y) = xy'''
x, y = xy
return (
x * cos(theta) - y * sin(theta),
Line 1,115 ⟶ 2,538:
 
 
# TEST -------------------------- TEST --------------------------
# main :: IO ()
def main():
'''SVG for Koch snowflake of order 4.'''
'''
print(
svgFromPoints(1024)(
Line 1,128 ⟶ 2,552:
 
 
# SVG -------------------------- SVG ---------------------------
 
# svgFromPoints :: Int -> [(Float, Float)] -> SVG String
def svgFromPoints(w):
'''Width of square canvas -> Point list -> SVG string'''.
'''
 
def go(w, xys):
xs = ' '.join(map(
lambda xy: str(round(xy[0], 2)) + ' ' + str(round(xy[1], 2)),
xys
))
return '\n'.join([
['<svg xmlns="http://www.w3.org/2000/svg"',
f'width="512" height="512" viewBox="5 5 {w} {w}">',
f'<path d="M{xs}" ',
'stroke-width="2" stroke="red" fill="transparent"/>',
'</svg>'
])
return )go
return lambda xys: go(w, xys)
 
 
# MAIN ---
# GENERIC -------------------------------------------------
if __name__ == '__main__':
main()</syntaxhighlight>
 
===String rewriting===
# concatMap :: (a -> [b]) -> [a] -> [b]
<syntaxhighlight lang="python">import numpy as np
def concatMap(f):
import matplotlib.pyplot as plt
'''A concatenated list or string over which a function
from matplotlib.colors import hsv_to_rgb as hsv
has been mapped.
The list monad can be derived by using a function f which
wraps its output in a list,
(using an empty list to represent computational failure).
'''
return lambda xs: (''.join if isinstance(xs, str) else list)(
chain.from_iterable(map(f, xs))
)
 
def curve(axiom, rules, angle, depth):
for _ in range(depth):
axiom = ''.join(rules[c] if c in rules else c for c in axiom)
 
# curry :: (( a, b)x, ->y c)= ->0, a -> b ->[0], c[0]
for c in axiom:
def curry(f):
match c:
'''A curried function derived
from a function over a tuple.case '+':
a += 1
'''
return lambda x: lambda y: f(x, y) case '-':
a -= 1
case 'F' | 'G':
x.append(x[-1] + np.cos(a*angle*np.pi/180))
y.append(y[-1] + np.sin(a*angle*np.pi/180))
 
l = len(x)
# this is very slow, but pretty colors
for i in range(l - 1):
plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))
plt.gca().set_aspect(1)
plt.show()
 
curve('F++F++F', {'F': 'F+F--F+F'}, 60, 5)
# MAIN ---
#curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
if __name__ == '__main__':
#curve('F+XF+F+XF', {'X': 'XF-F+F-XF+F+XF-F+F-X'}, 90, 5)
main()</lang>
#curve('F', {'F': 'G-F-G', 'G': 'F+G+F'}, 60, 7)
#curve('A', {'A': '+BF-AFA-FB+', 'B': '-AF+BFB+FA-'}, 90, 6)
#curve('FX+FX+', {'X': 'X+YF', 'Y': 'FX-Y'}, 90, 12)</syntaxhighlight>
 
=={{header|QBasic}}==
<langsyntaxhighlight lang="qbasic"> ' Chaos: start at any point, this program uses the middle of the screen (or universe. One of six
' degrees of freedom (a direction) is chosen at random (by throwing a six-sided die), and a line
' is drawn from the old point to the new point in the direction indicated by the pip on the die.
Line 1,396 ⟶ 2,830:
Y= Y + YP(N, R)
LINE -(X, Y) ' depending on the "die", draw the next part of the chaos curve.
GOTO 900 ' now, go and do another point.</langsyntaxhighlight><br><br>
 
=={{header|Quackery}}==
 
Using an L-system.
 
<syntaxhighlight lang="quackery"> [ $ "turtleduck.qky" loadfile ] now!
[ $ "" swap witheach
[ nested quackery join ] ] is expand ( $ --> $ )
[ $ "FRFLLFRF" ] is F ( $ --> $ )
[ $ "L" ] is L ( $ --> $ )
[ $ "R" ] is R ( $ --> $ )
$ "FLLFLLF"
4 times expand
turtle
20 frames
witheach
[ dup char F = iff
[ drop 3 1 walk ] done
char L = iff
[ -1 6 turn ] done
1 6 turn ]
1 frames</syntaxhighlight>
 
{{output}}
 
[[File:Quackery Koch curve.png]]
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
(require metapict)
Line 1,425 ⟶ 2,892:
(koch a c n)))
 
(scale 4 (snow 2))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 1,431 ⟶ 2,898:
{{works with|Rakudo|2018.03}}
Koch curve, actually a full Koch snowflake.
<syntaxhighlight lang="raku" perl6line>use SVG;
 
role Lindenmayer {
Line 1,461 ⟶ 2,928:
:polyline[ points => @points.join(','), :fill<white> ],
],
);</langsyntaxhighlight>
 
See: [https://github.com/thundergnat/rc/blob/master/img/koch1.svg Koch snowflake]
 
Variation using 90° angles:
<syntaxhighlight lang="raku" perl6line>use SVG;
 
role Lindenmayer {
Line 1,495 ⟶ 2,962:
:polyline[ points => @points.join(','), :fill<white> ],
],
);</langsyntaxhighlight>
See: [https://github.com/thundergnat/rc/blob/master/img/koch2.svg Koch curve variant with 90° angles]
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Koch curve
 
Line 1,567 ⟶ 3,034:
paint.drawline(x4, y4, x2, y2)
ok
</syntaxhighlight>
</lang>
Output image:
 
Line 1,576 ⟶ 3,043:
{{libheader|JRubyArt}}
Using a Lindenmayer System to produce a KochSnowflake or simple Koch Fractal
<langsyntaxhighlight lang="ruby">
attr_reader :koch
def settings
Line 1,672 ⟶ 3,139:
end
 
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
Output is a file in SVG format depicting a Koch snowflake.
<syntaxhighlight lang="rust">// [dependencies]
// svg = "0.8.0"
 
use svg::node::element::path::Data;
use svg::node::element::Path;
use svg::node::element::Rectangle;
 
const SQRT3_2: f64 = 0.86602540378444;
 
fn koch_curve(mut data: Data, x0: f64, y0: f64, x1: f64, y1: f64, order: usize) -> Data {
if order == 0 {
data = data.line_to((x1, y1));
} else {
let dx = x1 - x0;
let dy = y1 - y0;
let x2 = x0 + dx / 3.0;
let y2 = y0 + dy / 3.0;
let x3 = x0 + dx / 2.0 - dy * SQRT3_2 / 3.0;
let y3 = y0 + dy / 2.0 + dx * SQRT3_2 / 3.0;
let x4 = x0 + 2.0 * dx / 3.0;
let y4 = y0 + 2.0 * dy / 3.0;
data = koch_curve(data, x0, y0, x2, y2, order - 1);
data = koch_curve(data, x2, y2, x3, y3, order - 1);
data = koch_curve(data, x3, y3, x4, y4, order - 1);
data = koch_curve(data, x4, y4, x1, y1, order - 1);
}
data
}
 
fn write_koch_snowflake(file: &str, size: usize, order: usize) -> std::io::Result<()> {
let length = (size as f64) * SQRT3_2 * 0.95;
let x0 = ((size as f64) - length) / 2.0;
let y0 = (size as f64) / 2.0 - length * SQRT3_2 / 3.0;
let x1 = x0 + length / 2.0;
let y1 = y0 + length * SQRT3_2;
let x2 = x0 + length;
 
let mut data = Data::new().move_to((x0, y0));
data = koch_curve(data, x0, y0, x1, y1, order);
data = koch_curve(data, x1, y1, x2, y0, order);
data = koch_curve(data, x2, y0, x0, y0, order);
 
let path = Path::new()
.set("fill", "none")
.set("stroke", "white")
.set("stroke-width", "1")
.set("d", data);
 
let rect = Rectangle::new()
.set("width", "100%")
.set("height", "100%")
.set("fill", "black");
 
let document = svg::Document::new()
.set("width", size)
.set("height", size)
.add(rect)
.add(path);
 
svg::save(file, &document)
}
 
fn main() {
write_koch_snowflake("koch_snowflake.svg", 600, 5).unwrap();
}</syntaxhighlight>
 
{{out}}
[[Media:Koch_snowflake_rust.svg]]
 
=={{header|Sidef}}==
Using the LSystem class defined at [https://rosettacode.org/wiki/Hilbert_curve#Sidef Hilbert curve].
<langsyntaxhighlight lang="ruby">var rules = Hash(
F => 'F+F--F+F',
)
Line 1,692 ⟶ 3,230:
)
 
lsys.execute('F--F--F', 4, "koch_snowflake.png", rules)</langsyntaxhighlight>
 
Output image: [https://github.com/trizen/rc/blob/master/img/koch-snowflake-sidef.png Koch snowflake]
 
=={{header|VBScript}}==
VBScript does'nt have access to the OS graphics, so the code generates SVG code in an HTML file then opens it in the default browser
A Turtle graphics library makes defining the curve easy.
 
<syntaxhighlight lang="vb">
 
option explicit
'outputs turtle graphics to svg file and opens it
 
const pi180= 0.01745329251994329576923690768489 ' pi/180
const pi=3.1415926535897932384626433832795 'pi
class turtle
dim fso
dim fn
dim svg
dim iang 'radians
dim ori 'radians
dim incr
dim pdown
dim clr
dim x
dim y
 
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
if ori<0 then ori = ori+pi*2
end sub
public sub lt(i):
ori=(ori + i*iang)
if ori>(pi*2) then ori=ori-pi*2
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
 
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
 
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can't create svg file" :vscript.quit
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
 
sub koch (n,le)
if n=0 then x.fw le :exit sub
koch n-1, le/3
x.lt 1
koch n-1, le/3
x.rt 2
koch n-1, le/3
x.lt 1
koch n-1, le/3
end sub
 
dim x,i
set x=new turtle
x.iangle=60
x.orient=0
x.incr=3
x.x=100:x.y=300
for i=0 to 3
koch 7,100
x.rt 2
next
set x=nothing 'show image in browser
 
</syntaxhighlight>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|DOME}}
<syntaxhighlight lang="wren">import "graphics" for Canvas, Color, Point
import "dome" for Window
import "math" for M
 
class Game {
static init() {
Window.title = "Koch curve"
Canvas.resize(512, 512)
Window.resize(512, 512)
Canvas.cls(Color.white) // white background
koch(100, 100, 400, 400, 4)
koch(101, 100, 401, 400, 4) // 2 pixels wide
}
 
static koch(x1, y1, x2, y2, iter) {
var angle = Num.pi / 3 // 60 degrees
var x3 = (x1*2 + x2) / 3
var y3 = (y1*2 + y2) / 3
var x4 = (x1 + x2*2) / 3
var y4 = (y1 + y2*2) / 3
var x5 = x3 + (x4-x3)*M.cos(angle) + (y4-y3)*M.sin(angle)
var y5 = y3 - (x4-x3)*M.sin(angle) + (y4-y3)*M.cos(angle)
if (iter > 0) {
iter = iter - 1
koch(x1, y1, x3, y3, iter)
koch(x3, y3, x5, y5, iter)
koch(x5, y5, x4, y4, iter)
koch(x4, y4, x2, y2, iter)
} else {
Canvas.line(x1, y1, x3, y3, Color.blue)
Canvas.line(x3, y3, x5, y5, Color.blue)
Canvas.line(x5, y5, x4, y4, Color.blue)
Canvas.line(x4, y4, x2, y2, Color.blue)
}
}
 
static update() {}
 
static draw(dt) {}
}</syntaxhighlight>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">real PosX, PosY, Angle;
 
proc DrawSide(Depth, Dist); \Draw side as 4 segments
int Depth; real Dist;
int I; real Dir;
def Deg2Rad = 3.14159265358979323846/180.;
[Dir:= [0., -60., 120., -60.];
for I:= 0 to 3 do
[Angle:= Angle + Dir(I);
if Depth < 4 then DrawSide(Depth+1, Dist/3.)
else [PosX:= PosX + Dist*Cos(Angle*Deg2Rad);
PosY:= PosY + Dist*Sin(Angle*Deg2Rad);
Line(fix(PosX), fix(PosY), $F \BrWhite\);
];
];
];
 
int Side;
[SetVid($107); \set 1280x1024x8 VESA graphic display
PosX:= float(1280/2); PosY:= 0.;
Move(fix(PosX), fix(PosY)); \set start of Line
Angle:= 60.; \heading = 60 degrees
for Side:= 1 to 3 do \sides of triangle
[DrawSide(0, 290.);
Angle:= Angle + 120.;
];
]</syntaxhighlight>
 
{{out}}
<pre>
Essentially the same as the C++ image.
</pre>
 
=={{header|zkl}}==
Line 1,700 ⟶ 3,429:
Uses Image Magick and
the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<langsyntaxhighlight lang="zkl">var width=512, height=512, img=PPM(width,height,0xFfffFF); // white canvas
var angle=(60.0).toRad();
const green=0x00FF00;
Line 1,727 ⟶ 3,456:
 
koch(100.0,100.0, 400.0,400.0, 4);
img.writeJPGFile("koch.zkl.jpg");</langsyntaxhighlight>
Image at [http://www.zenkinetic.com/Images/RosettaCode/koch.zkl.jpg koch curve]
 
Line 1,733 ⟶ 3,462:
Using a Lindenmayer system and turtle graphics to draw a Koch snowflake:
 
<langsyntaxhighlight lang="zkl">lsystem("F--F--F", Dictionary("F","F+F--F+F"), "+-", 4) // snowflake
//lsystem("F", Dictionary("F","F+F--F+F"), "+-", 3) // curve
: turtle(_);
Line 1,763 ⟶ 3,492:
}
img.writeJPGFile("kochSnowFlake.zkl.jpg");
}</langsyntaxhighlight>
Image at [http://www.zenkinetic.com/Images/RosettaCode/kochSnowFlake.zkl.jpg Koch snow flake]
3,038

edits