中间的房间周围(东南西北)有四个房间,请编写Java类表达这种关系,同时给房间类提供一个方法,能够从某一出口出来进入该出口对应的房间
时间: 2024-11-03 20:21:30 浏览: 46
要表达一个中间房间四周有四个房间的关系,我们可以定义一个名为`FourWallsRoom`的类,它继承自一个基础的`Room`类,同时增加一个属性来表示中心位置以及四个方向的出口。这里是一个简单的示例:
```java
import java.util.HashMap;
import java.util.Map;
class Direction {
static final String NORTH = "north";
static final String SOUTH = "south";
static final String EAST = "east";
static final String WEST = "west";
// 可以考虑使用枚举替代字符串,增强类型安全
}
class BaseRoom {
private int id;
private String name;
// ... 省略Room类的其他属性和构造函数
}
public class FourWallsRoom extends BaseRoom {
private Map<String, Room> exits; // 使用Map保存四个方向的出口
public FourWallsRoom(int id, String name) {
super(id, name);
exits = new HashMap<>();
exits.put(Direction.NORTH, createAdjacentRoom(this, Direction.SOUTH));
exits.put(Direction.SOUTH, createAdjacentRoom(this, Direction.NORTH));
exits.put(Direction.EAST, createAdjacentRoom(this, Direction.WEST));
exits.put(Direction.WEST, createAdjacentRoom(this, Direction.EAST));
}
private Room createAdjacentRoom(Room currentRoom, Direction direction) {
// 创建新房间并将其添加到当前房间的出口列表中
Room adjacentRoom = new BaseRoom(); // 实际项目中应根据需求生成相应类型的房间
currentRoom.
阅读全文