Unit 2

GridWorld Summer 2007

► Unit 2 ---- Special Bugs
Unit 2 ---- Special Bugs
To the teacher
In Part 2 of GridWorld, the Bug and BoxBug code will be “opened” and
modified to create specialized bugs. Students can develop a basic
understanding of inheritance by extending an existing class. New bugs
will be created by overriding the act() method using the methods
specified in the Bug class. New methods are not defined. The
exercises are targeted to help students understand inheritance as they
strengthen their understanding of problem specification and algorithm
development.
Objectives
Materials in this chapter can reinforce the following concepts:
1. Use of instance variables
2. Extending another class
3. Overriding methods
4. Understanding the relationship of superclass and subclass
5. Using parameters effectively
6. Creating a runner or driver class to execute your own class
7. Using overloaded methods (in the runner)
8. Understanding the function of constructors
9. Developing algorithms to meet different specifications
10. Use of arrays
To the Student
We will explore the powerful notion of inheritance. We, as humans,
inherit from our parents but imagine if we inherited everything from one
of our parents; the exact looks and actions. (ooh…my poor children!) In
Java, a class that extends another does inherit everything from that
class.
We must first understand the relationship between a superclass and a
subclass. We know from Unit 1 that Bug, Flower and Rock are Actors.
These three classes extended the Actor class and so these
subclasses inherited all the instance variables and methods from Actor.
So now we ask: Why did the bug act differently than the rock or the
flower?
The act method was invoked when we clicked Step. Let us look at the
act() method for the rock. There is no code thus there were no
instructions for the rock. What about the act() method for the flower
and the act() method for the bug?
Each of the classes, Rock, Flower and Bug, inherits everything from
the superclass Actor and overrides the act() method to create its own
behavior in the simulation. The Bug class provides three additional
methods that specify how a bug moves and turns. Overriding the act
method using these specific methods creates a “special “ Actor. In this
unit we will create classes that extend the Bug class. Various
behaviors will be created by overriding the act() method using only the
methods specified in the Bug class.
For any Java program we must have a class that starts the program;
for Java applications the”driver class” uses the “public static void
main(String[] args)” method. In this case study we call the driver
classes “Runner” as in “BugRunner” and “BoxBugRunner.” Whenever
you want to run the GridWorld with a new class that extends Bug (or
Actor), you will need to write a new runner class. You can simply follow
the pattern of the BugRunner and BoxBugRunner classes. You can
add an instance of an actor to your simulation using the ActorWorld
add method, as shown in the example runner classes.
Assignments
Read Part 2 of the GridWorld manual. Complete “Do You Know” and
Exercises at the end of this part. Then try the additional "Directed
Observations
Directed Observations
1. Which class did your CircleBug extend?
2. The path of a CircleBug is an octagon but the code given below
needs debugging. Correct the errors:
public class CircleBug extends BugRunner
{
private int steps;
private int sideLength;
public CircleBug(int len)
{
sideLength = 0;
steps = 1;
}
public void act()
{
if ( steps< sideLength() || canMove() )
{
move();
}
else
{
turn();
steps = 0;
}
}
}
3. Create a method called leftTurn() that turns left 45 degrees
using only the methods defined in the bug class.
4. Did you increment sideLength in your code for SpiralBug? Why?
5. What line of code must you include in SpiralBugRunner to place
an instance of SpiralBug location (3, 8)?
6. Given the following code for ZBug:
public class ZBug extends Bug
{
private int steps;
private int sideLength;
private int side;
private static final int MAXSIDES = 3;
/**
* @param length the side length
*/
public ZBug(int length)
{
steps = 0;
sideLength = length;
side = 1;
setColor(Color.BLUE);
setDirection(Location.EAST);
}
Explain the bug’s action if the following condition is true:
if (side<= MAXSIDES && getDirection() = = Location.EAST &&
canMove()
7. How would you change your ZBug to an NBug?
8. How would you create an &Bug? Write specifications and
algorithm.
9. In writing code for DancingBug where and why would it be
appropriate to call super.act()?
10. Create one programming exercise and three multiple choice
questions for Unit 2.
Additional Exercises
1. Define a class SmartBug that extends Bug and acts as follows: If a smart
bug can move straight ahead, it does, otherwise it turns until it is facing an
open cell (all in one step). If there is no open cell adjacent to the smart bug,
then it remains in its original position (location and direction).
Variation: Define SmartBug2 so that it first turns until it is facing an open
cell, then moves into that cell (all in one step).
2. Define a class DruggedBug that extends Bug and acts as follows: a druggie
bug turns a random number of times between 0 and 7, then moves forward if
it can.
3. Define a class FigureEightBug that extends CircleBug. If there are no
obstacles, a figure-eight bug will move in a figure-eight pattern as shown
below. If it is blocked from moving, it turns right or left 45 degrees and starts
a new side. You can do this by overriding the turn() method in CircleBug and
not the act() method.

► Unit 2 forum
► Figure8Bug
Figure8Bug
by Leslie McLane - Monday, 16 July 2007, 10:02 AM
To implement a Figure8Bug that extends CircleBug, I had to add
accessor and modifier methods to my CircleBug class for access
to the two instance variables introduced in that class -- steps (the
number of steps a bug has taken along the current side) and
sideLength (the side length parameter for a given CircleBug).
The Figure8Bug problem description references a need to
override the turn() method, which I did, but makes no reference
to the need for accessor and modifier methods. Did I
overcomplicate the requirement??
Re: Figure8Bug
by Leslie McLane - Tuesday, 24 July 2007, 04:49 PM
Thought I'd ask again -- Did anyone implement a solution for
Figure8Bug that did not require accessor and modifier methods
be added to CircleBug? I overrode turn(), not act(), as
the requirements stated, but I could not develop a solution
without accessor methods for steps and stepLength for turn()
logic and a modifier method for steps for when the Bug
encounters an obstacle and needs to start a new side.
The "To the teacher" unit intro says "no new methods are
defined" for new bugs created by extending other bugs, but
maybe this only applies to new bugs that extend Bug?
Figure8Bug is one of the additional exercises, extending
CircleBug, not Bug...
Perspective would be appreciated.
Re: Figure8Bug
by Chris Nevison - Wednesday, 25 July 2007, 08:19 AM
Think about adding a new counter instance variable to your
Figure8Bug that is adjusted by your overridden turn method.
C&B
Re: Figure8Bug
by Leslie McLane - Wednesday, 25 July 2007, 05:04 PM
Thank you for the feedback. I will put my thinking cap on, but at first
glance I don't see why I would not want to capitalize on CircleBug's steps
field, incrementing and comparing to sideLength, as I did in CircleBug, to
determine when to turn (barring any obstacles) and possibly restart a
figure. This is my current code. Can you provide some feedback on my
solution as a whole while I work on your suggestion? Thanks in advance.
See code below:
private static int NUMSIDES = 8;
private int sideCount;
private boolean firstCircle;
private int turnDirection;
/**
* Constructs a Figure8Bug bug that traces a figure eight of a given
side length
*/
public Figure8Bug(int length)
{
super(length);
setSideCount(1);
turnDirection = Location.HALF_RIGHT;
firstCircle = true;
}
/**
* Moves to the next location of the figure.
*/
public void turn()
{
// tests for complete circle AND ensures figure 8 keeps same
orientation in the grid
// if getDirection() condition removed, figure 8 orientation changes in
the grid
if ( (getSteps() == getSideLength()) && (getDirection() ==
Location.NORTH ) && (sideCount > NUMSIDES) )
{
if (firstCircle)
{
turnDirection = Location.HALF_LEFT;
firstCircle = false;
}
else
{
turnDirection = Location.HALF_RIGHT;
firstCircle = true;
}
setSideCount(1);
}
// turn, and check for obstacles
setDirection(getDirection() + turnDirection);
while (!canMove())
setDirection(getDirection() + turnDirection);
// reset steps and increment sideCount
setSteps(0);
setSideCount(getSideCount() + 1);
}
// get current sideCount
public int getSideCount()
{
return sideCount;
}
// reset/increment sideCount
public void setSideCount(int val)
{
sideCount = val;
}
}
Re: Figure8Bug
by Leslie McLane - Wednesday, 25 July 2007, 05:37 PM
FYI - my e-mails rarely come in singles, by the way... I always
think of something else after clicking <send>...
I neglected to mention that I do have a new counter variable,
sideCount, that is adjusted by my overridden turn() method. But
it works in concert with steps... help...
Re: Figure8Bug
by Sam Koski - Friday, 17 August 2007, 05:31 AM
Leslie,
I did FigureEightBug by keeping count of the number of turns.
Since a Circle is really an octogon I knew that I had to make a
change every 8 turns.
Here are my changes. (Note that I am using the act method from
the super class CircleBug, so that there is no visible code in my
class for
act. When act calls turn(), MY turn() is used. my turn() keeps
count of
the total turns and changes the directions appropriatedly.
For the first 8 turns, turn only right.
After 8 turns turn only left.
At 16 turns start over.
In my constructor, I called super(length) so that I
could use the act method from the CircleBug class.
I also set up a boolean variable to keep track of
which way I want to turn. This variable will
change every 8 steps.
I also wrote a helper function turnLeft();
import info.gridworld.actor.Bug;
/**
* A <code>FigureEightBug</code> traces out a figure eigth of a
given size. <br />
*/
public class FigureEightBug extends CircleBug
{
private int turns;
private boolean right;
/**
* Constructs a figureeight bug that traces a figureeight a given
side length
* @param length the side length
*/
public FigureEightBug(int length)
{
super(length);
turns = 0;
right = true;
}
public void turnLeft()
{
for (int i=0; i<7; i++) super.turn();
}
public void turn()
{
turns++;
if (right)
super.turn();
else
turnLeft();
if (turns % 8 == 0) right = !right;
turns = turns % 16;
}
}
Re: Figure8Bug
by Leslie McLane - Friday, 17 August 2007, 08:59 AM
Interesting solution, thank you for sharing Sam. I did eventually
"de-complicate" my solution (below), also counting sides,
comparing the count to a constant vs. %, and keeping all turn
logic in my turn() method versus calls to super.turn(). I like your
calls to super.turn().
import info.gridworld.actor.Bug;
import info.gridworld.grid.Location;
/**
* A Figure8Bug acts draws a Figure8, capitalizing on the
behavior
* of a CircleBug
*/
public class Figure8Bug extends CircleBug
{
private static int NUMSIDES = 8;
private int sideCount;
private int turnDirection;
/**
* Constructs a Figure8Bug bug that traces a figure eight of a
given side length,
*
*/
public Figure8Bug(int length)
{
super(length);
sideCount = 1;
turnDirection = Location.HALF_RIGHT;
}
/**
* Moves to the next location of the figure.
*/
public void turn()
{
// check need to change direction
if ( sideCount > NUMSIDES )
{
if (turnDirection == Location.HALF_LEFT)
turnDirection = Location.HALF_RIGHT;
else
turnDirection = Location.HALF_LEFT;
sideCount = 1;
}
// turn
setDirection(getDirection() + turnDirection);
// increment sideCount
sideCount++;
}
}
► Question 6 on Quiz
Question 6 on Quiz
by Sam Koski - Friday, 17 August 2007, 05:11 AM
I don't agree with the answer for question 6.
The samples are all coded like:
world.add(new Location(7, 8), alice);
The supposed answer doesn't compile on my computer, because
the constructor needs a LOCATION and not two integers.
world.add(1,3,chris);
Re: Question 6 on Quiz
by Leslie McLane - Friday, 17 August 2007, 08:31 AM
Choices c and d do supply a location argument. Choice d
references the correct location coorindates for chris, and is the
stated answer if I recall correctly. No?
Leslie

► Change size of BoundedGrid
Change size of BoundedGrid
by Sharon Woodbridge - Tuesday, 17 July 2007, 06:58 AM
Is there any way to change the size of the BoundedGrid. I tried
changing the values for rows and columns in the World class but
I get an illegal argument exception when I try to add a bug to that
world. Sharon
Re: Change size of BoundedGrid
by Reg Hahne - Sunday, 22 July 2007, 08:34 PM
Sharon You can change the size of the Bounded Grid 2 ways...
1. Run one of the GridWorld Applications. Under the World menu
option there is a Set grid... option that will allow you to specify the
size of the grid needed. This way will only work for that specific
run.
2. If you're a little more adventurous you can actually change the
size of the grid from its 10 x 10 matrix to any size you wish.
Under the framework folder go the info.gridworld.world. There you
will find World.java. Open it and there are two static final ints
(DEFAULT_ROWS and DEFAULT_COLS). Set them to whatever
size you need and the BoundedGrid will take on that size when
you rerun the program.
Re: Change size of BoundedGrid
by Barbara Cloud - Monday, 23 July 2007, 01:36 PM
Reg's solution 2 only works if you are using the code folder as the
package. Most people will be using the gridworld.jar file and
changing and recompiling the source code will not have any
effect unless you also replace the jar file with a new one with this
change. Solution 1 is the best way to go.
Re: Change size of BoundedGrid
by Leslie McLane - Monday, 23 July 2007, 03:14 PM
I found the following statement on-line while researching the
compilation error I was encountering using the runner class
statements on page 7 of the Solutions Manual to create an
UnboundedGrid world:
"these messages occur when you are using classes that support
the new J2SE 1.5 feature - generics. You get them when you do
not explicitly specify the type of the collection's content."
My error was resolved when I changed the page 7 runner class
statement From
UnboundedGrid grid = new UnboundedGrid<Actor>;
To
UnboundedGrid<Actor> grid = new UnboundedGrid<Actor>;
I have since been able to create BoundedGrid worlds of any
dimension with comparable logic. For example:
BoundedGrid<Actor> gr = new BoundedGrid<Actor>(15,15);
ActorWorld world = new ActorWorld(gr);
Re: Change size of BoundedGrid
by Sam Koski - Friday, 17 August 2007, 05:35 AM
You also have to make sure that your Actor is imported.
import info.gridworld.actor.Actor;
BoundedGrid<Actor> gr = new BoundedGrid<Actor>(15,15);
ActorWorld world = new ActorWorld(gr);
Sam Koski’s Answers for Unit 2:
1.
Which class did your CircleBug extend? Bug
2.
The path of a CircleBug is an octagon but the code given below needs debugging.
Correct the errors:
import info.gridworld.actor.Bug;
import java.awt.Color;
public class CircleBug extends Bug
{
private int steps;
private int sideLength;
public CircleBug(int len)
{
sideLength = len;
steps = 1;
}
public void act()
{
if ( steps< sideLength && canMove() )
{
move();
steps++;
}
else
{
turn();
steps = 0;
}
}
}
}
3. Create a method called leftTurn() that turns left 45 degrees using only the methods
defined in the bug class.
public void leftTurn()
{
for (int i=0; i<8; i++) turn();
}
4.
Did you increment sideLength in your code for SpiralBug? Why?
No, I decremented it because I wanted the spiral to decrease.
5.
What line of code must you include in SpiralBugRunner to place an instance of
SpiralBug location (3, 8)?
SpiralBug spiro = new SpiralBug(8);
world.add(new Location(3,8), spiro);
6.
Given the following code for ZBug:
public class ZBug extends Bug
{
private int steps;
private int sideLength;
private int side;
private static final int MAXSIDES = 3;
/**
* @param length the side length
*/
public ZBug(int length)
{
steps = 0;
sideLength = length;
side = 1;
setColor(Color.BLUE);
setDirection(Location.EAST);
}
Explain the bug’s action if the following condition is true:
if (side<= MAXSIDES && getDirection() = = Location.EAST && canMove()
Bug move one step EAST
7.
How would you change your ZBug to an NBug?
Turn the monitor sideways 
setDirection(0);
8.
How would you create an &Bug? Write specifications and algorithm.
9.
In writing code for DancingBug where and why would it be appropriate to call
super.act()?
After all the dancing call super.act() Last line of act()
10. Create one programming exercise and three multiple choice questions for Unit 2.
Programming Exercise
Create an unbounded grid?
ActorWorld's have several constructors. The default constructor get no
parameter and creates a bounded grid. You can also construct an UnboundedGrid
and send it to the ActorWorld constructor that needs a grid
ActorWorld world = new ActorWorld(new UnboundedGrid());
1. Assume that all support code is written. What happens with the following code?
world.add(new BoxBug(5));
A)
B)
C)
D)
E)
A BoxBug is placed at location (5,5).
A BoxBug is placed in a random location on the grid.
A compile error occurs.
A runtime error occurs since the bug is not added to the grid.
None of these
2. Which of the following are CONSTANTS in the Location class.
A) LEFT B) RIGHT C) HALF_LEFT D)HALF_RIGHT E) All of These
2b. Which of the following are CONSTANTS in the Location class.
A) FULL_CIRCLE B) HALF_CIRCLE C) AHEAD D) SOUTWEST E) All of
These
3. In the Location class, what would the following line accomplish?
adjustedDirection = adjustedDirection % FULL_CIRCLE;
A)
B)
C)
D)
E)
Turns the BUG all the way around
Makes the BUG move in a circle
Reduces the value of the direction so that it lies between 0 and 360
Creates a DancingBug
None of these
Additional Exercises
1. Define a class SmartBug that extends Bug and acts as follows: If a smart bug can move
straight ahead, it does, otherwise it turns until it is facing an open cell (all in one step). If
there is no open cell adjacent to the smart bug, then it remains in its original position
(location and direction).
Variation: Define SmartBug2 so that it first turns until it is facing an open cell, then
moves into that cell (all in one step).
import
import
import
import
import
import
info.gridworld.actor.Bug;
info.gridworld.actor.Rock;
java.awt.Color;
info.gridworld.actor.Bug;
info.gridworld.actor.Rock;
java.awt.Color;
/**
* A <code>SmartBug</code> finds an opening before moving <br />
*/
public class SmartBug extends Bug
{
private int turns;
/**
* Constructs a smart bug that finds an opening before moving
*/
public SmartBug()
{
super();
setColor(Color.MAGENTA);
turns = 0;
}
/**
* Finds an opening then moves to the next location of the square.
*/
public void act()
{
if (canMove())
{
move();
turns = 0;
}
else
{
while(turns<8 && !canMove())
{
turn();
turns++;
}
//Variation 1: comment next line
if (canMove()) move();
turns=0;
}
}
}
2. Define a class DruggedBug that extends Bug and acts as follows: a druggie bug turns a
random number of times between 0 and 7, then moves forward if it can.
import info.gridworld.actor.Bug;
import java.awt.Color;
import java.util.*;
/**
* A <code>DruggedBug</code> turns randomly before each move. <br />
*/
public class DruggedBug extends Bug
{
int turn;
Random r;
/**
* Constructs a drugged bug that turns randomly
*/
public DruggedBug()
{
turn = 0;
setColor(Color.YELLOW);
r = new Random();
}
/**
* Turns randomly then Moves to the next location of the square.
*/
public void act()
{
for(int i=0; i<r.nextInt(8); i++)
{
turn();
}
super.act();
}
}
3. Define a class FigureEightBug that extends CircleBug. If there are no obstacles, a
figure-eight bug will move in a figure-eight pattern as shown below. If it is blocked from
moving, it turns right or left 45 degrees and starts a new side. You can do this by
overriding the turn() method in CircleBug and not the act() method.
import info.gridworld.actor.Bug;
/**
* A <code>FigureEightBug</code> traces out a figure eigth of a given size. <br />
*/
public class FigureEightBug extends CircleBug
{
private int turns;
private boolean right;
private int sideLength;
/**
* Constructs a figureeight bug that traces a figureeight a given side length
* @param length the side length
*/
public FigureEightBug(int length)
{
super(length);
turns = 0;
right = true;
}
public void turnLeft()
{
for (int i=0; i<7; i++) super.turn();
}
public void turn()
{
turns++;
if (right)
super.turn();
else
turnLeft();
if (turns % 8 == 0) right = !right;
turns = turns % 16;
}
}




