/* Alan Renaud */
/* Assignment 3 Sample Solution */
/* Using Arrays */
/* Oct. 17, 1999 */
/* Room.java */
/* An implementation of Room.java with arrays */
import java.io.*;
import java.util.*;
public class Room {
// constants signifying the maximum
number of doors
// and rooms respectively
public static final int MAXDOORS =
3;
public static final int MAXROOMS =
100;
// Static array cave to hold all the
rooms (note that we will not use
// the element with index 0;
public static Room[] cave =
new Room[MAXROOMS+1];
// instance array door which represents
the doors pointed to by each
// object
Room[] doors;
// Each room r has a unique id > 0.
// nextId is the ID# of the next room to be created.
private static int nextId =
1;
private int id;
// Create a new room with a unique ID# and
// a reference to the previous room.
public Room() {
id = nextId;
cave[nextId] = this;
nextId++;
doors = new
Room[1+MAXDOORS];
}
// return Room with specified targetId or null of it does not exist
public static Room
findRoom(int targetId) {
if (targetId<1 || targetId >= nextId)
return null;
return cave[targetId];
}
// farRoom(int door) is an instance method
// that returns the Room at the far
// side of the tunnel entered via the given door.
// The actual Room object, not just its ID#, is
// returned. Return null if the door does not exist,
// or if the door number is smaller than 1 or larger than 3.
public Room farRoom(int door) {
if ((door<1)||(door>MAXDOORS))
return null;
else
return doors[door];
}
// returns the index of the next free
door in Room r.
// returns 0 if there are no free doors
private static int nextFreeDoor(Room r) {
int i=1;
while(i<=MAXDOORS && r.doors[i]!=null) i++;
if (i>MAXDOORS) i=0;
return i;
}
// Method connect
// Adds a (bi-directional) door between the two rooms. Prints a diagnostic
// message and makes no connection when more than MAXDOORS doors is to be
// connected to either room.
public static void connect(Room a, Room b) {
int doorA=nextFreeDoor(a);
int doorB=nextFreeDoor(b);
if ((a!=b&&doorA!=0&&doorB!=0)){
a.doors[doorA]=b;
b.doors[doorB]=a;
}
else if (a==b&&doorA <=
MAXDOORS-1) {
a.doors[doorA]=b;
b.doors[doorA+1]=a;
}
else {
if (doorA==0) {
System.out.println("Connecting too many doors to Room " + a.ID());
}
else {
System.out.println("Connecting too many doors to Room "
+ b.ID());
}
}
}
// Return the room id
public int ID() {
return id;
}
// returns a description of the room, including its id number and
// where its doors lead to.
public String toString() {
String myInfo = "Room " + id +
".";
for (int i=1; i<= MAXDOORS ; i++) {
if (doors[i]!=null)
myInfo = myInfo + " <" + i + "> --> " + doors[i].id;
}
return myInfo;
}
// Method showRooms
// Prints a description of all objects in the class.
public static void showRooms() {
System.out.println();
for(int roomCount =
1; roomCount < nextId; roomCount++) {
System.out.println(cave[roomCount]);
}
System.out.println();
}
}