Advertisement
Guest User

Accidental Solution to Bit's Quest #10 and #12

a guest
Jul 8th, 2013
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * Boilerplate Code. Here we assign a numerical index to each direction for
  3.  * sensors and thrusters. We also have all sensor events call the "sense"
  4.  * method so we can handle them all generically.
  5.  */
  6.  
  7. var $this = this;
  8. var directions = ["right", "bottom", "left", "top"];
  9. var sensors   = [];
  10. var thrusters = [];
  11.  
  12. for (var _i = 0; _i < 4; ++_i)
  13.   (function() {
  14.     var i = _i;
  15.     this.on('sensor:' + directions[_i], function(c)
  16.     {
  17.       sensors[i] = c;
  18.       sense.call(this, i);
  19.     });
  20.    
  21.     sensors[i] = false;
  22.     thrusters[i] = this.thrusters[directions[i]];
  23.   }).call(this);
  24.  
  25.  
  26. /*
  27.  * First we move to a wall: Our algorithm only knows how to follow walls to
  28.  * the solution, and it expects to start against a wall, with no thrusters
  29.  * running.
  30.  */
  31.  
  32. this.on('start', function() {
  33.   this.thrusters.right(true);
  34.  
  35.   var initialized = false;
  36.   this.on('sensor:left', function() {
  37.     if (!initialized)
  38.     {
  39.       initialized = true;
  40.       this.thrusters.right(false);
  41.     }
  42.   });
  43. });
  44.  
  45.  
  46. /*
  47.  * We either found a new wall, or a wall is no longer next to us. For each
  48.  * wall we're next to, turn on the thruster clockwise to that wall. If we are
  49.  * no longer next to a wall, go towards the last disappeared wall.
  50.  */
  51.  
  52. function sense(i) {  
  53.   var anySensors = false;
  54.   for (j in sensors)
  55.     anySensors = anySensors || sensors[j];
  56.  
  57.   // A new direction to unexplored area just opened up, go to it
  58.   if (! anySensors)
  59.     thrusters[(i+2)%4](true);
  60.  
  61.   // Turn on a thruster clockwise from the wall we just encountered
  62.   // Or, turn it off if there is no wall anymore.
  63.   thrusters[(i+3)%4](sensors[i]);
  64. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement