Zigzag
Zigzag
This question involves reasoning about the code from the GridWorld case study. A copy of the
code is provided as part of the exam.
Consider defining a new type of bug called ZigZagBug, which moves in a zigzag pattern. The
ZigZagBug always faces in a diagonal direction.The first time a ZigZagBug moves, it will move
forward if that location is empty. This is illustrated in the figure below as the move from position 1
to position 2. The bug will then turn 90 degrees to the left. In each subsequent move, the
ZigZagBug will attempt to move forward , and then turn 90 degrees in the opposite direction of
its previous turn (the second move will forward with a right turn, the third move will forward with
a left turn, and so on). If the ZigZagBug is unable to move, it stays in the same location but
reverses its direction. After reversing its direction, the next time the ZigZagBug moves, it will
attempt to turn in the same direction as it tried before reversing. The diagrams below show the path
followed by a single ZigZagBug object as a result of multiple moves.
1 3
Now consider 2 4 what happens when the ZigZagBug attempts to
move forward from position 4. This move is blocked, and
consequently the ZigZagBug stays in the same location but reverses
its direction. This is illustrated as position 5 in the diagram below.
From position 5, the ZigZagBug moves forward and turns right, and from position 6, it moves
forward to position 7 and turns left.
7 5
8 6
The ZigZagBug class is defined by extending the Bug class and overriding the move, and the
turn methods. Because a ZigZagBug alternates its pattern of movement, a private instance
variable turnRight keeps track of the direction of the next movement.
public ZigZagBug()
{
turnRight=false;
}
(b) Override the canMove method for the ZigZagBug class. This method returns true if the
ZigZagFish can move into an empty location or a location with a flower along the appropriate
diagonal indicated by the turnRight variable, and false when it cannot.
(c) Override the turn method for the ZigZagBug class. This method reverses the direction of
the ZigZagBug without changing its location.