Dragon curve: Difference between revisions
m
Algol 68 →L-System: comments
m (→{{header|Lambdatalk}}: Tags "lang" corrected) |
m (Algol 68 →L-System: comments) |
||
(44 intermediate revisions by 17 users not shown) | |||
Line 102:
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example [[#C by IFS Drawing|C by IFS Drawing]] code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems. <br><br>
=={{header|Ada}}==
This example uses GTKAda and Cairo.
<div>[[File:Dragoncurve ada cairo.png|thumb]]</div>
<syntaxhighlight lang="Ada">
-- FILE: dragon_curve.gpr --
with "gtkada";
project Dragon_Curve is
Adaflags := External_As_List ("ADAFLAGS", " ");
Ldflags := External_As_List ("LDFLAGS", " ");
for Languages use ("Ada");
for Main use ("dragon_curve.adb");
for Source_Dirs use ("./");
for Object_Dir use "obj/";
for Exec_Dir use ".";
package Compiler is
for Switches ("Ada") use ("-g", "-O0", "-gnaty-s", "-gnatwJ")
& Adaflags;
end Compiler;
package Linker is
for Leading_Switches ("Ada") use Ldflags;
end Linker;
end Dragon_Curve;
</syntaxhighlight>
<syntaxhighlight lang="Ada">
-- FILE: dragon_curve.adb --
with Ada.Text_IO; use Ada.Text_IO;
with Events; use Events;
with GLib.Main; use GLib.Main;
with GTK;
with GTK.Drawing_Area; use GTK.Drawing_Area;
with GTK.Main;
with GTK.Window; use GTK.Window;
procedure Dragon_Curve is
Window : GTK_Window;
begin
GTK.Main.Init;
GTK_New (Window);
GTK_New (Drawing_Area);
Window.Add (Drawing_Area);
Drawing_Area.On_Draw (Events.Draw'Access, Drawing_Area);
Show_All (Window);
Resize (Window, 800, 800);
GTK.Main.Main;
end Dragon_Curve;
</syntaxhighlight>
<syntaxhighlight lang="Ada">
-- FILE: events.ads --
with Ada.Numerics.Generic_Elementary_Functions;
with Cairo;
with GLib; use Glib;
with GTK.Drawing_Area; use GTK.Drawing_Area;
with GTK.Widget; use GTK.Widget;
with GLib.Object; use GLib.Object;
package Events is
Drawing_Area : GTK_Drawing_Area;
package GDouble_Elementary_Functions is new Ada.Numerics.Generic_Elementary_Functions (Float);
use GDouble_Elementary_Functions;
function Draw (Self : access GObject_Record'Class;
CC : Cairo.Cairo_Context)
return Boolean;
end Events;
</syntaxhighlight>
<syntaxhighlight lang="Ada">
-- FILE: events.adb --
with Cairo;
with GTK;
package body Events is
function Draw (Self : access GObject_Record'Class;
CC : Cairo.Cairo_Context)
return Boolean
is
type Rotate_Type is (Counterclockwise, Clockwise);
type Point is record
X, Y : GDouble;
end record;
procedure Heighway_Branch (CC : Cairo.Cairo_Context;
A, B : Point;
Rotate : Rotate_Type;
N : Natural)
is
R, RU, C : Point;
begin
if N = 0 then
Cairo.Move_To (CC, A.X, A.Y);
Cairo.Line_To (CC, B.X, B.Y);
Cairo.Stroke (CC);
else
-- Rotate 45 degrees --
case Rotate is
when Clockwise =>
R.X := GDouble ((1.0 / Sqrt (2.0)) * Float (B.X - A.X)
- (1.0 / Sqrt (2.0)) * Float (B.Y - A.Y));
R.Y := GDouble ((1.0 / Sqrt (2.0)) * Float (B.X - A.X)
+ (1.0 / Sqrt (2.0)) * Float (B.Y - A.Y));
when Counterclockwise =>
R.X := GDouble ((1.0 / Sqrt (2.0)) * Float (B.X - A.X)
+ (1.0 / Sqrt (2.0)) * Float (B.Y - A.Y));
R.Y := GDouble (-(1.0 / Sqrt (2.0)) * Float (B.X - A.X)
+ (1.0 / Sqrt (2.0)) * Float (B.Y - A.Y));
end case;
-- Make unit vector from rotation --
RU.X := GDouble (Float (R.X) / Sqrt ( Float (R.X ** 2 + R.Y ** 2)));
RU.Y := GDouble (Float (R.Y) / Sqrt ( Float (R.X ** 2 + R.Y ** 2)));
-- Scale --
R.X := RU.X * GDouble (Sqrt (Float (B.X - A.X) ** 2 + Float (B.Y - A.Y) ** 2) / Sqrt (2.0));
R.Y := RU.Y * GDouble (Sqrt (Float (B.X - A.X) ** 2 + Float (B.Y - A.Y) ** 2) / Sqrt (2.0));
C := (R.X + A.X, R.Y + A.Y);
Heighway_Branch (CC, A, C, Clockwise, N - 1);
Heighway_Branch (CC, C, B, Counterclockwise, N - 1);
end if;
end Heighway_Branch;
Depth : constant := 14;
Center, Right, Bottom, Left: Point;
Width : GDouble := GDouble (Drawing_Area.Get_Allocated_Width);
Height : GDouble := GDouble (Drawing_Area.Get_Allocated_Height);
begin
Center := (Width / 2.0, Height / 2.0);
Right := (Width, Height / 2.0);
Left := (0.0, Height / 2.0);
Bottom := (Width / 2.0, Height);
Cairo.Set_Source_RGB (CC, 0.0, 1.0, 0.0);
Heighway_Branch (CC, Center, Right, Clockwise, Depth);
Cairo.Set_Source_RGB (CC, 0.0, 1.0, 1.0);
Heighway_Branch (CC, Center, Left, Clockwise, Depth);
Cairo.Set_Source_RGB (CC, 0.0, 1.0, 0.5);
Heighway_Branch (CC, Center, Bottom, Clockwise, Depth);
return True;
end Draw;
end Events;
</syntaxhighlight>
=={{header|Action!}}==
Action! language does not support recursion. Therefore an iterative approach with a stack has been proposed.
<
INT ARRAY
Line 190 ⟶ 346:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Dragon_curve.png Screenshot from Atari 8-bit computer]
=={{header|ALGOL 68}}==
===Animated===
{{trans|python}}
<!-- {{works with|ALGOL 68|Standard - but ''draw'' is not part of the standard prelude}} -->
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - when I figure out how to link to the linux plot lib, then it might work}} -->
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.8 algol68g-2.8].}}
'''File: prelude/turtle_draw.a68'''<
STRUCT (REAL x, y, heading, BOOL pen down) turtle;
Line 226 ⟶ 385:
);
SKIP</
COMMENT
Line 275 ⟶ 434:
PROC raise unimplemented = (EXCEPTOBJS obj, STRING msg)VOID: IF NOT on unimplemented mend(obj, msg) THEN stop FI;
SKIP</
# -*- coding: utf-8 -*- #
Line 360 ⟶ 519:
VOID(system("sleep 1"))
OD;
close (window)</
Output:
Line 367 ⟶ 526:
|}
Note: each Dragon curve is composed of many smaller dragon curves (shown in a different colour).
===L-System===
Alternative (monochrome) version using the L-System library.
{{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. 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 # Dragon 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 dragon 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+S"
, "S" -> "F-S"
)
);
STRING curve = ssc EVAL order;
curve INTERPRET ( ( CHAR c )VOID:
IF c = "F" OR c = "S" 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 +:= 90 MODAB 360
ELIF c = "-" THEN
angle -:= 90 MODAB 360
FI
);
put( svg file, ( "'/>", newline, "</svg>", newline ) );
close( svg file )
FI # sierpinski square # ;
dragon curve( "dragon.svg", 1200, 5, 12, 400, 200 )
END
</syntaxhighlight>
=={{header|AmigaE}}==
Example code using mutual recursion can be found in [http://cshandley.co.uk/JasonHulance/beginner_170.html Recursion Example] of "A Beginner's Guide to Amiga E".
=={{header|Asymptote}}==
Line 388 ⟶ 613:
=={{header|BASIC}}==
{{works with|QBasic}}
<
SUB turn (degrees AS Double)
Line 416 ⟶ 641:
PSET (150,180), 0
dragon 400, 12, 1
SLEEP</
Line 426 ⟶ 651:
* https://archive.org/details/byte-magazine-1983-12
==={{header|
{{trans|QuickBASIC|Internal subprogram is used, so it has access to program (global) variables.}}
{{works with|Decimal BASIC}}
<syntaxhighlight lang="basic">
100 PROGRAM DragonCurve
110 DECLARE SUB Dragon
120 SET WINDOW 0, 639, 0, 399
130 SET AREA COLOR 1
140 SET COLOR MIX(1) 0, 0, 0
150 REM SIN, COS in arrays for PI/4 multipl.
160 DIM S(0 TO 7), C(0 TO 7)
170 LET QPI = PI / 4
210 NEXT I
220 REM ** Initialize variables non-local for SUB Dragon.
230 LET SQ = SQR(2)
240 LET X = 224
250 LET Y = 140
260 LET RotQPi = 0
270 CALL Dragon(256, 15, 1) ! Insize = 2^WHOLE_NUM (looks better)
280 REM ** Subprogram
290 SUB Dragon (Insize, Level, RQ)
300 IF Level <= 1 THEN
310 LET XN = C(RotQPi) * Insize + X
320 LET YN = S(RotQPi) * Insize + Y
330 PLOT LINES: X, 399 - Y; XN, 399 - YN
340 LET X = XN
350 LET Y = YN
360 ELSE
370 LET RotQPi = MOD((RotQPi + RQ), 8)
380 CALL Dragon(Insize / SQ, Level - 1, 1)
390 LET RotQPi = MOD((RotQPi - RQ * 2), 8)
400 CALL Dragon(Insize / SQ, Level - 1, -1)
410 LET RotQPi = MOD((RotQPi + RQ), 8)
420 END IF
430 END SUB
440 END
</syntaxhighlight>
==={{header|Applesoft BASIC}}===
Apple IIe BASIC code can be found in Thomas Bannon, "Fractals and Transformations", Mathematics Teacher, March 1991, pages 178-185. ([http://www.jstor.org/stable/27967087 At JSTOR].)
==={{header|BASIC256}}===
[[File:Dragon curve BASIC-256.png|220px|thumb|right|Image created by the BASIC-256 script]]
<
graphsize 390,270
Line 497 ⟶ 746:
level = level + 1
insize = insize*SQ
return</
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
MOVE 800,400
GCOL 11
Line 518 ⟶ 767:
angle += d*PI/4
ENDIF
ENDPROC</
==={{header|
{{trans|Commodore BASIC}}
<syntaxhighlight lang="basic">
10 rem Dragon curve
20 rem sin, cos in arrays for pi/4 multipl.
30 dim s(7),c(7)
40 for i = 0 to 7
50 s(i) = sin(i*pi/4) : c(i) = cos(i*pi/4)
60 next i
70 level = 15
80 insize = 256 : rem 2^whole_num (looks better)
90 x = 224 : y = 140
100 sq = sqr(2)
110 rotqpi = 0 : rq = 1
120 dim r(level)
130 graphics 0 : graphics cls
140 gosub 160
150 end
160 rem Dragon
170 rotqpi = rotqpi and 7
180 if level <= 1 then
190 yn = s(rotqpi)*insize+y
200 xn = c(rotqpi)*insize+x
210 graphics moveto x,y : graphics lineto xn,yn
220 x = xn : y = yn
230 else
240 insize = insize*sq/2
250 rotqpi = (rotqpi+rq) and 7
260 level = level-1
270 r(level) = rq : rq = 1
280 gosub 160
290 rotqpi = (rotqpi-r(level)*2) and 7
300 rq = -1
310 gosub 160
320 rq = r(level)
330 rotqpi = (rotqpi+rq) and 7
340 level = level+1
350 insize = insize*sq
360 endif
370 return
</syntaxhighlight>
==={{header|Commodore BASIC}}===
{{trans|BASIC256}}
The values of <code>SIN</code> and <code>COS</code> for multiplies of <code>PI / 4</code> are remembered in arrays, so that the program may run (a little) faster.
{{works with|Commodore BASIC|3.5}}
<syntaxhighlight lang="basic">
10 REM DRAGON CURVE
20 REM SIN, COS IN ARRAYS FOR PI/4 MULTIPL.
30 DIM S(7),C(7)
40 QPI=ATN(1):SQ=SQR(2)
50 FOR I=0 TO 7
60 S(I)=SIN(I*QPI):C(I)=COS(I*QPI)
70 NEXT I
80 LEVEL=15
90 INSIZE=128:REM 2^WHOLE_NUM (LOOKS BETTER)
100 X=112:Y=70
110 ROTQPI=0:RQ=1
120 DIM R(LEVEL)
130 GRAPHIC 2,1
140 GOSUB 160
150 END
160 REM DRAGON
170 ROTQPI=ROTQPI AND 7
180 IF LEVEL>1 THEN GO TO 240
190 YN=S(ROTQPI)*INSIZE+Y
200 XN=C(ROTQPI)*INSIZE+X
210 DRAW ,X,Y TO XN,YN
220 X=XN:Y=YN
230 RETURN
240 INSIZE=INSIZE*SQ/2
250 ROTQPI=(ROTQPI+RQ)AND 7
260 LEVEL=LEVEL-1
270 R(LEVEL)=RQ:RQ=1
280 GOSUB 160
290 ROTQPI=(ROTQPI-R(LEVEL)*2)AND 7
300 RQ=-1
310 GOSUB 160
320 RQ=R(LEVEL)
330 ROTQPI=(ROTQPI+RQ)AND 7
340 LEVEL=LEVEL+1
350 INSIZE=INSIZE*SQ
360 RETURN
</syntaxhighlight>
==={{header|FreeBASIC}}===
{{trans|BASIC}}
<syntaxhighlight lang="freebasic">Const pi As Double = 4 * Atn(1)
Dim Shared As Double angulo = 0
Sub giro (grados As Double)
angulo += grados*pi/180
End Sub
Sub dragon (longitud As Double, division As Integer, d As Double)
If division = 0 Then
Line - Step (Cos(angulo)*longitud, Sin(angulo)*longitud), Int(Rnd * 7)
Else
giro d*45
dragon longitud/1.4142136, division-1, 1
giro -d*90
dragon longitud/1.4142136, division-1, -1
giro d*45
End If
End Sub
'--- Programa Principal ---
Screen 12
Pset (150,180), 0
dragon 400, 12, 1
Bsave "Dragon_curve_FreeBASIC.bmp",0
Sleep</syntaxhighlight>
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
{{works with|QBasic}}
{{trans|Commodore BASIC}}
<syntaxhighlight lang="qbasic">10 REM Dragon curve
20 REM SIN, COS in arrays for PI/4 multipl.
30 DIM S(7), C(7)
40 QPI = ATN(1): SQ = SQR(2)
50 FOR I = 0 TO 7
60 S(I) = SIN(I * QPI): C(I) = COS(I * QPI)
70 NEXT I
80 LEVEL% = 15
90 INSIZE = 128: REM 2^WHOLE_NUM (looks better)
100 X = 112: Y = 70
110 ROTQPI% = 0: RQ% = 1
120 DIM R%(LEVEL%)
130 SCREEN 2: CLS
140 GOSUB 160
150 END
160 REM ** Dragon
170 ROTQPI% = ROTQPI% AND 7
180 IF LEVEL% > 1 THEN GOTO 240
190 YN = S(ROTQPI%) * INSIZE + Y
200 XN = C(ROTQPI%) * INSIZE + X
210 LINE (2 * X, Y)-(2 * XN, YN): REM For SCREEN 2 doubled x-coords
220 X = XN: Y = YN
230 RETURN
240 INSIZE = INSIZE * SQ / 2
250 ROTQPI% = (ROTQPI% + RQ%) AND 7
260 LEVEL% = LEVEL% - 1
270 R%(LEVEL%) = RQ%: RQ% = 1
280 GOSUB 160
290 ROTQPI% = (ROTQPI% - R%(LEVEL%) * 2) AND 7
300 RQ% = -1
310 GOSUB 160
320 RQ% = R%(LEVEL%)
330 ROTQPI% = (ROTQPI% + RQ%) AND 7
340 LEVEL% = LEVEL% + 1
350 INSIZE = INSIZE * SQ
360 RETURN</syntaxhighlight>
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Dragon.bas"
110 OPTION ANGLE DEGREES
120 LET SQ2=SQR(2)
130 GRAPHICS HIRES 2
140 SET PALETTE 0,33
150 PLOT 250,360,ANGLE 0;
160 CALL DC(580,0,11)
170 DEF DC(D,A,LEV)
180 IF LEV=0 THEN
190 PLOT FORWARD D;
200 ELSE
210 PLOT RIGHT A;
220 CALL DC(D/SQ2,45,LEV-1)
230 PLOT LEFT 2*A;
240 CALL DC(D/SQ2,-45,LEV-1)
250 PLOT RIGHT A;
260 END IF
270 END DEF</syntaxhighlight>
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">nomainwin
mainwin 50 20
WindowHeight =620
WindowWidth =690
open "Graphics library" for graphics as #a
#a, "trapclose [quit]"
#a "down"
Turn$ ="R"
Pace =100
s = 16
[again]
print Turn$
#a "cls ; home ; north ; down ; fill black"
for i =1 to len( Turn$)
v =255 *i /len( Turn$)
#a "color "; v; " 120 "; 255 -v
#a "go "; Pace
if mid$( Turn$, i, 1) ="R" then #a "turn 90" else #a "turn -90"
next i
#a "color 255 120 0"
#a "go "; Pace
#a "flush"
FlippedTurn$ =""
for i =len( Turn$) to 1 step -1
if mid$( Turn$, i, 1) ="R" then FlippedTurn$ =FlippedTurn$ +"L" else FlippedTurn$ =FlippedTurn$ +"R"
next i
Turn$ =Turn$ +"R" +FlippedTurn$
Pace =Pace /1.35
scan
timer 1000, [j]
wait
[j]
timer 0
if len( Turn$) <40000 then goto [again]
wait
[quit]
close #a
end</syntaxhighlight>
==={{header|MSX Basic}}===
{{trans|Commodore BASIC}}
<syntaxhighlight lang="basic">
10 REM Dragon curve
20 REM SIN, COS in arrays for PI/4 multipl.
30 DIM S(7),C(7)
40 QPI=ATN(1):SQ=SQR(2)
50 FOR I=0 TO 7
60 S(I)=SIN(I*QPI):C(I)=COS(I*QPI)
70 NEXT I
80 LEVEL=15
90 INSIZE=128:REM 2^WHOLE_NUM (looks better)
100 X=80:Y=70
110 ROTQPI=0:RQ=1
120 DIM R(LEVEL)
130 SCREEN 2
140 GOSUB 200
150 OPEN "GRP:" FOR OUTPUT AS #1
160 DRAW "BM 0,184":PRINT #1,"Hit any key to exit."
170 IF INKEY$="" THEN 170
180 CLOSE #1
190 END
200 REM Dragon
210 ROTQPI=ROTQPI AND 7
220 IF LEVEL>1 THEN GOTO 280
230 YN=S(ROTQPI)*INSIZE+Y
240 XN=C(ROTQPI)*INSIZE+X
250 LINE (X,Y)-(XN,YN)
260 X=XN:Y=YN
270 RETURN
280 INSIZE=INSIZE*SQ/2
290 ROTQPI=(ROTQPI+RQ)AND 7
300 LEVEL=LEVEL-1
310 R(LEVEL)=RQ:RQ=1
320 GOSUB 200
330 ROTQPI=(ROTQPI-R(LEVEL)*2)AND 7
340 RQ=-1
350 GOSUB 200
360 RQ=R(LEVEL)
370 ROTQPI=(ROTQPI+RQ)AND 7
380 LEVEL=LEVEL+1
390 INSIZE=INSIZE*SQ
400 RETURN
</syntaxhighlight>
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">#SqRt2 = 1.4142136
#SizeH = 800: #SizeV = 550
Global angle.d, px, py, imageNum
Procedure turn(degrees.d)
angle + degrees * #PI / 180
EndProcedure
Procedure forward(length.d)
Protected w = Cos(angle) * length
Protected h = Sin(angle) * length
LineXY(px, py, px + w, py + h, RGB(255,255,255))
px + w: py + h
EndProcedure
Procedure dragon(length.d, split, d.d)
If split = 0
forward(length)
Else
turn(d * 45)
dragon(length / #SqRt2, split - 1, 1)
turn(-d * 90)
dragon(length / #SqRt2, split - 1, -1)
turn(d * 45)
EndIf
EndProcedure
OpenWindow(0, 0, 0, #SizeH, #SizeV, "DragonCurve", #PB_Window_SystemMenu)
imageNum = CreateImage(#PB_Any, #SizeH, #SizeV, 32)
ImageGadget(0, 0, 0, 0, 0, ImageID(imageNum))
angle = 0: px = 185: py = 190
If StartDrawing(ImageOutput(imageNum))
dragon(400, 15, 1)
StopDrawing()
SetGadgetState(0, ImageID(imageNum))
EndIf
Repeat: Until WaitWindowEvent(10) = #PB_Event_CloseWindow</syntaxhighlight>
==={{header|QuickBASIC}}===
{{trans|GW-BASIC|Introduced some parameters in the recursive subroutine (especially for a level and instead of the array simulating a stack).}}
<syntaxhighlight lang="basic">
REM Dragon curve
REM SIN, COS in arrays for PI/4 multipl.
DECLARE SUB Dragon (BYVAL Insize!, BYVAL Level%, BYVAL RQ%)
DIM SHARED S(7), C(7), X, Y, RotQPi%
CONST QPI = .785398163397448# ' PI / 4
FOR I = 0 TO 7
S(I) = SIN(I * QPI)
C(I) = COS(I * QPI)
NEXT I
X = 112: Y = 70
SCREEN 2: CLS
CALL Dragon(128, 15, 1) ' Insize = 2^WHOLE_NUM (looks better)
END
SUB Dragon (BYVAL Insize, BYVAL Level%, BYVAL RQ%)
CONST SQ = 1.4142135623731# ' SQR(2)
IF Level% <= 1 THEN
XN = C(RotQPi%) * Insize + X
YN = S(RotQPi%) * Insize + Y
LINE (2 * X, Y)-(2 * XN, YN) ' For SCREEN 2 doubled x-coords
X = XN: Y = YN
ELSE
RotQPi% = (RotQPi% + RQ%) AND 7
CALL Dragon(Insize / SQ, Level% - 1, 1)
RotQPi% = (RotQPi% - RQ% * 2) AND 7
CALL Dragon(Insize / SQ, Level% - 1, -1)
RotQPi% = (RotQPi% + RQ%) AND 7
END IF
END SUB
</syntaxhighlight>
==={{header|RapidQ}}===
{{trans|BASIC}}
This implementation displays the Dragon Curve fractal in a [[GUI]] window.
<syntaxhighlight lang="rapidq">DIM angle AS Double
DIM x AS Double, y AS Double
DECLARE SUB PaintCanvas
CREATE form AS QForm
Width = 800
Height = 600
CREATE canvas AS QCanvas
Height = form.ClientHeight
Width = form.ClientWidth
OnPaint = PaintCanvas
END CREATE
END CREATE
SUB turn (degrees AS Double)
angle = angle + degrees*3.14159265/180
END SUB
SUB forward (length AS Double)
x2 = x + cos(angle)*length
y2 = y + sin(angle)*length
canvas.Line(x, y, x2, y2, &Haaffff)
x = x2: y = y2
END SUB
SUB dragon (length AS Double, split AS Integer, d AS Double)
IF split=0 THEN
forward length
ELSE
turn d*45
dragon length/1.4142136, split-1, 1
turn -d*90
dragon length/1.4142136, split-1, -1
turn d*45
END IF
END SUB
SUB PaintCanvas
canvas.FillRect(0, 0, canvas.Width, canvas.Height, &H102800)
x = 220: y = 220: angle = 0
dragon 384, 12, 1
END SUB
form.ShowModal</syntaxhighlight>
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">graphic #g, 600,600
RL$ = "R"
loc = 90
pass = 0
[loop]
#g "cls ; home ; north ; down ; fill black"
for i =1 to len(RL$)
v = 255 * i /len(RL$)
#g "color "; v; " 120 "; 255 -v
#g "go "; loc
if mid$(RL$,i,1) ="R" then #g "turn 90" else #g "turn -90"
next i
#g "color 255 120 0"
#g "go "; loc
LR$ =""
for i =len( RL$) to 1 step -1
if mid$( RL$, i, 1) ="R" then LR$ =LR$ +"L" else LR$ =LR$ +"R"
next i
RL$ = RL$ + "R" + LR$
loc = loc / 1.35
pass = pass + 1
render #g
input xxx
cls
if pass < 16 then goto [loop]
end</syntaxhighlight>
<div>[[File:DragonCurveRunBasic.png]]</div>
==={{header|TI-89 BASIC}}===
{{trans|SVG}}
<syntaxhighlight lang="ti89b">Define dragon = (iter, xform)
Prgm
Local a,b
If iter > 0 Then
dragon(iter-1, xform*[[.5,.5,0][–.5,.5,0][0,0,1]])
dragon(iter-1, xform*[[–.5,.5,0][–.5,–.5,1][0,0,1]])
Else
xform*[0;0;1]→a
xform*[0;1;1]→b
PxlLine floor(a[1,1]), floor(a[2,1]), floor(b[1,1]), floor(b[2,1])
EndIf
EndPrgm
FnOff
PlotsOff
ClrDraw
dragon(7, [[75,0,26] [0,75,47] [0,0,1]])</syntaxhighlight>
Valid coordinates on the TI-89's graph screen are x 0..76 and y 0..158. This and [[wp:File:Dimensions_fractale_dragon.gif|the outer size of the dragon curve]] were used to choose the position and scale determined by the [[wp:Transformation_matrix#Affine_transformations|transformation matrix]] initially passed to <code>dragon</code> such that the curve will fit onscreen no matter the number of recursions chosen. The height of the curve is 1 unit, so the vertical (and horizontal, to preserve proportions) scale is the height of the screen (rather, one less, to avoid rounding/FP error overrunning), or 75. The curve extends 1/3 unit above its origin, so the vertical translation is (one more than) 1/3 of the scale, or 26. The curve extends 1/3 to the left of its origin, or 25 pixels; the width of the curve is 1.5 units, or 1.5·76 = 114 pixels, and the screen is 159 pixels, so to center it we place the origin at 25 + (159-114)/2 = 47 pixels.
==={{header|uBasic/4tH}}===
{{Trans|BBC BASIC}}
uBasic/4tH has neither native support for graphics nor floating point, so everything has to be defined in high level code. All calculations are done in integer arithmetic, scaled by 10K.
<syntaxhighlight lang="ubasic-4th">
Dim @o(5) ' 0 = SVG file, 1 = color, 2 = fillcolor, 3 = pixel, 4 = text
' === Begin Program ===
Proc _SetColor (FUNC(_Color ("Red"))) ' set the line color to red
Proc _SVGopen ("dragon.svg") ' open the SVG file
Proc _Canvas (525, 625) ' set the canvas size
Proc _Background (FUNC(_Color ("White")))
' we have a white background
a = 475 : b = 175 : t = 14142 : r = 0 : p = 7853
' x,y coordinates, SQRT(2), angle, PI/4
Proc _Dragon (512, 12, 1) ' size, split and direction
Proc _SVGclose ' close SVG file
End
_Dragon
Param (3)
If b@ Then ' if split > 0 then recurse
r = r + (c@ * p)
Proc _Dragon ((a@*10000)/t, b@ - 1, 1)
r = r - (c@ * (p+p))
Proc _Dragon ((a@*10000)/t, b@ - 1, -1)
r = r + (c@ * p)
Return
EndIf
' draw a line
Proc _Line (a, b, Set (a, a + (((-FUNC(_COS(r)))*a@)/10000)), Set (b, b + ((FUNC(_SIN(r))*a@)/10000)))
Return
' === End Program ===
_SetColor Param (1) : @o(1) = a@ : Return
_SVGclose Write @o(0), "</svg>" : Close @o(0) : Return
_color_ Param (1) : Proc _PrintRGB (a@) : Write @o(0), "\q />" : Return
_PrintRGB ' print an RBG color in hex
Param (1)
Radix 16
If a@ < 0 Then
Write @o(0), "none";
Else
Write @o(0), Show(Str ("#!######", a@));
EndIf
Radix 10
Return
_Background ' set the background color
Param (1)
Write @o(0), "<rect width=\q100%\q height=\q100%\q fill=\q";
Proc _color_ (a@)
Return
_Color ' retrieve color code from its name
Param (1)
Local (1)
Radix 16
if Comp(a@, "black") = 0 Then
b@ = 000000
else if Comp(a@, "blue") = 0 Then
b@ = 0000ff
else if Comp(a@, "green") = 0 Then
b@ = 00ff00
else if Comp(a@, "cyan") = 0 Then
b@ = 00ffff
else if Comp(a@, "red") = 0 Then
b@ = 0ff0000
else if Comp(a@, "magenta") = 0 Then
b@ = 0ff00ff
else if Comp(a@, "yellow") = 0 Then
b@ = 0ffff00
else if Comp(a@, "white") = 0 Then
b@ = 0ffffff
else if Comp(a@, "none") = 0 Then
b@ = Info ("nil")
else Print "Invalid color" : Raise 1
fi : fi : fi : fi : fi : fi : fi : fi : fi
Radix 10
Return (b@)
_Line ' draw an SVG line from x1,y1 to x2,y2
Param (4)
Write @o(0), "<line x1=\q";d@;"\q y1=\q";c@;
Write @o(0), "\q x2=\q";b@;"\q y2=\q";a@;"\q stroke=\q";
Proc _color_ (@o(1))
Return
_Canvas ' set up a canvas x wide and y high
Param (2)
Write @o(0), "<svg width=\q";a@;"\q height=\q";b@;"\q viewBox=\q0 0 ";a@;" ";b@;
Write @o(0), "\q xmlns=\qhttp://www.w3.org/2000/svg\q ";
Write @o(0), "xmlns:xlink=\qhttp://www.w3.org/1999/xlink\q>"
Return
_SVGopen ' open an SVG file by name
Param (1)
If Set (@o(0), Open (a@, "w")) < 0 Then
Print "Cannot open \q";Show (a@);"\q" : Raise 1
Else
Write @o(0), "<?xml version=\q1.0\q encoding=\qUTF-8\q standalone=\qno\q?>"
Write @o(0), "<!DOCTYPE svg PUBLIC \q-//W3C//DTD SVG 1.1//EN\q ";
Write @o(0), "\qhttp://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\q>"
EndIf
Return
' return SIN(x*10K), scaled by 10K
_SIN PARAM(1) : PUSH A@ : LET A@=TOS()<0 : PUSH ABS(POP()%62832)
IF TOS()>31416 THEN A@=A@=0 : PUSH POP()-31416
IF TOS()>15708 THEN PUSH 31416-POP()
PUSH (TOS()*TOS())/10000 : PUSH 10000+((10000*-(TOS()/72))/10000)
PUSH 10000+((POP()*-(TOS()/42))/10000) : PUSH 10000+((POP()*-(TOS()/20))/10000)
PUSH 10000+((POP()*-(POP()/6))/10000) : PUSH (POP()*POP())/10000
IF A@ THEN PUSH -POP()
RETURN
' return COS(x*10K), scaled by 10K
_COS PARAM(1) : PUSH ABS(A@%62832) : IF TOS()>31416 THEN PUSH 62832-POP()
LET A@=TOS()>15708 : IF A@ THEN PUSH 31416-POP()
PUSH TOS() : PUSH (POP()*POP())/10000 : PUSH 10000+((10000*-(TOS()/56))/10000)
PUSH 10000+((POP()*-(TOS()/30))/10000): PUSH 10000+((POP()*-(TOS()/12))/10000)
PUSH 10000+((POP()*-(POP()/2))/10000) : IF A@ THEN PUSH -POP()
RETURN
</syntaxhighlight>
==={{header|VBScript}}===
VBScript does'nt have direct access to OS graphics, so I write SVG commands to an HTML file then I display it with the default browser.
A turtle graphics class makes the definition of the curve very simple.
<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
' ori=ori+pi '?????
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
x=400:y=400:incr=100
ori=90*pi180
iang=90*pi180
clr=0
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 dragon(st,le,dir)
if st=0 then x.fw le: exit sub
x.rt dir
dragon st-1, le/1.41421 ,1
x.rt dir*2
dragon st-1, le/1.41421 ,-1
x.rt dir
end sub
dim x
set x=new turtle
x.iangle=45
x.orient=45
x.incr=1
x.x=200:x.y=200
dragon 12,300,1
set x=nothing 'this displays the image
</syntaxhighlight>
==={{header|Visual Basic}}===
{{works with|Visual Basic|VB6 Standard}}
<syntaxhighlight lang="vb">Option Explicit
Const Pi As Double = 3.14159265358979
Dim angle As Double
Dim nDepth As Integer
Dim nColor As Long
Private Sub Form_Load()
nColor = vbBlack
nDepth = 12
DragonCurve
End Sub
Sub DragonProc(size As Double, ByVal split As Integer, d As Integer)
If split = 0 Then
xForm.Line -Step(-Cos(angle) * size, Sin(angle) * size), nColor
Else
angle = angle + d * Pi / 4
Call DragonProc(size / Sqr(2), split - 1, 1)
angle = angle - d * Pi / 2
Call DragonProc(size / Sqr(2), split - 1, -1)
angle = angle + d * Pi / 4
End If
End Sub
Sub DragonCurve()
Const xcoefi = 0.74
Const xcoefl = 0.59
xForm.PSet (xForm.Width * xcoefi, xForm.Height / 3), nColor
Call DragonProc(xForm.Width * xcoefl, nDepth, 1)
End Sub</syntaxhighlight>
==={{header|Visual Basic .NET}}===
{{works with|Visual Basic .NET|2013}}
<syntaxhighlight lang="vbnet">Option Explicit On
Imports System.Math
Public Class DragonCurve
Dim nDepth As Integer = 12
Dim angle As Double
Dim MouseX, MouseY As Integer
Dim CurrentX, CurrentY As Integer
Dim nColor As Color = Color.Black
Private Sub DragonCurve_Click(sender As Object, e As EventArgs) Handles Me.Click
SubDragonCurve()
End Sub
Sub DrawClear()
Me.CreateGraphics.Clear(Color.White)
End Sub
Sub DrawMove(ByVal X As Double, ByVal Y As Double)
CurrentX = X
CurrentY = Y
End Sub
Sub DrawLine(ByVal X As Double, ByVal Y As Double)
Dim MyGraph As Graphics = Me.CreateGraphics
Dim PenColor As Pen = New Pen(nColor)
Dim NextX, NextY As Long
NextX = CurrentX + X
NextY = CurrentY + Y
MyGraph.DrawLine(PenColor, CurrentX, CurrentY, NextX, NextY)
CurrentX = NextX
CurrentY = NextY
End Sub
Sub DragonProc(size As Double, ByVal split As Integer, d As Integer)
If split = 0 Then
DrawLine(-Cos(angle) * size, Sin(angle) * size)
Else
angle = angle + d * PI / 4
DragonProc(size / Sqrt(2), split - 1, 1)
angle = angle - d * PI / 2
DragonProc(size / Sqrt(2), split - 1, -1)
angle = angle + d * PI / 4
End If
End Sub
Sub SubDragonCurve()
Const xcoefi = 0.74, xcoefl = 0.59
DrawClear()
DrawMove(Me.Width * xcoefi, Me.Height / 3)
DragonProc(Me.Width * xcoefl, nDepth, 1)
End Sub
End Class</syntaxhighlight>
==={{header|Yabasic}}===
{{trans|BASIC256}}
<syntaxhighlight lang="yabasic">w = 390 : h = int(w * 11 / 16)
open window w, h
level = 18 : insize = 247
x = 92 : y = 94
iters = 2^level
qiter = 510/iters
SQ = sqrt(2) : QPI = pi/4
rotation = 0 : iter = 0 : rq = 1.0
dim rqs(level)
color 0,0,0
clear window
dragon()
sub dragon()
if level<=0 then
yn = sin(rotation)*insize + y
xn = cos(rotation)*insize + x
if iter*2<iters then
color 0,iter*qiter,255-iter*qiter
else
color qiter*iter-255,(iters-iter)*qiter,0
end if
line x,y,xn,yn
iter = iter + 1
x = xn : y = yn
return
end if
insize = insize/SQ
rotation = rotation + rq*QPI
level = level - 1
rqs(level) = rq : rq = 1
dragon()
rotation = rotation - rqs(level)*QPI*2
rq = -1
dragon()
rq = rqs(level)
rotation = rotation + rq*QPI
level = level + 1
insize = insize*SQ
return
end sub</syntaxhighlight>
Other solution
<syntaxhighlight lang="yabasic">clear screen
width = 512 : height = 512 : crad = 0.01745329
open window width, height
window origin "cc"
x = 75 : y = 120 : level = 18 : iters = 2**level : qiter = 510/iters
sub dragon(size, lev, d)
if lev then
dragon(size / sqrt(2), lev - 1, 1)
angle = angle - d * 90
dragon(size / sqrt(2), lev - 1, -1)
else
x = x - cos(angle * crad) * size
y = y + sin(angle * crad) * size
if iter*2<iters then
color 0,iter*qiter,255-iter*qiter
else
color qiter*iter-255,(iters-iter)*qiter,0
endif
line to x, y
iter = iter + 1
endif
end sub
dot x, y
dragon(300, level, 1)</syntaxhighlight>
==={{header|ZX Spectrum Basic}}===
{{trans|BASIC256}}
<syntaxhighlight lang="zxbasic">10 LET level=15: LET insize=120
20 LET x=80: LET y=70
30 LET sq=SQR (2): LET qpi=PI/4
40 LET rotation=0: LET rq=1
50 DIM r(level)
60 GO SUB 70: STOP
70 REM Dragon
80 IF level>1 THEN GO TO 140
90 LET yn=SIN (rotation)*insize+y
100 LET xn=COS (rotation)*insize+x
110 PLOT x,y: DRAW xn-x,yn-y
120 LET x=xn: LET y=yn
130 RETURN
140 LET insize=insize/sq
150 LET rotation=rotation+rq*qpi
160 LET level=level-1
170 LET r(level)=rq: LET rq=1
180 GO SUB 70
190 LET rotation=rotation-r(level)*qpi*2
200 LET rq=-1
210 GO SUB 70
220 LET rq=r(level)
230 LET rotation=rotation+rq*qpi
240 LET level=level+1
250 LET insize=insize*sq
260 RETURN </syntaxhighlight>
=={{header|Befunge}}==
This is loosely based on the [[Dragon_curve#M4|M4]] predicate algorithm, only it produces a more compact ASCII output (which is also a little easier to implement), and it lets you choose the depth of the expansion rather than having to specify the coordinates of the viewing area.
In Befunge-93 the 8-bit cell size restricts you to a maximum depth of 15, but in Befunge-98 you should be able go quite a bit deeper before other limits of the implementation come into play.
<
| v%2\/3-1$_\#!4#:*#-\#1<\1+1:/4+1g00:\_\#$1<%2/2+1\g02\-1+%-g012\/-*<v"*/
_ >!>0$#0\#$\_-10p20p::00g4/:1+1>\#<1#*-#4:#\_$1-2*3/\2%!>0$#0\#$\_--vv|+2
Line 532 ⟶ 1,678:
>:1+*!60g*!#v_!\!*50g0`*!40gg,::30g40g:2-#^_>>$>>:^:+1g02::\,+55_55+,@v":*
v%2/2+*">~":< ^\-1g05-*">~"/2+*"|~"-%*"|~"\/*"|~":\-*">~"/2+%*"|~"\/*<^<:
>60p\:"~>"*+2/2%60g+2%70p:"kI"*+2/2%60p\:"kI"*+2/2%60g+2%-\70g-"~|"**+"}"^</
{{out}}
Line 566 ⟶ 1,712:
The drawing may be skewed for some iterations since it is drawn to fit the bounding box.
<
Turns ← {{𝕩∾1∾¬⌾((⌊2÷˜≠)⊸⊑)𝕩}⍟𝕩 ⥊1}
•Plot´ <˘⍉>+` (<0‿1)(Rot˜)`Turns 3</
[https://mlochbaum.github.io/BQN/try.html#code=Um90IOKGkCDCrOKKuHst4oy+KPCdlajiirjiipEp4oy98J2VqX0KVHVybnMg4oaQIHt78J2VqeKIvjHiiL7CrOKMvigo4oyKMsO3y5ziiaAp4oq44oqRKfCdlal94o2f8J2VqSDipYoxfQoK4oCiUGxvdMK0IDzLmOKNiT4rYCAoPDDigL8xKShSb3TLnClgVHVybnMgNAoK Try It!]
Line 577 ⟶ 1,723:
[[file:dragon-C.png|thumb|center]]
C code that writes PNM of dragon curve. run as <code>a.out [depth] > dragon.pnm</code>. Sample image was with depth 9 (512 pixel length).
<
#include <stdlib.h>
#include <string.h>
Line 705 ⟶ 1,851:
return 0;
}</
=={{header|C sharp|C#}}==
{{trans|Java}}
<
using System.Collections.Generic;
using System.Drawing;
Line 777 ⟶ 1,923:
Application.Run(new DragonCurve(14));
}
}</
=={{header|C++}}==
Line 783 ⟶ 1,929:
This program will generate the curve and save it to your hard drive.
<
#include <windows.h>
#include <iostream>
Line 979 ⟶ 2,125:
}
//-----------------------------------------------------------------------------------------
</syntaxhighlight>
=={{header|Clojure}}==
Calculates the absolute location of each step iteratively by bit-twiddling and then prints terminal output with unicode box-drawing characters:
<syntaxhighlight lang="clojure">(defn i->dir
[n]
(mod (Long/bitCount (bit-xor n (bit-shift-right n 1))) 4))
(defn safe-bit-or [v bit] (bit-or (or v 0) bit))
(let [steps 511
{[minx maxx miny maxy] :bbox data :data}
(loop [i 0
[x y] [0 0]
out {}
[minx maxx miny maxy] [0 0 0 0]]
(let [dir (i->dir i)
[nx ny] [(+ x (condp = dir 0 1 2 -1 0))
(+ y (condp = dir 1 1 3 -1 0))]
[ob ib] (nth [[8 4][2 1][4 8][1 2]] dir)
out (-> (update-in out [y x] safe-bit-or ob)
(update-in [ny nx] safe-bit-or ib))
bbox [(min minx nx) (max maxx nx)
(min miny ny) (max maxy ny)]]
(if (< i steps)
(recur (inc i) [nx ny] out bbox)
{:data out :bbox bbox})))]
(doseq [y (range miny (inc maxy))]
(->> (for [x (range minx (inc maxx))]
(nth " ╵╷│╴┘┐┤╶└┌├─┴┬┼" (get-in data [y x] 0)))
(apply str)
(println))))
</syntaxhighlight>
Output:
[[File:Clj-dragon-terminal-screenshot.png|alt=terminal output of Clojure dragon curve program]]
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
<
*> This code is dedicated to the public domain
identification division.
Line 1,155 ⟶ 2,337:
stop run
.
end program dragon.</
{{out}}
Line 1,187 ⟶ 2,369:
The recursive <tt>dragon-part</tt> function draws a curve connecting (0,0) to (1,0); if <var>depth</var> is 0 then the curve is a straight line. <var>bend-direction</var> is either 1 or -1 to specify whether the deviation from a straight line should be to the right or left.
<
(:use #:clim-lisp #:clim)
(:export #:dragon #:dragon-part))
Line 1,205 ⟶ 2,387:
(with-room-for-graphics ()
(with-scaling (t size)
(dragon-part depth 1))))</
=={{header|D}}==
Line 1,216 ⟶ 2,398:
*rules : (X → X+YF+),(Y → -FX-Y)
*angle : 90°
<
struct Board {
Line 1,321 ⟶ 2,503:
dragonX(7, t, b); // <- X
writeln(b);
}</
{{out}}
<pre> - - - -
Line 1,357 ⟶ 2,539:
===PostScript Output Version===
{{trans|Haskell}}
<
string drx(in size_t n) pure nothrow {
Line 1,375 ⟶ 2,557:
void main() {
writeln(dragonCurvePS(9)); // Increase this for a bigger curve.
}</
===On a Bitmap===
Line 1,382 ⟶ 2,564:
First a small "turtle.d" module, useful for other tasks:
<
import bitmap_bresenhams_line_algorithm, grayscale_image, std.math;
Line 1,403 ⟶ 2,585:
y += dy;
}
}</
Then the implementation is simple:
{{trans|PicoLisp}}
<
void drawDragon(Color)(Image!Color img, ref Turtle t, in uint depth,
Line 1,425 ⟶ 2,607:
img.drawDragon(t, 14, 45.0, 3);
img.savePGM("dragon_curve.pgm");
}</
===With QD===
Line 1,438 ⟶ 2,620:
{{libheader| Vcl.Graphics}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Dragon_curve;
Line 1,524 ⟶ 2,706:
Dragon.AsBitmap.SaveToFile('dragon.bmp');
Dragon.Free;
end.</
=={{header|EasyLang}}==
[https://easylang.dev/show/#cod=jU7NDoIwDL73Kb7Em4ZZSDDxwMMQNnHJ3HQjCD69ZWDiwYO9tF/7/bQLLkRwzeSsN0+rhytY1TShQVXTLO3EdAujwYSZWt87IzumHegeQwcd2z54JPsycGaEhoIiAPaS8cJFrglFgy4krCb7rNluMw6NYP/rtjyWw2U2Ln3W38FHpEccUOXEAiXKjbTaSa4WzzP/Iy2yVpGijXZilJU4vgE= Run it]
<syntaxhighlight lang="text">
color 050
linewidth 0.5
x = 25
y = 60
angle = 0
#
if lev = 0
x -= cos angle * size
y += sin angle * size
else
angle -= d * 90
.
.
</syntaxhighlight>
=={{header|Elm}}==
<
import Collage exposing (..)
import Element exposing (..)
Line 1,644 ⟶ 2,828:
, update = update
, subscriptions = subscriptions
}</
Link to live demo: http://dc25.github.io/dragonCurveElm
Line 1,651 ⟶ 2,835:
Drawing ascii art characters into a buffer using <code>[http://www.gnu.org/software/emacs/manual/html_node/emacs/Picture-Mode.html picture-mode]</code>
<syntaxhighlight lang="lisp">(defun dragon-ensure-line-above ()
"If point is in the first line of the buffer then insert a new line above."
(when (= (line-beginning-position) (point-min))
Line 1,742 ⟶ 2,924:
(goto-char (point-min)))
(dragon-picture 128 2)</
{{out}}
<pre>
Line 1,773 ⟶ 2,957:
=={{header|ERRE}}==
Graphic solution with PC.LIB library
<syntaxhighlight lang="erre">
PROGRAM DRAGON
Line 1,821 ⟶ 3,005:
GET(A$)
END PROGRAM
</syntaxhighlight>
=={{header|F Sharp|F#}}==
Using {{libheader|Windows Presentation Foundation}} for visualization:
<
open System.Windows.Media
Line 1,845 ⟶ 3,029:
[ for a, b in nest 13 step (seq [Point(0.0, 0.0), Point(1.0, 0.0)]) ->
PathFigure(a, [(LineSegment(b, true) :> PathSegment)], false) ]
(Application()).Run(Window(Content=Controls.Viewbox(Child=path))) |> ignore</
=={{header|Factor}}==
A translation of the BASIC example, using OpenGL, drawing with HSV coloring similar to the C example.
<syntaxhighlight lang="factor">
USING: accessors colors colors.hsv fry kernel locals math
math.constants math.functions opengl.gl typed ui ui.gadgets
Line 1,904 ⟶ 3,088:
MAIN: dragon-window
</syntaxhighlight>
=={{header|Forth}}==
{{works with|bigFORTH}}
<
2 value dragon-step
Line 1,921 ⟶ 3,105:
home clear
10 45 dragon</
{{works with|4tH}}
Basically the same code as the BigForth version.
[[file:4tHdragon.png|right|thumb|Output png]]
<
include lib/gturtle.4th
Line 1,944 ⟶ 3,128:
clear-screen 50 95 turtle!
xpendown 13 45 dragon
s" 4tHdragon.ppm" save_image</
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Dragon_curve}}
'''Solution'''
=== Recursive ===
[[File:Fōrmulæ - Dragon curve 01.png]]
'''Test case.''' Creating dragon curves from orders 2 to 13
[[File:Fōrmulæ - Dragon curve 02.png]]
[[File:Fōrmulæ - Dragon curve 03.png]]
=== 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 Dragon curve is:
[[File:Fōrmulæ - L-system - Dragon curve 01.png]]
[[File:Fōrmulæ - L-system - Dragon curve 02.png]]
Rounded version:
[[File:Fōrmulæ - L-system - Dragon curve (rounded) 01.png]]
[[File:Fōrmulæ - L-system - Dragon curve (rounded) 02.png]]
=={{header|Gnuplot}}==
Line 1,987 ⟶ 3,166:
Implemented by "parametric" mode running an index t through the desired number of curve segments with X,Y position calculated for each. The "lines" plot joins them up.
<
# The least significant bit is position 0.
# For example n=13 is binary "1101" and the high bit is pos=3.
Line 2,037 ⟶ 3,216:
set parametric
set key off
plot real(dragon(t)),imag(dragon(t)) with lines</
===Version #2.===
Line 2,048 ⟶ 3,227:
;plotdcf.gp:
<
## plotdcf.gp 1/11/17 aev
## Plotting a Dragon curve fractal to the png-file.
Line 2,069 ⟶ 3,248:
plot -100
set output
</syntaxhighlight>
;Plotting 3 Dragon curve fractals:
<
## pDCF.gp 1/11/17 aev
## Plotting 3 Dragon curve fractals.
Line 2,092 ⟶ 3,271:
filename = "DCF"; ttl = "Dragon curve fractal, order ".ord;
load "plotdcf.gp"
</syntaxhighlight>
{{Output}}
<pre>
Line 2,102 ⟶ 3,281:
[[file:GoDragon.png|right|thumb|Output png]]
Version using standard image libriary is an adaptation of the version below using the Bitmap task. The only major change is that line drawing code was needed. See comments in code.
<
import (
Line 2,177 ⟶ 3,356:
dragon(n-1, a1, 1, d, x, y)
dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])
}</
Original version written to Bitmap task:
<
// Files required to build supporting package raster are found in:
Line 2,221 ⟶ 3,400:
dragon(n-1, a1, 1, d, x, y)
dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])
}</
=={{header|Gri}}==
Recursively by a dragon curve comprising two smaller dragons drawn towards a midpoint.
<
Draw a dragon curve going from .x1. .y1. to .x2. .y2. with recursion
depth .level.
Line 2,288 ⟶ 3,467:
set y axis -1 1 .25
Draw Dragon</
=={{header|Haskell}}==
<
import Graphics.Gnuplot.Simple
Line 2,308 ⟶ 3,487:
where lxs = last xs
dragoncurve = iterate vmoot pl</
For plotting I use the gnuplot interface module from [http://hackage.haskell.org/packages/hackage.html hackageDB]
Line 2,315 ⟶ 3,494:
String rewrite, and outputs a postscript:
<
x n = (x$n-1)++" +"++(y$n-1)++" f +"
y 0 = ""
Line 2,325 ⟶ 3,504:
"f", x n, " stroke showpage"]
main = putStrLn $ dragon 14</
=={{header|HicEst}}==
A straightforward approach, since HicEst does not know recursion (rarely needed in daily work)
<
1 DLG(NameEdit=orders,DNum, Button='&OK', TItle=dragon) ! input orders
Line 2,358 ⟶ 3,537:
GOTO 1 ! this is to stimulate a discussion
END</
=={{header|Icon}} and {{header|Unicon}}==
The following implements a Heighway Dragon using the [[Lindenmayer system]]. It's based on the ''linden'' program in the Icon Programming Library.
<
procedure main()
Line 2,381 ⟶ 3,560:
WriteImage("dragon-unicon" || ".gif") # save the image
WDone()
end</
{{libheader|Icon Programming Library}}
Line 2,389 ⟶ 3,568:
=={{header|J}}==
<
start=: 0 0,: 1 0
step=: ],{: +"1 (0 _1,: 1 0) +/ .*~ |.@}: -"1 {:
plot <"1 |: step^:13 start</
In English: Start with a line segment. For each step of iteration, retrace that geometry backwards, but oriented 90 degrees about its original end point. To show the curve you need to pick some arbitrary number of iterations.
Line 2,400 ⟶ 3,579:
For a more colorful display, with a different color for the geometry introduced at each iteration, replace that last line of code with:
<
<div style="border: 1px solid #FFFFFF; overflow: auto; width: 100%"></div>
Line 2,409 ⟶ 3,588:
Giving the code
<
f1=.*&(-:1j1)
f2=.[: -. *&(-:1j_1)
plot (f1,}.@|.@f2)^:12 ]0 1</
Where both functions are applied successively to starting complex values of 0 and 1.
Line 2,418 ⟶ 3,597:
=={{header|Java}}==
<
import java.awt.Graphics;
import java.util.*;
Line 2,473 ⟶ 3,652:
new DragonCurve(14).setVisible(true);
}
}</
=={{header|JavaScript}}==
Line 2,482 ⟶ 3,661:
Though there is an impressive SVG example further below, this uses JavaScript to recurse through the expansion and simply displays each line with SVG. It is invoked as a method <code>DRAGON.fractal(...)</code> as described.
<
// MATRIX MATH
// -----------
Line 2,578 ⟶ 3,757:
};
}());</
My current demo page includes the following to invoke this:
<
<script src='./dragon.js'></script>
...
Line 2,590 ⟶ 3,769:
DRAGON.fractal('fractal', [100,300], [500,300], 15, false, 700);
</script>
...</
====Version #2.====
Line 2,597 ⟶ 3,776:
[[File:DC19.png|200px|right|thumb|Output DC19.png]]
[[File:DC25.png|200px|right|thumb|Output DC25.png]]
<
<!-- DragonCurve.html -->
<html>
Line 2,640 ⟶ 3,819:
</body>
</html>
</syntaxhighlight>
'''Testing cases:'''
<pre>
Line 2,668 ⟶ 3,847:
(Pure JS, without HTML or DOM)
<
'use strict';
Line 3,015 ⟶ 4,194:
// MAIN ---
return main();
})();</
=={{header|jq}}==
{{works with|jq|1.4}}
'''Works with gojq, the Go implementation of jq'''
The programs given here generate SVG code that can be
viewed directly in a browser, at least if the file suffix is .svg.
The first program uses simple turtle graphics and an L-system;
the second is based on the fractalMakeDragon example in [[#Javascript|Javascript]].
===L-System===
See [[Peano_curve#Simple_Turtle_Graphics | Simple Turtle Graphics]]
for the simple-turtle.jq module used in this entry. The `include`
statement assumes the file is in the pwd.
<syntaxhighlight lang="jq">include "simple-turtle" {search: "."};
def rules:
{ F: "F+S",
S: "F-S" };
def dragon($count):
rules as $rules
| def p($count):
if $count <= 0 then .
else gsub("S"; "s") | gsub("F"; $rules["F"]) | gsub("s"; $rules["S"])
| p($count-1)
end;
"F" | p($count) ;
def interpret($x):
if $x == "+" then turtleRotate(90)
elif $x == "-" then turtleRotate(-90)
elif $x == "F" then turtleForward(4)
elif $x == "S" then turtleForward(4)
else .
end;
def dragon_curve($n):
dragon($n)
| split("")
| reduce .[] as $action (turtle([200,300]) | turtleDown;
interpret($action) ) ;
dragon_curve(15)
| path("none"; "red"; "0.1") | svg(1700)</syntaxhighlight>
===fractalMakeDragon===
The following is based on the JavaScript example, with some variations, notably:
* the last argument of the main function allows CSS style elements to be specified
Line 3,033 ⟶ 4,258:
# left if true, make new point on left; if false, then on right
# css a JSON object optionally specifying "stroke" and "stroke-width"
<
def mult(m; v):
[ m[0][0] * v[0] + m[0][1] * v[1],
Line 3,088 ⟶ 4,313:
grow(ptA; ptC; steps; left),
"'/>",
"</svg>";</
'''Example''':
<
fractalMakeDragon("roar"; [100,300]; [500,300]; 15; false; {})</
{{out}}
[https://drive.google.com/file/d/0BwMI1gZaY2-MYW1oanVfMVRTVms/view SVG converted to png]
The command to generate the SVG and the first few lines of output are as follows:
<
<svg width='100%' height='100% '
id='roar'
Line 3,107 ⟶ 4,332:
M259.375 218.75L262.5 218.75
...
</syntaxhighlight>
=={{header|Julia}}==
Line 3,113 ⟶ 4,338:
Code uses Luxor library[https://juliagraphics.github.io/Luxor.jl/latest/turtle.html].
<
using Luxor
function dragon(turtle::Turtle, level=4, size=200, direction=45)
Line 3,132 ⟶ 4,357:
finish()
preview()
</syntaxhighlight>
[[File:Plot 1.png|frameless|center]]
=={{header|Kotlin}}==
{{trans|Java}}
<
import java.awt.Color
Line 3,190 ⟶ 4,416:
fun main(args: Array<String>) {
DragonCurve(14).isVisible = true
}</
=={{header|Lambdatalk}}==
1) two twinned recursive functions
<
{def dcr
{lambda {:step :length}
Line 3,231 ⟶ 4,457:
}}}
-> dcl
</syntaxhighlight>
The word Tθ rotates the drawing direction of the pen from θ degrees
and the word Md moves it on d pixels.
Line 3,244 ⟶ 4,470:
3) drawing three dragon curves [2,6,10] of decreasing width:
<
{svg
{@ width="580px" height="580px"
Line 3,258 ⟶ 4,484:
fill="transparent" stroke=":c" stroke-width=":w"}}
-> stroke
</syntaxhighlight>
The output can be seen in http://lambdaway.free.fr/lambdawalks/?view=dragon
=={{header|Logo}}==
===Recursive===
<
make "step :step - 1
make "length :length / 1.41421
Line 3,334 ⟶ 4,501:
if :step > 0 [lt 45 dcr :step :length rt 90 dcl :step :length lt 45]
if :step = 0 [lt 45 fd :length rt 90 fd :length lt 45]
end</
The program can be started using <tt>dcr 4 300</tt> or <tt>dcl 4 300</tt>.
Or removing duplication:
<
if :step = 0 [fd :length stop]
rt :dir
Line 3,348 ⟶ 4,515:
to dragon :step :length
dc :step :length 45
end</
An alternative approach by using sentence-like grammar using four productions o->on, n->wn, w->ws, s->os. O, S, N and W mean cardinal points.
<
if :step=1 [Rt 90 fd :length Lt 90] [O (:step - 1) (:length / 1.41421) N (:step - 1) (:length / 1.41421)]
end
Line 3,364 ⟶ 4,531:
to S :step :length
if :step=1 [Rt 180 fd :length Lt 180] [O (:step - 1) (:length / 1.41421) S (:step - 1) (:length / 1.41421)]
end</
===Iterative===
Line 3,370 ⟶ 4,537:
{{works with|UCB Logo}}
<
; If :n = binary "...z100..00" then the return is "z000..00".
; Eg. n=22 is binary 10110 the lowest 1-bit is the "...1." and the return is
Line 3,393 ⟶ 4,560:
end
dragon 256</
<
; off with little 45-degree diagonals.
; Done this way the vertices don't touch.
Line 3,414 ⟶ 4,581:
end
dragon.chamfer 256</
=={{header|Lua}}==
{{works with|Lua|5.1.4}}
Could be made much more compact, but this was written for speed. It has two rendering modes, one which renders the curve in text mode (default,) and one which just dumps all the coordinates for use by an external rendering application.
<
local l = "l"
local r = "r"
Line 3,511 ⟶ 4,678:
--replace this line with dump_points() to output a list of coordinates:
render_text_mode() </
Output:
<pre>
Line 3,565 ⟶ 4,732:
[https://1.bp.blogspot.com/-KTPvvri-EAQ/W_7C9ug1WFI/AAAAAAAAHck/NeWCuJ0GXpkMwkANM6i6UJRgZxqig_mXgCLcBGAs/s1600/dragon_curve.png Image]
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
def double angle, d45, d90, change=5000
Line 3,633 ⟶ 4,800:
Checkit
</syntaxhighlight>
=={{header|M4}}==
This code uses the "predicate" approach. A given x,y position is tested by a predicate as to whether it's on the curve or not and printed as a character or a space accordingly. The output goes row by row and column by column with no image storage or buffering.
<syntaxhighlight lang="text"># The macros which return a pair of values x,y expand to an unquoted 123,456
# which is suitable as arguments to a further macro. The quoting is slack
# because the values are always integers and so won't suffer unwanted macro
Line 3,772 ⟶ 4,939:
#
dragon_ascii(-6,5, dnl X range
-10,2) dnl Y range</
;Output
Line 3,831 ⟶ 4,998:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Two functions: one that makes 2 lines from 1 line. And another that applies this function to all existing lines:
<
NextStep[in_]:=Flatten[FoldOutLine/@in,1]
lines={{{0.,0.},{1.,0.}}};
Graphics[Line/@Nest[NextStep,lines,11]]</
=={{header|Metafont}}==
Line 3,841 ⟶ 5,008:
The following code produces a single character font, 25 points wide and tall (0 points in depth), and store it in the position where one could expect to find the character D.
<
dragoniter := 8;
beginchar("D", 25pt#, 25pt#, 0pt#);
Line 3,860 ⟶ 5,027:
draw for v:=1 step 2mstep until (2-2mstep): z[v] -- endfor z[2];
endchar;
end</
The resulting character, magnified by 2, looks like:
Line 3,873 ⟶ 5,040:
Rather than producing a big PPM file, we output a PNG file.
<
import imageman
Line 3,912 ⟶ 5,079:
# Save into a PNG file.
image.savePNG(Output, compression = 9)</
=={{header|OCaml}}==
{{libheader|Tk}}
Example solution, using an OCaml class and displaying the result in a Tk canvas, mostly inspired by the Tcl solution.
<
let pi = acos (-1.0);
Line 3,994 ⟶ 5,161:
ignore (Canvas.create_line ~xys: dcc#get_coords c);
Tk.mainLoop ();
;;</
=== A functional version ===
Here is another OCaml solution, in a functional rather than OO style:
<
let zag (x1,y1) (x2,y2) = (x1+x2-y1+y2)/2, (x1-x2+y1+y2)/2
Line 4,011 ⟶ 5,178:
let points = dragon p1 (zig p1 p2) p2 15 in
ignore (Canvas.create_line ~xys: points c);
Tk.mainLoop ()</
producing:
<div>[[File:OCaml_Dragon-curve-example2.png]]</div>
Line 4,020 ⟶ 5,187:
Using the two sub-curves inward approach. The sub-curves are rotated and shifted explicitly. That could be combined into a <code>multmatrix()</code> each if desired. Lines segments are drawn as elongated cuboids.
<
linewidth = .1; // fraction of segment length
sqrt2 = pow(2, .5);
Line 4,038 ⟶ 5,205:
dragon(level);
}
</syntaxhighlight>
=={{header|PARI/GP}}==
Line 4,045 ⟶ 5,212:
Using the "high level" <code>plothraw</code> with real and imaginary parts of vertex points as X and Y coordinates. Change <code>plothraw()</code> to <code>psplothraw()</code> to write a PostScript file "pari.ps" instead of drawing on-screen.
<
p = [0, 1]; \\ complex number points, initially 0 to 1
Line 4,061 ⟶ 5,228:
p = concat(p, apply(z->(end - I*z), Vecrev(p[^-1]))))
plothraw(apply(real,p),apply(imag,p), 1); \\ flag=1 join points</
===Version #2.===
Using the "low level" plotting functions to draw to a GUI window (X etc).
<
bit_above_low_1(n) = bittest(n, valuation(n,2)+1);
Line 4,081 ⟶ 5,248:
for(i=1,len, plotrline(0,dx,dy); \
if(bit_above_low_1(i), turn_right(), turn_left()));
plotdraw([0,100,100]);</
===Version #3.===
Line 4,092 ⟶ 5,259:
{{Works with|PARI/GP|2.7.4 and above}}
<
\\ Dragon curve
\\ 4/8/16 aev
Line 4,113 ⟶ 5,280:
}
</
{{Output}}
Line 4,136 ⟶ 5,303:
=={{header|Pascal}}==
using Compas (Pascal with Logo-expansion):
<
begin;
step:=step -1;
Line 4,178 ⟶ 5,345:
end;
end;
end;</
main program:
<
init;
penup;
Line 4,187 ⟶ 5,354:
dcr(step,direction,length);
close;
end.</
=={{header|Perl}}==
As in the Raku solution, we'll use a [[wp:L-System|Lindenmayer system]] and draw the dragon in [[wp:SVG|SVG]].
<
use List::Util qw(max min);
Line 4,232 ⟶ 5,399:
open $fh, '>', 'dragon_curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh;</
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/dragon_curve.svg Dragon curve] (offsite image)
Line 4,240 ⟶ 5,407:
You can run this online [http://phix.x10.mx/p2js/dragoncurve.htm here].
Changing the colour and depth give some mildly interesting results.
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\DragonCurve.exw
Line 4,307 ⟶ 5,474:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</
=={{header|PicoLisp}}==
{{trans|Forth}}
This uses the 'brez' line drawing function from [[Bitmap/Bresenham's line algorithm#PicoLisp]].
<
(load "@lib/math.l")
Line 4,351 ⟶ 5,518:
(prinl "P1")
(prinl 300 " " 200)
(mapc prinl Img) ) )</
=={{header|PL/I}}==
Line 4,361 ⟶ 5,528:
A restriction of the pl/i compiler in the 1980s was that array indices could not exceed 32767, thus the escalation to a two-dimensional array, as in <code>DECLARE FOLD(0:31,0:32767) BOOLEAN; /*Oh for (0:1000000) or so..*/</code> This made the array indexing rather messy.
<syntaxhighlight lang="pli">
* PROCESS GONUMBER, MARGINS(1,72), NOINTERRUPT, MACRO;
TEST:PROCEDURE OPTIONS(MAIN);
Line 4,599 ⟶ 5,766:
CALL PLOT(0,0,-3); CALL PLOT(0,0,999);
END TEST;
</syntaxhighlight>
=={{header|PostScript}}==
<
%%BoundingBox: 0 0 550 400
/ifpendown false def
Line 4,645 ⟶ 5,812:
% 0 0 moveto 550 0 rlineto 0 400 rlineto -550 0 rlineto closepath stroke
showpage
%%END</
Or (almost) verbatim string rewrite: (this is a 20 page document, and don't try to print it,
or you might have a very angry printer).
<
%%BoundingBox 0 0 300 300
Line 4,670 ⟶ 5,837:
1 1 20 { dragon showpage } for
%%EOF</
;See also:
* [http://www.cs.unh.edu/~charpov/Programming/L-systems/ L-systems in Postscript]
Line 4,681 ⟶ 5,848:
{{trans|Logo}}
{{libheader|turtle}}
<
[Single]$script:QUARTER_PI=0.7853982
[Single]$script:HALF_PI=1.570796
Line 4,776 ⟶ 5,943:
# display the GDI Form window, which triggers its prepared anonymous drawing function
$Form.ShowDialog()
</syntaxhighlight>
=={{header|Processing}}==
<
int ints = 13;
Line 4,811 ⟶ 5,978:
turn_right(l, ints-1);
}
}</
==={{header|Processing Python mode}}===
<
ints = 13
Line 4,841 ⟶ 6,008:
turn_left(l, ints - 1)
rotate(radians(-90))
turn_right(l, ints - 1)</
=={{header|Prolog}}==
Works with SWI-Prolog which has a Graphic interface XPCE.<BR>
DCG are used to compute the list of "turns" of the Dragon Curve and the list of points.
<
dcg_dg(N, [left], DCL, []),
Side = 4,
Line 4,905 ⟶ 6,072:
inverse(right) -->
[left].</
Output :
<pre>1 ?- dragonCurve(13).
true </pre>[[File : Prolog-DragonCurve.jpg]]
=={{header|Python}}==
{{trans|Logo}}
{{libheader|turtle}}
<
def dragon(step, length):
Line 4,990 ⟶ 6,116:
right(90)
forward(length)
left(45)</
A more pythonic version:
<
def dragon(level=4, size=200, zig=right, zag=left):
Line 5,009 ⟶ 6,135:
hideturtle()
dragon(6)
exitonclick() # click to exit</
Other version:
<
def dragon(level=4, size=200, direction=45):
Line 5,026 ⟶ 6,152:
hideturtle()
dragon(6)
exitonclick() # click to exit</
=={{header|Quackery}}==
<
[ 2 *
Line 5,054 ⟶ 6,180:
right ] resolves left ( n --> )
turtle
20 frames
-260 1 fly
3 4 turn
100 1 fly
5 8 turn
11 left
1 frames</syntaxhighlight>
{{output}}
[[File:Quackery dragon curve.png|thumb|center]]
=={{header|R}}==
===Version #1.===
<syntaxhighlight lang="r">
Dragon<-function(Iters){
Rotation<-matrix(c(0,-1,1,0),ncol=2,byrow=T) ########Rotation multiplication matrix
Line 5,100 ⟶ 6,228:
segments(Iteration[[i]][s,1], Iteration[[i]][s,2], Iteration[[i]][s,3], Iteration[[i]][s,4], col= 'red')
}}#########################################################################
</syntaxhighlight>
[https://commons.wikimedia.org/wiki/File:Dragon_Curve_16_Iterations_R_programming_language.png#mediaviewer/File:Dragon_Curve_16_Iterations_R_programming_language.png]
Line 5,112 ⟶ 6,240:
[[File:DCR13.png|200px|right|thumb|Output DCR13.png]]
[[File:DCR16.png|200px|right|thumb|Output DCR16.png]]
<syntaxhighlight lang="r">
# Generate and plot Dragon curve.
# translation of JavaScript v.#2: http://rosettacode.org/wiki/Dragon_curve#JavaScript
Line 5,146 ⟶ 6,274:
##gpDragonCurve(15, "darkgreen", "", 10, 2, -450, -500)
gpDragonCurve(16, "darkgreen", "", 10, 3, -1050, -500)
</syntaxhighlight>
{{Output}}
Line 5,167 ⟶ 6,295:
=={{header|Racket}}==
<
(require plot)
Line 5,204 ⟶ 6,332:
new-pos
(cons new-pos trail))))])
(plot-file (lines trail) "dragon.png" 'png))</
[[Image:Racket_Dragon_curve.png]]
Line 5,210 ⟶ 6,338:
(formerly Perl 6)
We'll use a L-System role, and draw the dragon in SVG.
<syntaxhighlight lang="raku"
role Lindenmayer {
Line 5,238 ⟶ 6,366:
:polyline[ :points(@points.join: ','), :fill<white> ],
],
);</
=={{header|REXX}}==
Line 5,297 ⟶ 6,377:
This, in effect, allows the dragon curve to be plotted/displayed with a different (starting) orientation.
<
d.= 1; d.L= -d.; @.= ' '; x= 0; x2= x; y= 0; y2= y; z= d.; @.x.y= "∙"
plot_pts = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZΘ' /*plot chars*/
Line 5,331 ⟶ 6,411:
end /*c*/ /* [↑] append a single column of a row.*/
if a\=='' then say strip(a, "T") /*display a line (row) of curve points.*/
end /*r*/ /*stick a fork in it, we're all done. */</
Choosing a ''high visibility'' glyph can really help make the dragon much more viewable; the
<br>solid fill ASCII character (█ or hexadecimal '''db''' in code page 437) is quite good for this.
Line 5,471 ⟶ 6,551:
=={{header|Ruby}}==
{{libheader|Shoes}}
<
Line = Struct.new(:start, :stop)
Line 5,502 ⟶ 6,582:
end
end
end</
{{libheader|RubyGems}}
{{libheader|JRubyArt}}
<
GEN = 14
attr_reader :angle
Line 5,543 ⟶ 6,623:
size(700, 600)
end
</syntaxhighlight>
{{libheader|RubyGems}}
Line 5,549 ⟶ 6,629:
{{libheader|cf3ruby}}
Context Free Art version
<
INV_SQRT = 1 / Math.sqrt(2)
Line 5,586 ⟶ 6,666:
start_x: width / 3, start_y: height / 3.5
end
</syntaxhighlight>
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use ggez::{
conf::{WindowMode, WindowSetup},
Line 5,770 ⟶ 6,814:
event::run(ctx, event_loop, state)
}
</syntaxhighlight>
<div>[[File:dragon_curve_rust.gif]]</div>
=={{header|Scala}}==
<
import java.awt.Graphics
Line 5,824 ⟶ 6,868:
object DragonCurve extends App {
new DragonCurve(14).setVisible(true);
}</
=={{header|Scilab}}==
It uses complex numbers and treats them as vectors to perform rotations of the edges of the curve around one of its ends. The output is a shown in a graphic window.
<syntaxhighlight lang="text">n_folds=10
folds=[];
Line 5,863 ⟶ 6,907:
set(gca(),"isoview","on");
set(gca(),"axes_visible",["off","off","off"]);</
=={{header|Seed7}}==
<
include "float.s7i";
include "math.s7i";
Line 5,913 ⟶ 6,957:
dragon(768.0, 14, 1);
ignore(getc(KEYBOARD));
end func;</
Original source: [http://seed7.sourceforge.net/algorith/graphic.htm#dragon_curve]
Line 5,919 ⟶ 6,963:
=={{header|SequenceL}}==
'''Tail-Recursive SequenceL Code:'''<br>
<
import <Utilities/Conversion.sl>;
Line 5,956 ⟶ 7,000:
result when steps <= 0
else
run(steps - 1, next);</
'''C++ Driver Code:'''<br>
{{libheader|CImg}}
<
#include <vector>
#include "SL_Generated.h"
Line 6,033 ⟶ 7,077:
sl_done();
return 0;
}</
{{out}}
Line 6,040 ⟶ 7,084:
=={{header|Sidef}}==
Uses the '''LSystem()''' class from [https://rosettacode.org/wiki/Hilbert_curve#Sidef Hilbert curve].
<
x => 'x+yF+',
y => '-Fx-y',
Line 6,057 ⟶ 7,101:
)
lsys.execute('Fx', 11, "dragon_curve.png", rules)</
Output image: [https://github.com/trizen/rc/blob/master/img/dragon_curve-sidef.png Dragon curve]
Line 6,071 ⟶ 7,115:
=={{header|SPL}}==
Animation of dragon curve.
<
level = 0
step = 1
Line 6,108 ⟶ 7,152:
<
#.scr()
.</
=={{header|SVG}}==
Line 6,121 ⟶ 7,165:
<div style="clear: right;"></div>
<
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
Line 6,180 ⟶ 7,224:
</g>
</svg></
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
{{libheader|Tk}}
<
set pi [expr acos(-1)]
Line 6,226 ⟶ 7,270:
.c create line {0 0 0 0} -tag dragon
dragon 400 17
.c coords dragon $coords</
See also the Tcl/Tk wiki [http://wiki.tcl.tk/3349 Dragon Curves] and [http://wiki.tcl.tk/10745 Recursive curves] pages.
Line 6,239 ⟶ 7,283:
So, for [[plainTeX]],
<
\usetikzlibrary{lindenmayersystems}
Line 6,252 ⟶ 7,296:
lindenmayer system;
\endtikzpicture
\bye</
=={{header|LaTeX}}==
Or fixed-direction variant to stay horizontal, this time for [[LaTeX]],
<
\usepackage{tikz}
\usetikzlibrary{lindenmayersystems}
Line 6,279 ⟶ 7,323:
}
\begin{document}
\end{document}</
=={{header|Vedit macro language}}==
Line 6,315 ⟶ 7,337:
This way we can avoid using any floating point calculations, trigonometric functions etc.
<
BOF Del_Char(ALL)
Line 6,414 ⟶ 7,436:
#10 = #10 >> 8
}
return</
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|DOME}}
<
import "dome" for Window
Line 6,559 ⟶ 7,491:
static draw(alpha) {}
}</
=={{header|X86 Assembly}}==
[[File:DragX86.gif|right]]
Translation of XPL0. Assemble with tasm, tlink /t
<
.code
.486
Line 6,625 ⟶ 7,557:
pop cx
ret
end start</
=={{header|Xfractint}}==
Line 6,631 ⟶ 7,563:
The <code>xfractint</code> program includes two dragon curves in its lsystem/fractint.l. Here is another version. Xfractint has only a single "F" drawing symbol, so empty symbols X and Y are used for even and odd positions to control the expansion. Each X and each Y is always followed by a single F each.
<
Angle 4
Axiom XF
X=XF+Y
Y=XF-Y
}</
Put this in a file <code>dragon3.l</code> and run as follows. <code>params=8</code> means an 8-order curve.
<
=={{header|XPL0}}==
[[File:DragonXPL0.gif|right]]
<
proc Dragon(D, P, Q); \Draw a colorful dragon curve
Line 6,669 ⟶ 7,601:
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
]</
=={{header|zkl}}==
Draw the curve in SVG to stdout.
{{trans|Raku}}
<
0'|<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'|"\n"
0'|'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>|"\n"
Line 6,747 ⟶ 7,630:
x=dx; y=dy;
}
println("</svg>");</
{{out}}
<pre>
Line 6,764 ⟶ 7,647:
</pre>
http://home.comcast.net/~zenkinetic/Images/dragon.svg
{{omit from|AWK}}
{{omit from|Minimal BASIC}}
[[Category:Geometry]]
|