// Example from lyn's conditional lecture (Lec #6), June 23, 2003 // From lecture 8: More Conditionals // [lyn, 9/28/07] Adapted for revised BuggleWorld for use in Fall'07 Lec. #9 import java.awt.*; public class SnakeWorld extends BuggleWorld { public void run () { SnakeBuggle sandra = new SnakeBuggle(); sandra.tick128(); } public static void main (String[] args) { runAsApplication(new SnakeWorld(), "SnakeWorld"); } } // A buggle that covers rows alternating from left to right // and right to left. This pattern is known as "boustrophendon", // defined in the OED as "(Written) alternately from right to left // and from left to right, like the course of the plough in successive // furrows; as in various ancient inscriptions in Greek and other // languages. Hence boustrophedonic a." class SnakeBuggle extends TickBuggle { public void tick(){ snakeStep(); } public void snakeStep () { if (isFacingUpperRightCorner() || isFacingUpperLeftCorner()) { // Do nothing } else if (isFacingEastWall()) { left(); forward(); left(); } else if (isFacingWestWall()) { right(); forward(); right(); } else { forward(); } } public boolean isFacingUpperRightCorner() { return isFacingEastWall() && isWallToLeft(); } public boolean isFacingUpperLeftCorner() { return isFacingWestWall() && isWallToRight(); } public boolean isFacingEastWall() { return isFacingWall() && (getHeading() == Direction.EAST); } public boolean isFacingWestWall() { return isFacingWall() && (getHeading() == Direction.WEST); } // Returns true if there is a wall to the right, and false otherwise. // The position and heading of the buggle are invariant. public boolean isWallToRight() { right(); boolean result = isFacingWall(); left(); return result; } // Returns true if there is a wall to the left, and false otherwise. // The position and heading of the buggle are invariant. public boolean isWallToLeft() { left(); boolean result = isFacingWall(); right(); return result; } // An alternative, more effcient version of snakeStep(): // it performs fewer buggle operations. But it is also // more difficult to understand. // Unless efficiency is paramount, we recommend that you write // methods in a clearer style that makes liberal use of abstractions. public void snakeStepEfficient () { if (isFacingWall()) { if (getHeading() == Direction.EAST) { left(); if (isFacingWall()) { right(); } else { forward(); left(); } } else { // if (getHeading() == Direction.WEST) right(); if (isFacingWall()) { left(); } else { forward(); right(); } } } else { forward(); } } }