langton_s_ant_2.sf 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/ruby
  2. # Sidef implementation of Langton's Ant
  3. # Translation of: https://rosettacode.org/wiki/Langton%27s_ant#Perl
  4. # Using screen coordinates - 0,0 in upper-left, +X right, +Y down -
  5. # these directions (right, up, left, down) are counterclockwise
  6. # so advance through the array to turn left, retreat to turn right
  7. var dirs = [[1,0], [0,-1], [-1,0], [0,1]];
  8. var size = 15;
  9. # we treat any false as white and true as black, so undef is fine for initial all-white grid
  10. var plane = [];
  11. for (0 .. size-1) {|i| plane[i] = [] };
  12. # start out in approximate middle
  13. var (x, y) = (size/2, size/2);
  14. # pointing in a random direction
  15. var dir = dirs.len.rand.int;
  16. var move;
  17. for (move = 0; (x >= 0) && (x < $size) && (y >= 0) && (y < size); move++) {
  18. # toggle cell's value (white->black or black->white)
  19. if (plane[x][y] = (1 - (plane[x][y] := 0))) {
  20. # if it's now true (black), then it was white, so turn right
  21. dir = ((dir - 1) % dirs.len);
  22. } else {
  23. # otherwise it was black, so turn left
  24. dir = ((dir + 1) % dirs.len);
  25. }
  26. x += dirs[dir][0];
  27. y += dirs[dir][1];
  28. }
  29. {
  30. "Out of bounds after %d moves at (%d, %d)\n".printf(move, x, y);
  31. for (var y=0; y < size; y++) {
  32. for (var x=0; x < size; x++) {
  33. print (plane[x][y] := 0 == 1 ? '#' : '.');
  34. }
  35. print "\n";
  36. }
  37. }.run;