我正在编写迷宫生成器。我有一个“小区”类,这是如下:如何清理我在Java中编写的这种方法?
public class Cell {
public boolean northWall;
public boolean southWall;
public boolean eastWall;
public boolean westWall;
public Cell north;
public Cell south;
public Cell east;
public Cell west;
public boolean visited;
public Cell() {
northWall = true;
southWall = true;
eastWall = true;
westWall = true;
visited = false;
}
public boolean hasUnvisitedNeighbors() {
return ((north != null && !north.Visited)
|| (south != null && !south.Visited)
|| (east != null && !east.Visited) || (west != null && !west.Visited));
}
public Cell removeRandomWall() {
List<Cell> unvisitedNeighbors = new ArrayList<Cell>();
if (north != null && !north.Visited)
unvisitedNeighbors.add(north);
if (south != null && !south.Visited)
unvisitedNeighbors.add(south);
if (west != null && !west.Visited)
unvisitedNeighbors.add(west);
if (east != null && !east.Visited)
unvisitedNeighbors.add(east);
if (unvisitedNeighbors.size() == 0) {
return null;
} else {
Random randGen = new Random();
Cell neighbor = unvisitedNeighbors.get(randGen
.nextInt((unvisitedNeighbors.size())));
if (neighbor == north) {
northWall = false;
north.southWall = false;
return north;
} else if (neighbor == south) {
southWall = false;
south.northWall = false;
return south;
} else if (neighbor == west) {
westWall = false;
west.eastWall = false;
return west;
} else if (neighbor == east) {
eastWall = false;
east.westWall = false;
return east;
}
return null;
}
}
}
在我的节目A迷宫只是细胞的2D维阵列。创建阵列后,我手动进入并设置所有对相邻单元(北,南,东,西)的引用。
我想清理的是removeRandomWall()。假设随机选择其访问标志设置为false的相邻小区,并删除该小区和连接它们的相邻小区的墙。
因此,它需要考虑所有未访问过的邻居单元,随机选择一个,然后将该单元格中的墙和相邻单元格设置为false,以便它们之间存在路径。我在上面尝试过,但看起来非常粗糙。
任何人都可以帮我吗?
没有回答你的问题,但(IMO)有价值的提示:使用Java代码约定!通过这样做,熟悉Java的其他人将更容易为您提供帮助。类名以大写字母开头,变量名以小写字母开头。更多信息:http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html –
@Bart,我明白了。出于某种原因,我认为公众成员是以帽子开始的。我会坚持公约。 – Scorcher84
我试图现在切换到Java约定。 – Scorcher84