Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //MyBug.java
- /*
- * MyBug extends Bug, so a MyBug is a Bug.
- * Bug extends Actor, so a MyBug is an Actor also.
- * Note: Rock and Flower classes extend the Actor class too,
- * which is why they can exist all on the same grid of Actor type.
- *
- * Other than the constructor names the code below is the same as in the
- * Bug class itself. Modify the code to change the way your bug behaves.
- *
- */
- import java.awt.Color;
- import info.gridworld.grid.Grid;
- import info.gridworld.grid.Location;
- import info.gridworld.actor.*;
- public class MyBug extends Bug
- {
- public MyBug()
- {
- setColor(Color.BLUE);
- this.setDirection(Location.NORTHWEST);
- }
- /**
- * Constructs a DiagonalBug of a given color.
- * @param bugColor the color for this bug
- */
- public MyBug(Color bugColor)
- {
- setColor(bugColor);
- this.setDirection(Location.NORTHWEST);
- }
- /**
- * Each time through the grid, each Actor object (Bug) is told to act().
- * If the MyBug can move then it moves or else it turns.
- */
- public void act()
- {
- if (canMove())
- move();
- else
- turn();
- }
- /**
- * Turns the bug 45 degrees to the right without changing its location.
- */
- public void turn()
- {
- setDirection(getDirection() + Location.HALF_RIGHT);
- }
- /**
- * Moves the bug forward, putting a flower into the location it previously occupied.
- */
- public void move()
- {
- Grid<Actor> gr = getGrid();
- if (gr == null)
- return;
- Location loc = getLocation();
- Location next = loc.getAdjacentLocation(getDirection());
- if (gr.isValid(next))
- moveTo(next);
- else
- removeSelfFromGrid();
- Flower flower = new Flower(getColor());
- flower.putSelfInGrid(gr, loc);
- }
- /**
- * Tests whether this bug can move forward into a location that is empty or contains a flower.
- * @return true if this bug can move.
- */
- public boolean canMove()
- {
- Grid<Actor> gr = getGrid();
- if (gr == null)
- return false;
- Location loc = getLocation();
- Location next = loc.getAdjacentLocation(getDirection());
- if (!gr.isValid(next))
- return false;
- Actor neighbor = gr.get(next);
- if ((neighbor instanceof Rock))
- {
- neighbor.removeSelfFromGrid();
- return false;
- }
- return (neighbor == null) || (neighbor instanceof Flower);
- // Ok to move into empty location or onto flower
- // but not Ok to move onto any other actor
- public void breed()
- {
- Grid<Actor> gr = getGrid();
- if (gr == null)
- return;
- Location loc = getLocation();
- Location next = loc.getAdjacentLocation(loc.EAST);
- if (!gr.usValid(next))
- {
- next = loc.getAdjacentLocation(loc.WEST);
- if (!gr.isValid(next))
- return;
- }
- Actor neighbor = gr.get(next);
- if (neighbor == null || neighbor instanceof Flower || neighbor instanceof Rock)
- {
- MyBug babyBuggy = new MyBig();
- babyBuggy.putSelfInGrid(gr, next);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement