random_langton_s_ant.pl 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # License: GPLv3
  4. # Date: 15 December 2013
  5. # Website: https://trizenx.blgospot.com
  6. # Variation of: https://rosettacode.org/wiki/Langton%27s_ant#Perl
  7. # More info about Langton's ant: https://en.wikipedia.org/wiki/Langton%27s_ant
  8. use 5.010;
  9. use strict;
  10. use warnings;
  11. use GD::Simple;
  12. my $width = 12480;
  13. my $height = 7020;
  14. my $line = 10; # line length
  15. my $size = 1000; # pattern size
  16. my $turn_left_color = 'red';
  17. my $turn_right_color = 'black';
  18. my $img_file = 'random_langton_s_ant.png';
  19. my $p = GD::Simple->new($width, $height);
  20. $p->moveTo($width / 2, $height / 2);
  21. # Using screen coordinates - 0,0 in upper-left, +X right, +Y down -
  22. # these directions (right, up, left, down) are counterclockwise
  23. # so advance through the array to turn left, retreat to turn right
  24. my @dirs = ([1, 0], [0, -1], [-1, 0], [0, 1]);
  25. # we treat any false as white and true as black, so undef is fine for initial all-white grid
  26. my @plane;
  27. for (0 .. $size - 1) { $plane[$_] = [(map {int(rand(2))} 1..rand(100)) x rand(100)] }
  28. # start out in approximate middle
  29. my ($x, $y) = ($size / 2, $size / 2);
  30. # pointing in a random direction
  31. my $dir = int rand @dirs;
  32. # turn in a random direction
  33. $p->turn(90 * $dir);
  34. my $move;
  35. for ($move = 0 ; $x >= 0 && $x < $size && $y >= 0 && $y < $size ; $move++) {
  36. # toggle cell's value (white->black or black->white)
  37. if ($plane[$x][$y] = 1 - ($plane[$x][$y] ||= 0)) {
  38. # if it's now true (black), then it was white, so turn right
  39. $p->fgcolor($turn_right_color);
  40. $p->line($line);
  41. # for more interesting patterns, try multiplying 90 with $dir
  42. $p->turn(90);
  43. $dir = ($dir - 1) % @dirs;
  44. }
  45. else {
  46. # otherwise it was black, so turn left
  47. $p->fgcolor($turn_left_color);
  48. $p->line($line);
  49. $p->turn(-90);
  50. $dir = ($dir + 1) % @dirs;
  51. }
  52. $x += $dirs[$dir][0];
  53. $y += $dirs[$dir][1];
  54. }
  55. open my $fh, '>', $img_file
  56. or die "$img_file: $!";
  57. print {$fh} $p->png;
  58. close $fh;