chaos_game_triangle.pl 1.1 KB

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