chaos_game_tetrahedron.pl 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 Tetrahedron.
  7. # https://en.wikipedia.org/wiki/Chaos_game
  8. use 5.010;
  9. use strict;
  10. use warnings;
  11. use Imager;
  12. my $width = 2000;
  13. my $height = 2000;
  14. my @points = (
  15. [int($width/2), 0],
  16. [ 0, int($height-$height/4)],
  17. [ $width-1, int($height-$height/4)],
  18. [int($width/2), $height-1],
  19. );
  20. my $img = Imager->new(
  21. xsize => $width,
  22. ysize => $height,
  23. channels => 3,
  24. );
  25. my $color = Imager::Color->new('#ff0000');
  26. my $r = [int(rand($width)), int(rand($height))];
  27. foreach my $i (1 .. 200000) {
  28. my $p = $points[rand @points];
  29. my $h = [
  30. int(($p->[0] + $r->[0]) / 2),
  31. int(($p->[1] + $r->[1]) / 2),
  32. ];
  33. $img->setpixel(
  34. x => $h->[0],
  35. y => $h->[1],
  36. color => $color,
  37. );
  38. $r = $h;
  39. }
  40. $img->write(file => 'chaos_game_tetrahedron.png');