如何将Enum与其相反的值相关联,如在主要方向(南北,东西等)?

Sco*_*r84 5 java enums

我还在为我的迷宫游戏制作我的Cell课程.在另一个线程的帮助之后,有人建议我使用EnumMap作为我的墙/邻居,这到目前为止工作得很好.

这是我到目前为止:

enum Dir {
    NORTH, SOUTH, EAST, WEST
}

class Cell {
    public Map<Dir, Cell> neighbors = Collections
            .synchronizedMap(new EnumMap<Dir, Cell>(Dir.class));
    public Map<Dir, Boolean> walls = Collections
            .synchronizedMap(new EnumMap<Dir, Boolean>(Dir.class));

    public boolean Visited;

    public Cell() {
        Visited = false;
        for (Dir direction : Dir.values()) {
            walls.put(direction, true);
        }
    }

    // Randomly select an unvisited neighbor and tear down the walls
    // between this cell and that neighbor.
    public Cell removeRandomWall() {
        List<Dir> unvisitedDirections = new ArrayList<Dir>();
        for (Dir direction : neighbors.keySet()) {
            if (!neighbors.get(direction).Visited)
                unvisitedDirections.add(direction);
        }

        Random randGen = new Random();
        Dir randDir = unvisitedDirections.get(randGen
                .nextInt(unvisitedDirections.size()));
        Cell randomNeighbor = neighbors.get(randDir);

        // Tear down wall in this cell
        walls.put(randDir, false);
        // Tear down opposite wall in neighbor cell
        randomNeighbor.walls.put(randDir, false); // <--- instead of randDir, it needs to be it's opposite.

        return randomNeighbor;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你看那里的最后一个评论,我首先拆掉我当前单元格中的北墙.然后我带我的北邻居,现在我必须拆掉我的南墙,所以两个牢房之间的墙壁已被拆除.

什么是一个简单的方法来扩展我的枚举,所以我可以给它一个方向,它回到我的对面?

Jas*_*n S 15

还有另一种没有开关/盒子的方式,或者必须存储状态:

public enum Dir {
   NORTH { @Override public Dir opposite() { return SOUTH; }},
   EAST  { @Override public Dir opposite() { return WEST;  }},
   SOUTH { @Override public Dir opposite() { return NORTH; }},
   WEST  { @Override public Dir opposite() { return EAST;  }},
   ;

   abstract public Dir opposite();
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这将创建五个类文件而不是一个. (2认同)

jqn*_*qno 10

我认为最简单的方法就是添加一个方法.请注意,这仅在枚举常量的数量不会随时间变化时才有效.

enum Dir {
    NORTH,
    SOUTH,
    EAST,
    WEST;

    public Dir opposite() {
        switch(this) {
            case NORTH: return Dir.SOUTH;
            case SOUTH: return Dir.NORTH;
            case EAST: return Dir.WEST;
            case WEST: return Dir.EAST;
            default: throw new IllegalStateException("This should never happen: " + this + " has no opposite.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的代码中,您可以这样做:

randomNeighbor.walls.put(randDir.opposite(), false);
Run Code Online (Sandbox Code Playgroud)

  • +1.你不应该在枚举上"切换",但由于循环依赖,这是最干净,最易读的方法...假设你添加`default:throw new AssertionError(this)`:) (3认同)
  • @ Scorcher84如果您稍后决定在枚举中添加一个条目(例如,NORTHWEST),则必须更新所有switch语句.如果他们在enum本身,这很烦人但可行.如果你的代码中有其他地方的交换机,它几乎是不可能的.通常,最好在枚举中添加抽象方法.在这种情况下,这是不可能的,因为在声明之前你不能引用枚举常量. (2认同)