chaos_game_pentagon.pl 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 29 April 2017
  5. # https://github.com/trizen
  6. # Chaos game, generating a Sierpinski pentagon.
  7. # See also:
  8. # https://www.youtube.com/watch?v=kbKtFN71Lfs
  9. # https://www.youtube.com/watch?v=e0JaZuLfZ_0 (starting from 18:03)
  10. use 5.010;
  11. use strict;
  12. use warnings;
  13. use Imager;
  14. my $width = 1000;
  15. my $height = 1000;
  16. my @points = (
  17. [$width/2, 0],
  18. [0, $height/2.5],
  19. [$width, $height/2.5],
  20. [$width/5, $height],
  21. [$width-$width/5, $height],
  22. );
  23. my $img = Imager->new(
  24. xsize => $width,
  25. ysize => $height,
  26. channels => 3,
  27. );
  28. my $color = Imager::Color->new('#ff0000');
  29. my $r = [$points[rand(@points)], $points[rand(@points)]];
  30. foreach my $i (1 .. 100000) {
  31. my $p = $points[rand @points];
  32. my $h = [
  33. sprintf('%.0f',($p->[0] + $r->[0]) / 3) + $width/6,
  34. sprintf('%.0f',($p->[1] + $r->[1]) / 3) + $height/5,
  35. ];
  36. $img->setpixel(
  37. x => $h->[0],
  38. y => $h->[1],
  39. color => $color,
  40. );
  41. $r = $h;
  42. }
  43. $img->write(file => 'chaos_game_pentagon.png');