gpt4 book ai didi

java - 如何清理我用 Java 编写的这个方法?

转载 作者:行者123 更新时间:2023-12-01 07:16:18 25 4
gpt4 key购买 nike

我正在编写一个迷宫生成器。我有一个“Cell”类,如下所示:

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

}
}

我的程序中的迷宫只是一个二维单元数组。创建数组后,我手动进入并设置对相邻单元格的所有引用(北、南、东、西)。

我要清理的是removeRandomWall()。假设随机选择一个其访问标志设置为 false 的相邻单元格,并移除该单元格和连接它们的相邻单元格中的墙。

因此,它需要考虑所有未访问过的相邻单元格,随机选择一个,然后将该单元格中的墙和相邻单元格中的墙设置为 false,以便它们之间现在有一条路径。我已经在上面尝试过了,但看起来很笨拙。

谁能帮帮我吗?

最佳答案

而不是有 4 个独立的成员:

public Cell North;
public Cell South;
public Cell East;
public Cell West;

只有 1 个数组:

public Cell [] cells = new Cell[4];

和 4 个常量:

public final int NORTH = 0;
public final int EAST = 1;
public final int SOUTH = 2;
public final int WEST = 3;

它使得移除随机墙之类的事情变得更加容易。

关于java - 如何清理我用 Java 编写的这个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1573955/

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