pythagoras_tree.pl 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 08 June 2016
  5. # Website: https://github.com/trizen
  6. # See: https://rosettacode.org/wiki/Pythagoras_tree
  7. # https://en.wikipedia.org/wiki/Pythagoras_tree_(fractal)
  8. use Imager;
  9. sub tree {
  10. my ($img, $x1, $y1, $x2, $y2, $depth) = @_;
  11. return () if $depth <= 0;
  12. my $dx = ($x2 - $x1);
  13. my $dy = ($y1 - $y2);
  14. my $x3 = ($x2 - $dy);
  15. my $y3 = ($y2 - $dx);
  16. my $x4 = ($x1 - $dy);
  17. my $y4 = ($y1 - $dx);
  18. my $x5 = ($x4 + 0.5 * ($dx - $dy));
  19. my $y5 = ($y4 - 0.5 * ($dx + $dy));
  20. # Square
  21. $img->polygon(
  22. points => [
  23. [$x1, $y1],
  24. [$x2, $y2],
  25. [$x3, $y3],
  26. [$x4, $y4],
  27. ],
  28. color => [0, 255 / $depth, 0],
  29. );
  30. # Triangle
  31. $img->polygon(
  32. points => [
  33. [$x3, $y3],
  34. [$x4, $y4],
  35. [$x5, $y5],
  36. ],
  37. color => [0, 255 / $depth, 0],
  38. );
  39. tree($img, $x4, $y4, $x5, $y5, $depth - 1);
  40. tree($img, $x5, $y5, $x3, $y3, $depth - 1);
  41. }
  42. my ($width, $height) = (1920, 1080);
  43. my $img = Imager->new(xsize => $width, ysize => $height);
  44. $img->box(filled => 1, color => 'white');
  45. tree($img, $width/2.3, $height, $width/1.8, $height, 10);
  46. $img->write(file => 'pythagoras_tree.png');