Resources
► Unit 2 Do You Know answers
Do You Know? (Set 2)
1. What is the role of the instance variable sideLength?
The sideLength instance variable defines the number of steps a
BoxBug moves on each side of its box.
2. What is the role of the instance variable steps?
The steps instance variable keeps track of how many steps a
BoxBug has moved on the current side of its box.
3. Why is the turn method called twice when steps becomes equal
to sideLength?
When a BoxBug travels sideLength steps, it has to turn 90 degrees
to travel along the next side of its box. The turn method only
executes a 45 degree turn; therefore it takes two turn method calls
to turn 90 degrees.
4. Why can the move method be called in the BoxBug class when
there is no move method in the BoxBug code?
The BoxBug class extends the Bug class and the Bug class has a
public move method. Since the BoxBug class is a subclass of the Bug
class, it inherits the move method from the Bug class.
5. After a BoxBug is constructed, will the size of its square pattern
always be the same? Why or why not?
Yes. When a BoxBug is constructed, the side length is determined
and cannot be changed by client code.
6. Can the path a BoxBug travels ever change? Why or why not?
Yes. If another Actor, like a Rock or Bug, is in front of a BoxBug
when it tries to move, the BoxBug will turn and start a new box
path.
7. When will the value of steps be set to zero?
Initially, the value of steps is set to zero when a BoxBug is
constructed. After that, the value of steps will be set to zero when
steps is equal to sideLength - meaning the BoxBug has completed
one side of its box path, or when the BoxBug cannot move and
turns instead to start a new box path.
Exercises (Page 12)
1. Write a new class CircleBug that is identical to BoxBug, except
that in the act method the turn method is called once instead of
twice. How is its behavior different from a BoxBug?
import info.gridworld.actor.Bug;
public class CircleBug extends Bug
{
private int steps;
private int sideLength;
public CircleBug(int n)
{
sideLength = n;
}
public void act()
{
if (steps < sideLength && canMove())
{
move();
steps++;
}
else
{
turn();
steps = 0;
}
}
}
The path of a CircleBug is an octagon, instead of a square.
2. Write a new class SpiralBug that extends Bug. The bug should
drop flowers in a spiral pattern. Hint: Imitate BoxBug, but adjust
the side length when the bug turns. You may want to use an
UnboundedGrid to see the spiral pattern more clearly.
Note: You can change the grid to Unbounded by using the
dropdown menu.
import info.gridworld.actor.Bug;
public class SpiralBug extends Bug
{
private int sideLength;
private int steps;
public SpiralBug(int n)
{
sideLength = n;
steps = 0;
}
public void act()
{
if (steps < sideLength && canMove())
{
move();
steps++;
}
else
{
turn();
turn();
steps = 0;
//Each time a SpiralBug turns, increase the sideLength by
one
sideLength++;
}
}
}
If you want to include SpiralBugRunner because of the Unbounded
Grid this is a suggestion:
import info.gridworld.actor.Actor;
import info.gridworld.grid.UnboundedGrid;
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
public class SpiralBugRunner
{
public static void main(String[] args)
{
UnboundedGrid grid = new UnboundedGrid<Actor>();
ActorWorld world = new ActorWorld(grid);
SpiralBug sp = new SpiralBug(3);
world.add(new Location(3,5),sp);
world.show();
}
}
3. Write a class ZBug to implement bugs that move in a “Z” pattern,
starting in the top left corner. After completing one “Z” pattern, a
ZBug should stop moving. Supply the length of the “Z” as a
parameter in the constructor. The following image shows a “Z”
pattern of length 4. Hint: Notice that a ZBug needs to be facing east
before beginning its "Z" pattern.
import info.gridworld.actor.Bug;
import info.gridworld.grid.Location;
public class ZBug extends Bug
{
private int steps;
private int sideLength;
private int side; //which side of the Z the ZBug is on
public ZBug(int length)
{
turn();
turn();
steps = 0;
side = 0;
sideLength = length;
}
public void act()
{
if (side < 3 && steps < sideLength && canMove())
{
move();
steps++;
}
else if (side == 0)
{
turn();
turn();
turn();
steps = 0;
side++;
}
else if (side == 1)
{
for( int k=0; k<5; k++)
turn();
steps = 0;
side++;
}
else if(side == 2)
{
side++;
}
}
Or this solution below but not so good for A students at
this time.
import info.gridworld.actor.Bug;
import java.awt.Color;
import info.gridworld.grid.Location;
public class ZBug extends Bug
{
private int steps;
private int sideLength;
private int side;
private static final int MAXSIDES = 3;
public ZBug(int length)
{
steps = 0;
sideLength = length;
side = 1;
setColor(Color.BLUE);
setDirection(Location.EAST);
}
public void act()
{
if (side <= MAXSIDES && steps < sideLength && canMove())
{
move();
steps++;
}
else if (side < MAXSIDES && getDirection()==
Location.EAST && canMove())
{
setDirection(Location.SOUTHWEST);
steps = 0;
side++;
}
else if (canMove())
{
setDirection(Location.EAST);
steps = 0;
side++;
}
}
}
4. Write a class DancingBug that dances by making different turns
before each move. The DancingBug constructor has an integer
array as a parameter. the integer entries in the array represent
how many times the bug turns before it moves. For example, if an
array entry is 5, the bug would turn a total 225 degrees (recall one
turn is 45 degrees). When a DancingBug acts, it should turn the
number of times given by the current entry in its array, then act
like a Bug. In the next move it should use the next array entry.
After carrying out the last turn in the array it should start again
with the initial array value so that the dancing bug continually
repeats the same turning pattern. The DancingBugRunner class
should create an array and pass it as a parameter to the
DancingBug constructor.
import info.gridworld.actor.Bug;
public class DancingBug extends Bug
{
private int[] turnList;
private int currentStep;
public DancingBug(int[] turns)
{
turnList = turns;
currentStep = 0;
}
public void multiTurn(int times)
{
for(int j = 1; j <= times; j++)
{
turn();
}
}
public void act()
{
if(currentStep == turnList.length)
currentStep = 0;
multiTurn (turnList[currentStep]);
currentStep++;
super.act();
}
}
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
public class DancingBugRunner
{
public static void main(String[] args)
{
ActorWorld world = new ActorWorld();
int[] turns = {3,2,1,3};
DancingBug dancer = new DancingBug(turns);
dancer.setColor(Color.ORANGE);
world.add(new Location(9, 9), dancer);
world.show();
}
}
5. Study the code for the BoxBugRunner class. Summarize the steps
you would use to add another BoxBug actor to the grid.
1. Create a BoxBug object with its sideLength
2. Add this instance of BoxBug to the world at a random or a
specific location.