我仍然在爲我的迷宮遊戲製作我的Cell類。在另一個線程的幫助後,有人建議我爲我的Walls/Neighbors使用EnumMap,目前這個工作非常順利。如何將Enum與其相反的值相關聯,如在主要方向(南北,東西方等)?
這裏是我迄今:
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;
}
}
如果你在那最後的評論看那裏,我第一次推倒說,在我目前的小區北牆。然後,我帶走我的北方鄰居,現在我必須拆除我的南牆,這樣兩個單元之間的牆壁才被拆除。
什麼是一個簡單的方法來擴展我的枚舉,所以我可以給它一個方向,它返回給我它是相反的?
+1。你不應該在枚舉上「切換」,但由於循環依賴關係,這是最乾淨,最可讀的方式來執行它......假設你添加了'default:throw new AssertionError(this)':) – gustafc
@ gustafc同意,我更新了我的答案。 – jqno
@gustafc,通常不希望打開枚舉的原因是什麼? – Scorcher84