Pythagoras tree: Difference between revisions

m
m (→‎{{header|Rust}}: Used features of rust version 1.58.0 for println!())
m (→‎{{header|Dart}}: cosmetics)
 
(46 intermediate revisions by 10 users not shown)
Line 13:
=={{header|Ada}}==
{{libheader|SDLAda}}
<langsyntaxhighlight Adalang="ada">with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Rectangles;
Line 98:
Window.Finalize;
SDL.Finalise;
end Pythagoras_Tree;</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
Requires [https://www.autohotkey.com/boards/viewtopic.php?t=6517 Gdip Library]
<langsyntaxhighlight AutoHotkeylang="autohotkey">pToken := Gdip_Startup()
gdip1()
Pythagoras_tree(600, 600, 712, 600, 1)
Line 172:
gdip2()
ExitApp
return</langsyntaxhighlight>
 
=={{header|BASIC256BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
Subroutine pythagoras_tree(x1, y1, x2, y2, depth)
If depth > 10 Then Return
Line 204 ⟶ 205:
ImgSave "pythagoras_tree.jpg", "jpg"
End
</syntaxhighlight>
</lang>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Pythagor.bas"
110 OPTION ANGLE DEGREES
120 LET SQ2=SQR(2)
130 SET VIDEO MODE 1:SET VIDEO COLOUR 0:SET VIDEO X 42:SET VIDEO Y 25
140 OPEN #101:"video:"
150 SET PALETTE 0,141
160 DISPLAY #101:AT 1 FROM 1 TO 25
170 PLOT 580,20;ANGLE 90;
180 CALL BROCCOLI(225,10)
190 DO
200 LOOP WHILE INKEY$=""
210 TEXT
220 DEF BROCCOLI(X,Y)
230 IF X<Y THEN EXIT DEF
240 CALL SQUARE(X)
250 PLOT FORWARD X,LEFT 45,
260 CALL BROCCOLI(X/SQ2,Y)
270 PLOT RIGHT 90,FORWARD X/SQ2,
280 CALL BROCCOLI(X/SQ2,Y)
290 PLOT BACK X/SQ2,LEFT 45,BACK X,
300 END DEF
310 DEF SQUARE(X)
320 FOR I=1 TO 4
330 PLOT FORWARD X;RIGHT 90;
340 NEXT
350 END DEF</syntaxhighlight>
 
=={{header|C}}==
Line 210 ⟶ 239:
 
Requires the [http://www.cs.colorado.edu/~main/bgi/cs1300/ WinBGIm] library.
<syntaxhighlight lang="c">
<lang C>
#include<graphics.h>
#include<stdlib.h>
Line 277 ⟶ 306:
return 0;
 
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 283 ⟶ 312:
Windows version
{{trans|Java}}
<langsyntaxhighlight lang="cpp">#include <windows.h>
#include <string>
#include <iostream>
Line 407 ⟶ 436:
t.save( "?:/pt.bmp" );
return 0;
}</langsyntaxhighlight>
 
=={{header|Dart}}==
===Creating an SVG file===
{{trans|Rust}}
Dart version: ^3.0.0
<syntaxhighlight lang="dart">import 'dart:math';
import 'dart:io';
 
void main() {
var basis = [(Point(-200.0, 0.0), Point(200.0, 0.0))];
final groups = Iterable.generate(12, (lvl) {
final basis0 = basis;
basis = [];
final lvlPolygons = basis0.map((pp) {
final (a, b) = pp;
final v = Point((b - a).y, (a - b).x);
final [c, d, e] = [a, b, (a + b + v) * 0.5].map((p) => p + v).toList();
basis.addAll([(c, e), (e, d)]);
return '<polygon points="${[a, c, e, d, c, d, b].expand((p) => [p.x, p.y]).join(' ')}"/>';
}).join('\n');
rg(int step) => ((80 + (lvl - 2) * step) & 255).toRadixString(16).padLeft(2, '0');
return '<g fill="#${rg(20)}${rg(30)}18">\n$lvlPolygons\n</g>';
}).join('\n');
final (x, y) = basis.fold((0.0, 0.0), (p, pp) => (min(p.$1, pp.$1.x), min(p.$2, pp.$1.y)));
final attrs = 'viewBox="$x $y ${-x - x} ${-y}" stroke="white" xmlns="http://www.w3.org/2000/svg"';
File('Pythagor_tree.svg').writeAsString('<svg $attrs>\n$groups\n</svg>');
}
</syntaxhighlight>
===Drawing in Flutter===
[https://dartpad.dev/?id=c5a5f23a36c2707b7d57e2fd1359ebd3 View output / play with the code - online in DartPad]
<syntaxhighlight lang="dart">import 'package:flutter/material.dart';
 
void main() => runApp(FittedBox(
child: CustomPaint(painter: TreePainter(), size: const Size(2400, 1600))));
 
class TreePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final stroke = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 0.9
..color = Colors.white;
final fill = Paint()..style = PaintingStyle.fill;
canvas.drawColor(Colors.white, BlendMode.src);
 
const halfBase = Offset(200, 0);
var basis = [(size.bottomCenter(-halfBase), size.bottomCenter(halfBase))];
for (var lvl = 0; lvl < 12; lvl++) {
final path = Path();
final basis0 = basis;
basis = [];
for (var (a, b) in basis0) {
final v = Offset((b - a).dy, (a - b).dx);
final [c, d, e] = [a, b, (a + b + v) / 2].map((p) => p + v).toList();
basis.addAll([(c, e), (e, d)]);
path.addPolygon([a, c, e, d, c, d, b], true);
}
rg(int step) => (80 + (lvl - 2) * step) & 255;
canvas
..drawPath(path, fill..color = Color.fromARGB(255, rg(20), rg(30), 18))
..drawPath(path, stroke);
}
}
 
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
</syntaxhighlight>
 
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=ZZDLCoMwFET3fsUs24qp8QEW2i8pXal9gDQiLpK/79zEgKGBBO7Mua/Mi+mxLuMIq+E0bAVXYRjn9Q0FlQH4PLf4ik5insHiJmjBrCg5SixQMH+TbB2onOYmOZGcl2ykGqF0QjWh1p5qhWoolarFCQeOIBnHmCK+S/1i5/dmMktNU67v71c6Q3cU4hKzmdzLfHFPfoN7cG42Z/3HP7lzOSUHiUz41p0ReubQCeCtUCUBVKYyTzQaukR7kbfMfg== Run it]
[https://easylang.online/apps/_pythagoras-tree.html Run it]
 
<syntaxhighlight lang="text">
<lang>func tree x1 y1 x2 y2 depth . .
proc tree ifx1 y1 x2 y2 depth <. 8.
if dxdepth =< x2 - x18
dy dx = y1x2 - y2x1
x3 dy = x2y1 - dyy2
y3 x3 = y2x2 -+ dxdy
x4 y3 = x1y2 -+ dydx
y4 x4 = y1x1 -+ dxdy
x5 y4 = x4y1 + 0.5 * (dx - dy)
y5 x5 = y4x4 -+ 0.5 * (dx + dy)
set_rgb 0.3 y5 = y4 + 0.25 +* depth(dx /- 18 0.1dy)
draw_polygon [ x1color3 y10.3 x20.2 y2+ x3depth y3/ x418 y4 ]0.1
draw_polygon polygon [ x1 y1 x2 y2 x3 y3 x4 y4 x5 y5 ]
call tree polygon [ x3 y3 x4 y4 x5 y5 depth + 1]
call tree x5x4 y5y4 x3x5 y3y5 depth + 1
tree x5 y5 x3 y3 depth + 1
.
.
.
tree 41 10 59 10 0
set_rgb 0.3 0 0.1
</syntaxhighlight>
call tree 41 90 59 90 0</lang>
 
=={{header|F_Sharp|F#}}==
<p>Creating an HTML file with an inline SVG. The generation of the tree is done breadth first.</p>
<langsyntaxhighlight lang="fsharp">type Point = { x:float; y:float }
type Line = { left : Point; right : Point }
 
Line 493 ⟶ 591:
generate [{ left = { x = 275.; y = 500. }; right = { x = 375.; y = 500. } }] depth
out draw_end_html
0</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
{{trans|zkl}}
<langsyntaxhighlight lang="freebasic">' version 03-12-2016
' compile with: fbc -s gui
' or fbc -s console
Line 534 ⟶ 632:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_window = 1
 
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 705, 500 )
window _window, @"Pythagoras Tree In FutureBasic", r, NSWindowStyleMaskTitled
WindowSetBackgroundColor( _window, fn ColorBlack )
end fn
 
local fn PythagorasTree( x1 as double, y1 as double, x2 as double, y2 as double, depth as NSUInteger )
if depth > 10 then exit fn
double dx = x2 - x1, dy = y1 - y2
double x3 = x2 - dy, y3 = y2 - dx
double x4 = x1 - dy, y4 = y1 - dx
double x5 = x4 + (dx - dy) / 2
double y5 = y4 - (dx + dy) / 2
select ( rnd(5) )
case 1 : pen 2, fn ColorBrown
case 2 : pen 2, fn ColorRed
case 3 : pen 2, fn ColorOrange
case 4 : pen 2, fn ColorYellow
case 5 : pen 2, fn ColorGreen
end select
line x1, y1, x2, y2 : Line x2, y2, x3, y3
line x3, y3, x4, y4 : Line x4, y4, x1, y1
fn PythagorasTree( x4, y4, x5, y5, depth +1 )
fn PythagorasTree( x5, y5, x3, y3, depth +1 )
end fn
 
local fn DrawTree
NSUInteger w = 700, h = w * 11 \ 16
NSUInteger w2 = w \ 2, diff = w \ 12
fn PythagorasTree( w2 - diff, h -10 , w2 + diff , h -10 , 0 )
end fn
 
random
 
fn BuildWindow
fn DrawTree
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Pythagoras_Tree_FutureBasic.png]]
 
=={{header|Go}}==
<langsyntaxhighlight Golang="go">package main
 
import (
Line 622 ⟶ 771:
}
return x
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 630 ⟶ 779:
Firstly, we define a function <code>mkBranches</code> that produces a pair of minor squares based on a given square. Each square is represented as a list of points.
 
<langsyntaxhighlight lang="haskell">mkBranches :: [(Float,Float)] -> [[(Float,Float)]]
mkBranches [a, b, c, d] = let d = 0.5 <*> (b <+> (-1 <*> a))
l1 = d <+> orth d
Line 640 ⟶ 789:
(a, b) <+> (c, d) = (a+c, b+d)
n <*> (a, b) = (a*n, b*n)
orth (a, b) = (-b, a)</langsyntaxhighlight>
 
We then create <code>squares</code> using <code>mkBranches</code> to build a list representing the set of squares. In order to apply this function iteratively to form a 10-generation tree, we also have to define the monadic iteration <code>iterateM</code> within <code>squares</code>.
 
<langsyntaxhighlight lang="haskell">squares = concat $ take 10 $ iterateM mkBranches start
where start = [(0,100),(100,100),(100,0),(0,0)]
iterateM f x = iterate (>>= f) (pure x)</langsyntaxhighlight>
 
The raw result returned by <code>squares</code> should be used in the <code>main</code> function in order to be displayed in a new window, saved directly to a SVG file, or printed to a bitmap file.
Line 652 ⟶ 801:
'''Window output'''
{{libheader|Gloss}}
<langsyntaxhighlight lang="haskell">--import should go to the top of the code
import Graphics.Gloss
 
main = display (InWindow "Pithagoras tree" (400, 400) (0, 0)) white tree
where tree = foldMap lineLoop squares</langsyntaxhighlight>
 
'''SVG file'''
<langsyntaxhighlight lang="haskell">main = writeFile "pith.svg" svg
where svg = "<svg " ++ attrs ++ foldMap (mkLine . close) squares ++ "</svg>"
attrs = "fill='none' stroke='black' height='400' width='600'>"
mkLine path = "<polyline points ='" ++ foldMap mkPoint path ++ "'/>"
mkPoint (x,y) = show (250+x) ++ "," ++ show (400-y) ++ " "
close lst = lst ++ [head lst]</langsyntaxhighlight>
 
'''Bitmap image'''
{{libheader|easyplot}}
<langsyntaxhighlight lang="haskell">--import should go to the top of the code
import Graphics.EasyPlot
 
Line 674 ⟶ 823:
main = plot (PNG "pith.png") $ map (mkLine . close) squares
where mkLine = Data2D [Style Lines, Color Black,Title ""] []
close lst = lst ++ [head lst]</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 PROGRAM "Pythagor.bas"
110 OPTION ANGLE DEGREES
120 LET SQ2=SQR(2)
130 SET VIDEO MODE 1:SET VIDEO COLOUR 0:SET VIDEO X 42:SET VIDEO Y 25
140 OPEN #101:"video:"
150 SET PALETTE 0,141
160 DISPLAY #101:AT 1 FROM 1 TO 25
170 PLOT 580,20;ANGLE 90;
180 CALL BROCCOLI(225,10)
190 DO
200 LOOP WHILE INKEY$=""
210 TEXT
220 DEF BROCCOLI(X,Y)
230 IF X<Y THEN EXIT DEF
240 CALL SQUARE(X)
250 PLOT FORWARD X,LEFT 45,
260 CALL BROCCOLI(X/SQ2,Y)
270 PLOT RIGHT 90,FORWARD X/SQ2,
280 CALL BROCCOLI(X/SQ2,Y)
290 PLOT BACK X/SQ2,LEFT 45,BACK X,
300 END DEF
310 DEF SQUARE(X)
320 FOR I=1 TO 4
330 PLOT FORWARD X;RIGHT 90;
340 NEXT
350 END DEF</lang>
 
=={{header|J}}==
<syntaxhighlight lang=J>require'plot'
Using the bash shell, gnuplot for graphics, with ijconsole installed on the PATH, and having saved the program in the file /tmp/pt.ijs the following command plots the Pythagoras tree:
 
Pt=: {{
<pre>
if. 0<m do.
gnuplot --persist -e 'plot"<ijconsole /tmp/pt.ijs"w l'
d=. 0j1*y-x
</pre>
p2=. y+d
p3=. x+d
p4=. (0.5*x+y)+1.5*d
pd x,y,p2,p3
p3 (<:m) Pt p4
p4 (<:m) Pt p2
end.
}}
 
<lang J>
NB. use on linux: gnuplot --persist -e 'plot"< ijconsole /tmp/pt.ijs"w l'
 
NB. translated from c
 
ex=: {.
why=: {:
but_first=: & NB. just for fun
append=: ,
subtract=: -
 
X=: adverb def ' ex m'
Y=: adverb def 'why m'
 
pt=: dyad define
 
'a b'=. y
 
NB. c.x = b.x - (a.y - b.y);
NB. c.y = b.y - (b.x - a.x);
c=. (b X , a append but_first why b) ,&(-/) (b Y , b ,&ex a)
NB. d.x = a.x - (a.y - b.y);
NB. d.y = a.y - (b.x - a.x);
d=. (a X , a append but_first why b) ,&(-/) (a Y , b ,&ex a)
 
NB. e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2;
NB. e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2;
e=. (d X + -: (b -&ex a) - a subtract but_first why b) , d Y - -: -/ b X , a X , a Y , b Y
 
if. 0 < x do.
NB. line(a.x,a.y,b.x,b.y); line(c.x,c.y,b.x,b.y); line(c.x,c.y,d.x,d.y); line(a.x,a.y,d.x,d.y);
echo (a ,: b) , (c ,: b) , (c ,: d) ,: (a ,: d)
echo ''
(<: x) pt"2 (d ,: e) ,: (e ,: c) NB. pythagorasTree(d,e,times-1);pythagorasTree(e,c,times-1);
end.
)
 
Pytree=: {{
pd 'reset'
pd 'type poly'
5r2j4 y Pt 7r2j4
pd 'show'
}}
 
Pytree 7</syntaxhighlight>
NB. a.x = 6*side/2 - side/2;
NB. a.y = 4*side;
NB. b.x = 6*side/2 + side/2;
NB. b.y = 4*side;
petri=: 7&$: :(empty@:(pt (x:inv 5r2 7r2 ,. 4)&*))
 
[[File:J-pytree.png]]
petri 1
exit 0
</lang>
 
=={{header|Java}}==
[[File:pythagoras_tree.png|300px|thumb|right]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
Line 837 ⟶ 929:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
==={{trans|Java}}===
<langsyntaxhighlight lang="javascript"><!DOCTYPE html>
<html lang="en">
 
Line 945 ⟶ 1,037:
</body>
 
</html></langsyntaxhighlight>
==={{trans|Rust}}===
[[File:PythagorTreeJS.svg|400px]]<br>
Run this script from the browser console (F12) or from the <script> tag of an html document.
<syntaxhighlight lang="javascript">let base = [[{ x: -200, y: 0 }, { x: 200, y: 0 }]];
const doc = [...Array(12)].reduce((doc_a, _, lvl) => {
const rg = step => `0${(80 + (lvl - 2) * step).toString(16)}`.slice(-2);
return doc_a + base.splice(0).reduce((ga, [a, b]) => {
const w = (kx, ky) => (kx * (b.x - a.x) + ky * (b.y - a.y)) / 2;
const [c, e, d] = [2, 3, 2].map((j, i) => ({ x: a.x + w(i, j), y: a.y + w(-j, i) }));
base.push([c, e], [e, d]);
return ga + `<polygon points="${[a, c, e, d, c, d, b].map(p => [p.x, p.y])}"/>\n`;
}, `<g fill="#${rg(20)}${rg(30)}18">\n`) + '</g>\n';
}, '<svg xmlns="http://www.w3.org/2000/svg" width="1200" stroke="white">\n') + '</svg>';
 
const { x, y } = base.flat().reduce((a, p) => ({ x: Math.min(a.x, p.x), y: Math.min(a.y, p.y) }));
const svg = doc.replace('<svg ', `<svg viewBox="${[x, y, -x - x, -y]}" `);
document.documentElement.innerHTML = svg, ''; // display svg in the browser window</syntaxhighlight>
 
=={{header|jq}}==
Line 956 ⟶ 1,065:
 
Notice that the SVG viewBox dimensions are computed dynamically.
<syntaxhighlight lang="jq">
<lang jq>
# viewBox = <min-x> <min-y> <width> <height>
# Input: {svg, minx, miny, maxx, maxy}
Line 1,017 ⟶ 1,126:
 
PythagorasTree | svg
</syntaxhighlight>
</lang>
{{out}}
 
Line 1,023 ⟶ 1,132:
=={{header|Julia}}==
{{trans|PARI/GP}}
<langsyntaxhighlight Julialang="julia">using Gadfly
using DataFrames
 
Line 1,066 ⟶ 1,175:
end
 
pythagorastree(275.,500.,375.,500.,640., 9)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.awt.*
Line 1,149 ⟶ 1,258:
}
}
}</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
===Cartesian Coordinates===
{{trans|zkl}}
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
MODULE Pythagoras_tree {
CLS 5, 0 ' MAGENTA, NO SPLIT SCREEN
Line 1,184 ⟶ 1,293:
}
Pythagoras_tree
</syntaxhighlight>
</lang>
===Polar Coordinates===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
MODULE Pythagoras_Example{
CLS 5, 0 ' MAGENTA, split line = 0
Line 1,231 ⟶ 1,340:
}
Pythagoras_Example
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">n = 7;
colors = Blend[{Orange, Yellow, Green}, #] & /@ Subdivide[n - 1];
ClearAll[NextConfigs, NewConfig]
Line 1,250 ⟶ 1,359:
config = <|"quads" -> {nc["quad"]}, "triangs" -> {nc["triang"]}|>;
config = NestList[NextConfigs, config, n - 1];
Graphics[MapThread[{EdgeForm[Black], FaceForm[#2], #1["quads"], #1["triangs"]} &, {config, colors}]]</langsyntaxhighlight>
 
=={{header|Nim}}==
Line 1,256 ⟶ 1,365:
{{libheader|imageman}}
Using Perl algorithm with some changes: background is black and there is no color variation according to depth.
<langsyntaxhighlight Nimlang="nim">import imageman
 
const
Line 1,292 ⟶ 1,401:
var image = initImage[ColorRGBU](Width, Height)
image.drawTree(int(Width / 2.3), Height - 1, int(Width / 1.8), Height - 1, MaxDepth)
image.savePNG("pythagoras_tree.png", compression = 9)</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(import (lib gl))
(import (OpenGL version-1-0))
Line 1,338 ⟶ 1,447:
))
))
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
Line 1,350 ⟶ 1,459:
{{Works with|PARI/GP|2.7.4 and above}}
 
<langsyntaxhighlight lang="parigp">\\ Pythagoras Tree (w/recursion)
\\ 4/11/16 aev
plotline(x1,y1,x2,y2)={plotmove(0, x1,y1);plotrline(0,x2-x1,y2-y1);}
Line 1,383 ⟶ 1,492:
{\\ Executing:
PythagorTree(275,500,375,500,9,640); \\PythTree1.png
}</langsyntaxhighlight>
{{Output}}
<pre> *** Pythagoras Tree, depth 9, size 640
Line 1,390 ⟶ 1,499:
=={{header|Perl}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="perl">use Imager;
 
sub tree {
Line 1,436 ⟶ 1,545:
$img->box(filled => 1, color => 'white');
tree($img, $width/2.3, $height, $width/1.8, $height, 10);
$img->write(file => 'pythagoras_tree.png');</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 1,443 ⟶ 1,552:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/PythagorasTree.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\PythagorasTree.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 1,528 ⟶ 1,637:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|Processing}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="java">void tree(float x1, float y1, float x2, float y2, int depth) {
 
if (depth <= 0) {
Line 1,576 ⟶ 1,685:
stroke(0, 255, 0);
tree(width/2.3, height, width/1.8, height, 10);
}</langsyntaxhighlight>
 
==={{header|Processing Python mode}}===
<langsyntaxhighlight lang="python">def setup():
size(800, 400)
background(255)
Line 1,618 ⟶ 1,727:
 
tree(x4, y4, x5, y5, depth - 1)
tree(x5, y5, x3, y3, depth - 1)</langsyntaxhighlight>
 
=={{header|PureBasic}}==
{{trans|FreeBasic}}
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
DisableDebugger
 
Line 1,682 ⟶ 1,791:
Repeat : Until WaitWindowEvent(50)=#PB_Event_CloseWindow
EndIf
End</langsyntaxhighlight>
 
=={{header|Python}}==
Using [https://docs.python.org/3/library/turtle.html turtle graphics] and the Zkl example for the calculations.
<langsyntaxhighlight lang="python">from turtle import goto, pu, pd, color, done
 
def level(ax, ay, bx, by, depth=0):
Line 1,705 ⟶ 1,814:
pu()
level(-100, 500, 100, 500, depth=8)
done()</langsyntaxhighlight>
 
=={{header|R}}==
Line 1,712 ⟶ 1,821:
[[File:PYTHTR9.png|200px|right|thumb|Output PYTHTR9.png]]
[[File:PYTHTR7.png|200px|right|thumb|Output PYTHTR7.png]]
<langsyntaxhighlight lang="r">## Recursive PT plotting
pythtree <- function(ax,ay,bx,by,d) {
if(d<0) {return()}; clr="darkgreen";
Line 1,743 ⟶ 1,852:
## Executing:
pPythagorasT(275,500,375,500,9)
pPythagorasT(275,500,375,500,7)</langsyntaxhighlight>
{{Output}}
<pre>> pPythagorasT(275,500,375,500,9)
Line 1,755 ⟶ 1,864:
 
=={{header|QB64}}==
<langsyntaxhighlight lang="qb64">_Title "Pythagoras Tree"
 
Dim As Integer sw, sh
Line 1,790 ⟶ 1,899:
Call pythTree(ex, ey, dx, dy, depth + 1)
End If
End Sub</langsyntaxhighlight>
 
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(require racket/draw pict)
 
Line 1,824 ⟶ 1,933:
(send the-dc set-pen old-pen)))
 
(dc (draw-pythagoras-tree 7 (+ 200 32) 255 (- 200 32) 255) 400 256)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
We'll generate a SVG image.
<syntaxhighlight lang="raku" perl6line>class Square {
has Complex ($.position, $.edge);
method size { $!edge.abs }
Line 1,859 ⟶ 1,968:
}
 
tree Square.new: :position(250+0i), :edge(60+0i);</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring"># Project : Pythagoras tree
 
load "guilib.ring"
Line 1,929 ⟶ 2,038:
paint.drawline(x4,y4,x1,y1)
pythagorastree(x4, y4, x5, y5, depth +1)
pythagorastree(x5, y5, x3, y3, depth +1)</langsyntaxhighlight>
Output:
https://www.dropbox.com/s/a1gtue7tvmaj2je/PythagorasTree.jpg?dl=0
Line 1,937 ⟶ 2,046:
{{libheader|JRubyArt}}
A clone of processing version
<langsyntaxhighlight lang="ruby">
# frozen_string_literal: true
 
Line 1,984 ⟶ 2,093:
end
 
</syntaxhighlight>
</lang>
=={{header|Rust}}==
Creates a '''[httphttps://gist.githubusercontent.com/vvshard/833bd69acfa9160350cdbc9b57bbefe4/raw/pythagoras_tree.svg svg file]'''pythagoras_tree.svg file (12 levels)'''] that can be opened in a browser<br>
[[File:Pythagoras_tree.svg]]
<lang fsharp>/* add to file Cargo.toml:
[dependencies]
svg = "0.10.0"
*/
 
'''[dependencies]'''<br>
use svg::node::element::{Group, Polygon};
svg = "0.12"
<syntaxhighlight lang="rust">use svg::node::element::{Group, Polygon};
 
fn main() {
let mut docbase: Vec<[(f64, f64); 2]> = svg::Document::newvec![[()-200.set, 0.), ("stroke"200., "white"0.)]];
let doc = (0..12_u8).fold(svg::Document::new().set("stroke", "white"), |doc_a, lvl| {
let mut base: Vec<[(f64, f64); 2]> = vec![[(-200.0, 0.0), (200.0, 0.0)]];
for lvl in 0..12u8 {
let rg = |step| lvl.wrapping_mul(step).wrapping_add(80 - step * 2);
let mut groupg = Group::new().set("fill", format!("#{:02X}{:02X}18", rg(20), rg(30))); // level color
doc_a.add(base.split_off(0).into_iter().fold(g, |ga, [a, b]| {
let mut next_base = Vec::new();
for [a, b] in base {
let v = (b.0 - a.0, b.1 - a.1);
let [c, d, w] = ([a, b, v].map(|p| (p.0 + v.1, ap.1 - v.0));
let de = (c.0 + vw.0 / 2., c.1 + vw.1 / 2.);
let e = base.extend([[c.0, +e], 0.5 * (v.0 + v.1)[e, c.1 + 0.5 * (v.1 - v.0)d]]);
group = groupga.add(Polygon::new().set("points", vec![a, c, e, d, c, d, b]));
}))
next_base.extend([[c, e], [e, d]]);
});
let (x, y) = (base.iter()).fold((0., 0.), |(xa, ya), [p, _]| (p.0.min(xa), p.1.min(ya)));
base = next_base;
svg::save("Pythagor_tree.svg", &doc.set("viewBox", (x, y, -x - x, -y))).unwrap();
doc = doc.add(group);
}</syntaxhighlight>
}
let (x0, y0) = (base.iter()).fold((0.0, 0.0), |(x0, y0), [(x, y), _]| (x.min(x0), y.min(y0)));
let file = "pythagoras_tree.svg";
match svg::save(file, &doc.set("viewBox", (x0, y0, -x0 * 2.0, -y0))) {
Ok(_) => println!("{file} file written successfully!"),
Err(e) => println!("failed to write {file}: {e}"),
}
}</lang>
 
=={{header|Scala}}==
===Java Swing Interoperability===
<langsyntaxhighlight Scalalang="scala">import java.awt._
import java.awt.geom.Path2D
 
Line 2,078 ⟶ 2,177:
})
 
}</langsyntaxhighlight>
 
=={{header|Scilab}}==
===L-System approach===
This solution uses complex numbers to represent vectors, and it draws the contour of the tree. By "uncommenting" the six commented lines inside the <code>select</code> structure, it will also draw the triangles between the squares. The output is a new graphic window.
<syntaxhighlight lang="text">side = 1; //side length of the square
depth = 8; //final number of branch levels
 
Line 2,174 ⟶ 2,273:
plot2d(real(tree),imag(tree),14);
set(gca(),'isoview','on');
set(gca(),'axes_visible',['off','off','off']);</langsyntaxhighlight>
===Recursive approach===
A minor change was made so that the final depth of the tree is an argument of <code>fcn</code>, and not a condition set within itself.
{{trans|zkl}}
<syntaxhighlight lang="text">function []=fcn(bitmap,ax,ay,bx,by,depth)
if depth < 0 then
return
Line 2,206 ⟶ 2,305:
xname('Pythagoras tree: '+string(final_depth)+' levels');
set(gca(),'isoview','on');
set(gca(),'axes_visible',['off','off','off']);</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Java}}
<langsyntaxhighlight lang="ruby">require('Imager')
 
func tree(img, x1, y1, x2, y2, depth) {
Line 2,255 ⟶ 2,354:
img.box(filled => 1, color => 'white')
tree(img, width/2.3, height, width/1.8, height, 10)
img.write(file => 'pythagoras_tree.png')</langsyntaxhighlight>
Output image: [https://github.com/trizen/rc/blob/master/img/pythagoras-tree-sidef.png Pythagoras tree]
 
=={{header|uBasic/4tH}}==
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">Dim @o(5) ' 0 = SVG file, 1 = color, 2 = fillcolor, 3 = pixel, 4 = text
 
' === Begin Program ===
 
w = 800 : h = w * 11 / 16
v = w / 2 : d = w / 12
 
Proc _SVGopen ("pythtree.svg") ' open the SVG file
Proc _Canvas (w, h) ' set the canvas size
Proc _Background (FUNC(_Color ("White")))
' we have a white background
Proc _Pythagoras_tree (v - d, h - 10, v + d, h - 10, 0)
Proc _SVGclose
End
 
_Pythagoras_tree
Param (5)
Local (8)
 
If e@ > 10 Then Return
 
f@ = c@ - a@ : g@ = b@ - d@
h@ = c@ - g@ : i@ = d@ - f@
j@ = a@ - g@ : k@ = b@ - f@
l@ = j@ + (f@ - g@) / 2
m@ = k@ - (f@ + g@) / 2
 
Proc _SetColor (FUNC(_RGBtoColor (0, e@*25, 0)))
' draw the box
Proc _Line (b@, a@, d@, c@) : Proc _Line (d@, c@, i@, h@)
Proc _Line (i@, h@, k@, j@) : Proc _Line (k@, j@, b@, a@)
 
Proc _Pythagoras_tree (j@, k@, l@, m@, e@ +1)
Proc _Pythagoras_tree (l@, m@, h@, i@, e@ +1)
Return
 
' === End Program ===
 
_RGBtoColor Param (3) : Return (a@ * 65536 + b@ * 256 + c@)
_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</syntaxhighlight>
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|DOME}}
{{libheader|Wren-polygon}}
<langsyntaxhighlight ecmascriptlang="wren">import "graphics" for Canvas, Color
import "dome" for Window
import "./polygon" for Polygon
Line 2,314 ⟶ 2,534:
}
 
var Game = PythagorasTree.new(640, 640)</langsyntaxhighlight>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">proc DrawTree(X1, Y1, X2, Y2, Depth);
int X1, Y1, X2, Y2, Depth;
int X3, Y3, X4, Y4, X5, Y5, DX, DY, Color;
[if Depth < 7 then
[DX:= X2 - X1; DY:= Y1 - Y2;
X3:= X2 - DY; Y3:= Y2 - DX;
X4:= X1 - DY; Y4:= Y1 - DX;
X5:= X4 + (DX-DY)/2; Y5:= Y4 - (DX+DY)/2;
Color:= $2A + Depth;
Move(X1, Y1);
Line(X2, Y2, Color); Line(X3, Y3, Color);
Line(X4, Y4, Color); Line(X1, Y1, Color);
DrawTree(X4, Y4, X5, Y5, Depth+1);
DrawTree(X5, Y5, X3, Y3, Depth+1);
];
];
 
def ScrW=320, ScrH=200;
[SetVid($13);
DrawTree(9*ScrW/20, 3*ScrH/4, 11*ScrW/20, 3*ScrH/4, 0);
]</syntaxhighlight>
{{out}}
[[File:PythtreeXPL0.gif]]
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight Yabasiclang="yabasic">Sub pythagoras_tree(x1, y1, x2, y2, depth)
local dx, dy, x3, y3, x4, y4, x5, y5
Line 2,348 ⟶ 2,593:
clear window
 
pythagoras_tree(w2 - diff, h -10 , w2 + diff , h -10 , 1)</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 2,355 ⟶ 2,600:
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
[[File:PythagorasTreeWithLeafs.zkl.jpg|300px|thumb|right]]
<langsyntaxhighlight lang="zkl">fcn pythagorasTree{
bitmap:=PPM(640,640,0xFF|FF|FF); // White background
 
Line 2,373 ⟶ 2,618:
 
bitmap.writeJPGFile("pythagorasTree.jpg",True);
}();</langsyntaxhighlight>
106

edits