anon
anon

Reputation: 83

How to get Karel to put beepers everywhere?

This is the code that I tried.

function main() {
  while (frontIsClear()) {
    //this tells karel to go and put beepers
    putBeeper();
    move();
  }
  if (frontIsBlocked()) {
    //this tells karel to change the direction if there's a wall
    if (facingEast()) {
      turnLeft();
      putBeeper();
      if (frontIsClear()) {
        //and this brings karel to the upper street
        move();
        turnLeft();
      } else {
        turnRight();
      }
    }
    if (facingWest()) {
      turnRight();
      putBeeper();
      if (frontIsClear()) {
        move();
        turnRight();
      } else {
        turnRight();
      }
    }
  }
}

When I run the code it gives me an error. It says ReferenceError: virtualDirection is not defined. Pls help. Thanks.

This is the goal. This is the Karel website.

Upvotes: 1

Views: 3292

Answers (2)

anon
anon

Reputation: 83

I changed it a bit. Here's the code that works in both even and odd numbered grids.

function main(){
   while (leftIsClear()){
      putBeeperRow();
      turnForCleanLeftRow();
      putBeeperRow();
      turnForCleanRightRow();
   }
   putBeeperRow();
}
function turnForCleanLeftRow(){
   turnLeft();
   move();
   turnLeft();
}
function turnForCleanRightRow(){
   turnRight();
   if (frontIsClear()){
      move();
      turnRight();
} else {
   turnRight();
   while (frontIsClear()){
      move();
   }
   pickBeeper();
  }
}
function putBeeperRow(){
   while(frontIsClear()){
      putBeeper();
      move();
   }
   putBeeper();
}

Upvotes: 1

Shan S
Shan S

Reputation: 678

The problem with that code is that facingWest() and facingEast() don't seem to be functions. Instead, they're properties, so use facingEast and facingWest (i.e. use them without brackets). That gets rid of the error but facingEast and facingWest are never true based on my testing, which means you can't make it turn based on that.

So, I think you'll have to write some code that doesn't rely on the facing commands. As long as you can assume that Karel starts at the bottom left of a grid, you can just turn when the front is blocked, starting left and then alternating to right. Something like this should work, you'll just have to edit this to make sure it doesn't tell you front is blocked at the end of traversing an even-numbered grid.

function main(){
   while (leftIsClear()){
      putBeeperRow();
      turnForClearLeftRow();
      putBeeperRow();
      turnForClearRightRow();      
   }
   putBeeperRow();
}

function turnForClearLeftRow() {
   turnLeft();
   move();
   turnLeft();
}

function turnForClearRightRow() {
   turnRight();
   move();
   turnRight();
}

function putBeeperRow() {
   while(frontIsClear()){ 
      putBeeper();
      move();
   }
   putBeeper();
}

Upvotes: 1

Related Questions