Background
jLogo Programming
- Commanding a Turtle
- Pseudocode
- Adding New Commands
- Iteration & Animation
- Hierarchical Structure
- Procedure Inputs
- Operators & Expressions
- Defining Operators
- Words & Sentences
- User Interface Events
- What If? (Predicates)
- Recursion
- Local Variables
- Global Variables
- Word/Sentence Iteration
- Mastermind Project
- Turtles As Actors
- Arrays
- File Input/Output
Java
- A Java Program
- What's a Class?
- Extending Existing Classes
- Types
- Turtle Graphics
- Control Flow
- User Interface Events
Appendices
- Jargon
- What Is TG?
- TG Directives
- jLogo Primitives
- TG Editor
- Java Tables
- Example Programs
- *** New ***:
Installation Notes
Updates
- December 13, 2008
- January 6, 2012
- March 15, 2013
- January 20, 2014
- February 13, 2014
- July 29, 2014
- January 18, 2016
- January 29, 2016
- August 19, 2016
Lastly
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.
|
We could also have used the AND operator in a similar solution.
|
But, as promised, there is a trick you can use to simplify the procedure. Checkout this code.
|
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?