// CSE 142, Autumn 2009, Marty Stepp // A Snake moves in a "slithering" pattern, where he goes // E, S, WW, S, EEE, S, WWWW, S, EEEEE, S, WWWWWW, S, ... public class Snake extends Critter { private int moves; // total moves he has made private int eastWestLength; // number of total squares to walk W or E private int eastWestMoves; // # moves he has currently walked W or E public Snake() { moves = 0; eastWestLength = 1; eastWestMoves = 0; } public Direction getMove() { moves++; if (eastWestLength % 2 == 1 && eastWestMoves < eastWestLength) { // he has changed W/E an even number of times (so EAST), // and he has not walked that way enough times yet; // so keep going east eastWestMoves++; return Direction.EAST; } else if (eastWestLength % 2 == 0 && eastWestMoves < eastWestLength) { // he has changed W/E an odd number of times (so WEST), // and he has not walked that way enough times yet; // so keep going west eastWestMoves++; return Direction.WEST; } else { // he has reached the end; go south, and change field values // so that he will start over a new east/west walk next time // that is 1 move longer in total length eastWestLength++; eastWestMoves = 0; return Direction.SOUTH; } } public String toString() { return "S"; } }