因此,我正在制作基于控制台的游戏。
但是我不能理解这一点,或者为什么这样做是错误的。
所以基本上我有10个房间 所以房间里有以下东西:
-房间号
-包含“房间”作为值和“字符串”作为键的哈希图
现在问题出了,一个房间可以从北,东,南,西四个方向退出,这就是哈希图中的字符串/键 它还可以有2个出口或1或3。 因此,在该哈希图中,我将方向另存为键,将另一个房间对象的值另存为值,这样我就可以跟踪到出口为止。 所以我有一种添加出口的方法。看起来像这样: 代码
public class Room {
private int RoomNo;
private HashMap<String, Room> Exits;
public Room(int roomNo){
Exits = new HashMap<String, Room>();
this.RoomNo = roomNo;
}
public void Addexits(Room room, String exitDirection){
Exits.put(exitDirection,room);
}
与之相比,在游戏类中,我创建了10个房间并使用addexits方法调用添加出口,如下所示:
Rooms = new ArrayList<Room>();
//initialize all rooms
room1 = new Room(1);
room1.Addexits(room4,"West");
room1.Addexits(room3,"East");
room2 = new Room(2);
room2.Addexits(room2,"North");
room2.Addexits(room2,"South");
room3 = new Room(3);
room3.Addexits(room3,"West");
room3.Addexits(room3,"East");
room4 = new Room(4);
room4.Addexits(room4,"West");
room4.Addexits(room4,"East");
但是,正如您在room1中看到的那样,我尝试将2个出口1在西侧添加到room4,将1个东部在1号出口添加到room3,但是当我运行它时,它将在哈希图中显示: 西->空 东->空
但是当我添加2个都与对象room1一起退出时,它说应该像这样:
西->房间1 东-> room1
所以我并没有真正弄错我在做错什么,每个房间在创建时都有自己的哈希图,并且房间已经创建好了,所以不应该成为问题。
答案 0 :(得分:0)
首先初始化所有房间,然后添加出口;
room1 = new Room(1);
room2 = new Room(2);
room3 = new Room(3);
room4 = new Room(4);
room1.Addexits(room4,"West");
room1.Addexits(room3,"East");
room2.Addexits(room2,"North");
room2.Addexits(room2,"South");
room3.Addexits(room3,"West");
room3.Addexits(room3,"East");
room4.Addexits(room4,"West");
room4.Addexits(room4,"East");
答案 1 :(得分:0)
在下面的代码中
Rooms = new ArrayList<Room>();
//initialize all rooms
room1 = new Room(1);
room1.Addexits(room4,"West");
room1.Addexits(room3,"East");
您要添加尚未初始化的room3和room4。您刚刚声明了它。那就是为什么你得到空的原因。初始化后,尝试添加它。
Rooms = new ArrayList<Room>();
//initialize all rooms
room1 = new Room(1);
room2 = new Room(2);
room2.Addexits(room2,"North");
room2.Addexits(room2,"South");
room3 = new Room(3);
room3.Addexits(room3,"West");
room3.Addexits(room3,"East");
room4 = new Room(4);
room4.Addexits(room4,"West");
room4.Addexits(room4,"East");
//here you add room4 and room3 exits
room1.Addexits(room4,"West");
room1.Addexits(room3,"East");
答案 2 :(得分:0)
这是因为,当您调用Addexits()时,不能保证您要添加的房间已经存在。因此,切换您的语句应该可以解决此问题。
Rooms = new ArrayList<Room>();
//initialize all rooms
room1 = new Room(1);
room2 = new Room(2);
room3 = new Room(3);
room4 = new Room(4);
// add all exits
room1.Addexits(room4,"West");
room1.Addexits(room3,"East");
room2.Addexits(room2,"North");
room2.Addexits(room2,"South");
room3.Addexits(room3,"West");
room3.Addexits(room3,"East");
room4.Addexits(room4,"West");
room4.Addexits(room4,"East");
还请注意,您正在将room3作为房间3的出口添加,与房间2和4相同。我不知道这是否是意图。