Pythagoras tree: Difference between revisions

m
m (→‎{{header|J}}: slightly more efficient)
m (→‎{{header|Dart}}: cosmetics)
 
(36 intermediate revisions by 6 users not shown)
Line 206:
End
</syntaxhighlight>
 
==={{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 409 ⟶ 437:
return 0;
}</syntaxhighlight>
 
=={{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">
funcproc tree x1 y1 x2 y2 depth . .
if depth < 8
dx = x2 - x1
Line 428 ⟶ 524:
polygon [ x1 y1 x2 y2 x3 y3 x4 y4 ]
polygon [ x3 y3 x4 y4 x5 y5 ]
call tree x4 y4 x5 y5 depth + 1
call tree x5 y5 x3 y3 depth + 1
.
.
call tree 41 10 59 10 0
</syntaxhighlight>
 
Line 537 ⟶ 633:
Sleep
End</syntaxhighlight>
 
=={{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}}==
Line 677 ⟶ 824:
where mkLine = Data2D [Style Lines, Color Black,Title ""] []
close lst = lst ++ [head lst]</syntaxhighlight>
 
=={{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|J}}==
Line 813 ⟶ 932:
 
=={{header|JavaScript}}==
==={{trans|Java}}===
<syntaxhighlight lang="javascript"><!DOCTYPE html>
<html lang="en">
Line 919 ⟶ 1,038:
 
</html></syntaxhighlight>
==={{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 1,959 ⟶ 2,095:
</syntaxhighlight>
=={{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]]
<syntaxhighlight lang="rust">/* 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);
}
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}"),
}
}</syntaxhighlight>
 
Line 2,231 ⟶ 2,357:
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}}
<syntaxhighlight lang="ecmascriptwren">import "graphics" for Canvas, Color
import "dome" for Window
import "./polygon" for Polygon
106

edits