BFOIT - Introduction to Computer Programming

TurtleInGridLand Solution

I picked this little bug-finding exercise because it is similar to other programs in the predicates lesson and has a *trick* solution.

The most obvious way to go about coding the moveForwardCell procedure is to compute the coordinates of the turtle's location if it is moved forward and check to see if this point is in the grid.  The turtle's heading determines which coordinate (X or Y) needs to be changed and how the coordinate is adjusted.

As examples, if the turtle is heading east, the turtle's X coordinate needs to be increased by the size of a cell.  If the turtle is heading south, its Y coordinate need decreased by the size of a cell.  The adjusted coordinate can then be input to gridContainsXY? to determine if the new location is within the bounds of the grid.

So here is part of one solution.

   to moveForwardCell
     if equal? heading east ~
        [if gridContainsXY? (sum xcor gridCellSize) ycor [forward gridCellSize]]
     if equal? heading south ~
        [if gridContainsXY? xcor (difference ycor gridCellSize) [forward gridCellSize]]   
     ...
     end

We could also have used the AND operator in a similar solution.

   to moveForwardCell
     if and (equal? heading east) (gridContainsXY? (sum xcor gridCellSize) ycor) ~
        [forward gridCellSize]
     if and (equal? heading south) (gridContainsXY? xcor (difference ycor gridCellSize)) ~   
        [forward gridCellSize]
     ...
     end

But, as promised, there is a trick you can use to simplify the procedure.  Checkout this code.

   to moveForwardCell
     hideturtle
     forward gridCellSize
     if not gridContainsPos? pos [back gridCellSize]
     showturtle
     end

The trick is to make the turtle disappear, get it to put on its Cloak of Invisibility for a moment.  It then moves forward the size of a cell and we check this position to see if it is in the grid.  If not, we move the turtle back the size of a cell.  Finally, we bring the turtle back into view.  Neat huh?

Public Domain Mark
This work (BFOIT: Introduction to Computer Programming, by Guy M. Haas),
identified by Berkeley Foundation for Opportunities in IT (BFOIT),
is free of known copyright restrictions.