langton_s_ant_gd.pl 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 = 1920;
  13. my $height = 1080;
  14. my $line = 10; # line length
  15. my $size = 100; # pattern size
  16. my $turn_left_color = 'red';
  17. my $turn_right_color = 'black';
  18. my $img_file = '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[$_] = [] }
  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 or die "$img_file: $!";
  56. print {$fh} $p->png;
  57. close $fh;