Custom Actor World That Reports The Furthest Bug

<< Make Custom Pictures For Gridworld Actors | GridworldTrailIndex | Coin and PurseWorld >>

Watch a working demonstration

Here is a customized World for Gridworld where the message on the top is updated to show how many bugs there are and the location of the furthest Bug in the grid. You need to implement the Comparator interface for the grid world Bug class. You need to define a compare method that returns an int. Get the location of each Bug and use the compareTo method of Location. Here is the starter code:

BugComparator.java

import info.gridworld.actor.*;
import java.util.Comparator;
/**
 * Bug Comparator is used so an ArrayList of Bugs can sorted
 * by the Loaction.  It uses the getLocation() method of the
 * two different bugs.  Lucky for us, the Location class implements
 * the Comparable interface, so we can use the Loaction's compareTo() method!
 */
public class BugComparator implements Comparator<Bug>
{
	//your code here
}

FarthestBugWorld.java

import java.awt.Color;
import java.util.ArrayList;
import info.gridworld.actor.*;
import info.gridworld.grid.*;
import java.util.Collections;
public class FarthestBugWorld extends ActorWorld
{

    public FarthestBugWorld(int rows, int cols, int numberOfBugs){
        super();
        this.setGrid(new BoundedGrid<Actor>(rows,cols));
        if (numberOfBugs<1)
             numberOfBugs=1;
        for (int i=0; i<numberOfBugs; i++)
             this.add(new Bug() );
        updateMessage();
    }
    public void step()
    {
        super.step();
        updateMessage();
    }
    public void updateMessage()
    {
        ArrayList<Location> locs= getGrid().getOccupiedLocations();
        ArrayList<Bug> bugs=new ArrayList<Bug>();
        for (Location loc: locs){
           Grid<Actor> gr = getGrid();
           Actor a = gr.get(loc);
           if (a instanceof Bug )
                bugs.add((Bug)a);

        }
        Collections.sort(bugs,new BugComparator());
        int n=bugs.size();
        setMessage(n+" bugs, furthest is at "+bugs.get(n-1).getLocation() );

    }
}

BugComparatorTester.java

public class BugComparatorTester 
{
	public static void main (String[] args)
	{
		FarthestBugWorld  myWorld = new FarthestBugWorld(4,5,3);
		myWorld.show();
	}

}