我有两个阵列:墙和邻居.
public boolean[] walls = new boolean[4];
public Cell[] neighbors = new Cell[4];
Run Code Online (Sandbox Code Playgroud)
我有一个枚举:
enum Dir
{
North,
South,
East,
West
}
Run Code Online (Sandbox Code Playgroud)
现在,我希望能够通过他们的方向访问墙壁或邻居,所以我不必传递一堆魔法索引.
但是,当我阅读Enum.ordinal()的文档时,它说程序员几乎没有使用这种方法,这让我认为它不应该以这种方式使用.
我在想做类似的事情:
List<Dir> availableDirections = new ArrayList<Dir>();
for(Dir direction : Dir.values())
if (!Neighbors[direction.ordinal()].Visited)
availableDirections.add(direction);
Run Code Online (Sandbox Code Playgroud)
甚至:
return Neighbors[Dir.North.ordinal()];
Run Code Online (Sandbox Code Playgroud)
我应该恢复使用设置为索引值的NORTH,SOUTH,EAST,WEST的静态常量还是使用Enum的序数方法?
我写了一些为我生成迷宫的代码.迷宫由(nxn)个单元组成,每个单元具有一个布尔值来表示一个墙(北,南,东西).
它工作正常,我写了下面的函数来打印出迷宫:
public static void printMaze(Cell[][] maze)
{
for(int i = 0; i < maze.length; i++)
{
for(int j = 0; j < maze[i].length; j++)
{
System.out.print((maze[i][j].walls.get(Dir.NORTH)) ? "+--+" : "+ +");
}
System.out.println();
for(int j = 0; j < maze[i].length; j++)
{
System.out.print((maze[i][j].walls.get(Dir.WEST)) ? "|" : " ");
System.out.print(" ");
System.out.print((maze[i][j].walls.get(Dir.EAST)) ? "|" : " ");
}
System.out.println();
for(int j = 0; j < maze[i].length; j++)
{
System.out.print((maze[i][j].walls.get(Dir.SOUTH)) ? "+--+" : "+ +");
}
System.out.println();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,由于细胞共用墙壁,我在打印功能中产生了一种双壁走廊外观:
+--++--++--++--++--++--++--++--++--++--+ …Run Code Online (Sandbox Code Playgroud) 我还在为我的迷宫游戏制作我的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 …Run Code Online (Sandbox Code Playgroud) 我在屏幕上使用Java2D绘制了一堆原语,我得到了很多撕裂/闪烁.
如何启用/使用双缓冲,以便将其从屏幕上拉出然后显示整个事物?
有没有什么情况我想在我的算法中使用显式堆栈数据结构,而不是做递归(使用调用堆栈)?
以一种方式做另一种方式有什么好处吗?我认为使用显式数据结构会更高效,因为它不需要方法调用,但再次是微优化领域.