gpt4 book ai didi

java - 我如何将枚举与其相反的值关联起来,如在基本方向(北 - 南,东 - 西等)上?

转载 作者:搜寻专家 更新时间:2023-10-31 08:06:32 27 4
gpt4 key购买 nike

我仍在为我正在尝试制作的迷宫游戏编写 Cell 类(class)。在获得不同线程的帮助后,有人建议我为我的墙壁/邻居使用 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;
}
}

如果你看那里的最后一条评论,我首先要拆除我当前牢房中的北墙。然后我带着我的北邻居,现在我必须拆除我的南墙,所以两个牢房之间的墙已经被拆除。

有什么简单的方法可以扩展我的枚举,以便我可以给它一个方向,然后它返回给我相反的方向?

最佳答案

还有另一种方式,无需 switch/case,也不必存储状态:

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();
}

关于java - 我如何将枚举与其相反的值关联起来,如在基本方向(北 - 南,东 - 西等)上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1575146/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com