// CSE 142, Marty Stepp // // A Snake moves in a lengthening horizontal "slither" pattern: // E, S, WW, S, EEE, S, WWWW, S, EEEEE, S, ... // // We did this example in lecture to practice figuring out what state // is needed to implement a particular complex movement pattern. public class Snake extends Critter { private boolean west; // am I going west right now? private int moves; // how many moves have I made in current direction? private int layer; // which E/W pass am I on? public Snake() { west = false; // initially going east, not west moves = 0; layer = 1; // will walk a total of 1 move east, at first } // Implements the slithering pattern of movement. // E, S, WW, S, EEE, S, WWWW, S, EEEEE, S, ... public Direction getMove() { if (moves < layer) { // I still need to go sideways more moves++; if (west) { return Direction.WEST; } else { return Direction.EAST; } } else { // I am done walking sideways; // go down, reset moves, and increase slither walk length west = !west; moves = 1; layer++; return Direction.SOUTH; } } public String toString() { return "S"; } }