I am making a Hunt the Wumpus game using the graph data structure. Each vertex in it is an array of size 4 to represent each direction, north south east west. The directions are stored in an enum. When one vertex is connected with another, its adjacency is supposed to change so that it connects with the other vertex (I'm still confused about this- why is my vertex an array of size 4 but only has 1 direction).
When I connect one vertex with another and print out the arraylist of neighbors, I get a strange output. When I print the unconnected vertex I get [null, null, null, null] for neighbors; when I print the connected vertex I get [null, null, null, [null, null, null, null]. I don't know what the neighbors are supposed to be- should they print out as integers representing the direction enum index, or a direction? What should be printing out?
import java.util.ArrayList;
import java.util.Collection;
enum Direction{
EAST,
WEST,
NORTH,
SOUTH
}
public class Vertex extends Agent implements Comparable<Vertex>{
private Vertex[] connections;
private Direction dir;
private int cost;
private boolean marked;
public Vertex(double x0, double y0){
super( x0, y0);
connections = new Vertex[4];
this.dir = dir;
this.cost = cost;
this.marked = marked;
}
public Direction opposite(Direction dir) {
//that returns the compass opposite of a direction (i.e. South for North...)
if(dir == Direction.EAST){
dir = Direction.WEST;
}
else if(dir == Direction.WEST){
dir = Direction.EAST;
}
else if(dir == Direction.NORTH){
dir = Direction.SOUTH;
}
else dir = Direction.NORTH;
return dir;
}
void connect(Vertex other, Direction dir){
//modify the object's adjacency list/map so that it connects with the other Vertex. This is a uni-directional link.
connections[dir.ordinal()] = other;
}
Vertex getNeighbor(Direction dir){
//returns the Vertex in the specified direction or null.
return this.connections[dir.ordinal()];
}
Collection getNeighbors(){
//returns a Collection, which could be an ArrayList, of all of the object's neighbors.
ArrayList<Vertex> neighborList = new ArrayList<Vertex>();
for (Direction dir: Direction.values()){
neighborList.add(this.getNeighbor(dir));
}
return neighborList;
}
public int getCost(){
return this.cost;
}
public int setCost(int c){
return this.cost = c;
}
public boolean getMarked(){
return this.marked;
}
public boolean setMarked(boolean m){
return this.marked = m;
}
public int compareTo(Vertex other){
return (this.cost - other.cost);
}
/*
* returns a string containing the number of neighbors, the cost, and the marked flag
*/
public String toString(){
String s = "";
s += this.getNeighbors() + "\n" ;
s += "cost: " + this.cost + "\n";
s += "marked: " + this.marked;
return s;
}
public static void main (String args[]){
Vertex newE = new Vertex(0.5, 0.5);
Vertex newerE = new Vertex(0.123, 1.56);
newE.connect(newerE, Direction.SOUTH);
newE.setCost(1);
newE.setMarked(true);
System.out.println(newE.toString());
}
}