Глядя на ваши данные, чтобы определить подходящую реализацию, я считаю, что направления exit должны быть enum
.
public enum Direction {
EAST, NORTH, SOUTH, WEST;
}
И exit - это комбинация направления и числа, то есть количество выходов из комнаты в данном направлении. Итак, я создал класс RoomExit
.
public class RoomExit {
private Direction direction;
private int count;
public RoomExit(Direction direction, int count) {
if (count < 0) {
throw new IllegalArgumentException("negative exits");
}
this.direction = direction;
this.count = count;
}
public Direction getDirection() {
return direction;
}
public int getCount() {
return count;
}
}
Наконец, ваш образец данных описывает серию комнат, где каждая комната имеет идентификатор, имя, описание и количество выходов. Итак, я создал класс RoomData
.
import java.util.ArrayList;
import java.util.List;
public class RoomData {
private int id;
private String name;
private String description;
private List<RoomExit> exits;
public RoomData(int id, String name) {
this.id = id;
this.name = name;
exits = new ArrayList<>();
}
public boolean addExit(RoomExit exit) {
return exits.add(exit);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public List<RoomExit> getExits() {
return exits;
}
public String toString() {
return String.format("%d %s [%s] %d exits", id, name, description, exits.size());
}
}
Затем я создал класс «драйвер», который считывает текстовый файл, содержащий данные о комнатах (я назвал этот файл roomdata.txt
), и создает список комнат. .
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class RoomTest {
private static final String COMMA = ",";
private static final String DESCRIPTION = "Description :";
private static final String EQUALS = "=";
private static final String EXITS = "exits";
private static final String ID = "ID";
private static final String SEMI_COLON = ";";
private static int getRoomId(String line) {
Objects.requireNonNull(line, "null line");
String[] firstSplit = line.split(COMMA);
if (firstSplit.length != 2) {
throw new IllegalArgumentException("Unexpected line: " + line);
}
String[] secondSplit = firstSplit[0].split(EQUALS);
if (secondSplit.length != 2) {
throw new IllegalArgumentException("Unexpected line: " + line);
}
int roomId = Integer.parseInt(secondSplit[1].trim());
return roomId;
}
private static String getRoomName(String line) {
Objects.requireNonNull(line, "null line");
String[] firstSplit = line.split(COMMA);
if (firstSplit.length != 2) {
throw new IllegalArgumentException("Unexpected line: " + line);
}
String[] secondSplit = firstSplit[1].split(EQUALS);
if (secondSplit.length != 2) {
throw new IllegalArgumentException("Unexpected line: " + line);
}
return secondSplit[1].trim();
}
private static void setRoomExits(RoomData room, String line) {
Objects.requireNonNull(line, "null line");
line = line.trim();
if (line.endsWith(SEMI_COLON)) {
line = line.substring(0, line.length() - 1);
}
String[] exits = line.split(COMMA);
for (String exit : exits) {
exit = exit.trim();
String[] parts = exit.split(" ");
if (parts.length != 2) {
throw new IllegalArgumentException("Unexpected exit: " + exit);
}
RoomExit roomExit = new RoomExit(Direction.valueOf(parts[0].trim().toUpperCase()),
Integer.parseInt(parts[1].trim()));
room.addExit(roomExit);
}
}
public static void main(String[] args) {
try (FileReader fr = new FileReader("roomdata.txt");
BufferedReader br = new BufferedReader(fr)) {
boolean isExits = false;
List<RoomData> rooms = new ArrayList<>();
RoomData room = null;
String line = br.readLine();
StringBuilder description = null;
while (line != null) {
if (line.startsWith(ID)) {
if (room != null) {
isExits = false;
room.setDescription(description.toString());
rooms.add(room);
description = null;
}
room = new RoomData(getRoomId(line), getRoomName(line));
}
else if (DESCRIPTION.equals(line)) {
description = new StringBuilder();
}
else if (EXITS.equals(line)) {
isExits = true;
}
else {
if (isExits) {
setRoomExits(room, line);
}
else {
description.append(line);
description.append(System.lineSeparator());
}
}
line = br.readLine();
}
if (room != null) {
room.setDescription(description.toString());
rooms.add(room);
}
System.out.printf("There are %d rooms.%n", rooms.size());
rooms.forEach(System.out::println);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Вот результат выполнения указанной выше программы «драйвера».
There are 6 rooms.
1 Bed Room [You are standing in the middle of a dark room. It's your room, but something feels off everything is gone just a plan dark room.
You see a red light sighing under the door it seems like a way to exit.
You can go North from here out the Door.
] 1 exits
2 Hallway [You enter the Hallway still noticing a red light, but it's still coming way down at the other end. You look around and notice patches of torn spots on the wall
full of black voids looking spots. Slowly sucking in more of the room. Everything else is black, and grey, just like your room was with more objects missing.
You know the red light is at the other end of the hallway with a entrance to the living room
] 2 exits
3 Living-room [You enter the living room its still has some color left, but you notice its slowly fading away on the table in the middle of the room surrounded by to gray couches.
you look over to your East and hear a Scream coming from the Dinning-room
but also notice Movement through the West Leading to the Basement
] 3 exits
4 Dinning-room [You have entered the Dinning-room and Notice shadows moving around the room you feel a cold and lifeless wind.
You are continuing to hear Screams but not from this room its coming from the East that leads to the Front-yard The screams get louder for ever step you get closer
] 2 exits
5 Basement [You have enter the Basement its empty and cold never felt temperatures this low. you notice smoke coming out of you mouth but also three different spots in
each corner of the basement also forming smoke just as you are.
There is not Exit other then East where you came from.
] 1 exits
6 Front-yard [You entered the Front-yard you notices Shadows moving along the lawn back in the fort but no ones there just you and you garden and your thoughts the driveway has no Cars
You notice you're all alone, but it can be possible you hear and see unexceptionable things. The house is floating in a endless void there is no where to go.
your only way is back into the house West
] 1 exits