Reflex agent

Initialization

None :-)

Agent code

if(!this.breeze() && !this.stench()) {
  this.go(this.adjacent().random());
} else {
  this.stepback();
}

Model-based reflex agent

Initialization

nopit    = set();
nowumpus = set();

Agent code

if(!this.stench()) {
  this.adjacent().each(function(square) {
    nowumpus.add(square);
  });
}

if(!this.breeze()) {
  this.adjacent().each(function(square) {
    nopit.add(square);
  });
}

action = this.adjacent().filter(function(square) {
  return nopit.contains(square) && nowumpus.contains(square);
}).random();

if(action) this.go(action);
else this.stepback();

Agent using planning

Initialization

nopit = set();
nowumpus = set();
visited = set();
position = "A0";
visited.add("A0");
nopit.add("A0");
nowumpus.add("A0");

stopped = false;

this.search = function(predicate, optPosition) {

  if(optPosition === undefined) optPosition = position;
  
  var fringe = [ optPosition ];
  var cost   = {};
  var level = 0;
  cost[optPosition] = 0;
  
  while(fringe.length > 0) {
    ++level;
    fringe = fringe.flatMap(this.adjacent.bind(this)).filter(function(square) {
      return cost[square] === undefined && nopit.contains(square) && nowumpus.contains(square);
    }).map(function(square) {
      cost[square] = level;
      return square;
    });
    fringe = _.uniq(fringe);
    
    var goals = fringe.filter(predicate.bind(this));
    if(goals.length > 0) {
      var square = goals[0];
      var plan = [];
      while(square != optPosition) {
        plan.push(square);
        square = _.min(this.adjacent(square), function(sq) {
          return cost[sq] === undefined ? Infinity : cost[sq];
        });
      }
      return plan.reverse();
    }
  }
  
  return false;
}

Agent code

if(stopped) return;

if(!this.stench()) {
  this.adjacent().each(function(square) {
    nowumpus.add(square);
  });
}

if(!this.breeze()) {
  this.adjacent().each(function(square) {
    nopit.add(square);
  });
}

var plan = false;
if(!this.gold()) {
  // find path to the closest safe unvisited square
  plan = this.search(function(square) {
    return !visited.contains(square) && nopit.contains(square) && nowumpus.contains(square);
  });
} else {
  // find path to A0
  plan = this.search(function(square) {
    return square === "A0";
  });
}

if(!plan || plan.length == 0) {
  alert("I don't know what to do!");
  stopped = true;
} else {
  position = plan[0];
  this.go(plan[0]);
  visited.add(plan[0]);
}