![](/img/trans.png)
[英]Game Of Life Java - Counting neighbors with 2D arrays and for loops
[英]Counting neighbors with wrap around in 2d array(game of life)
所以我正在尝试构建生命游戏程序,而且我对java /编码一般都很新鲜,而且我在绕着2D数组环绕时遇到了问题。 我有一个构造函数和方法,将构建一个数组并将“单元格”放在我想要的位置,但我不明白我怎么能看到一个单元格有多少个邻居。
把它们加起来:
我可以制作任何类型的2D数组。
我可以将“单元格”放在数组中的不同元素上
现在我怎么看我被检查的单元格旁边的空格是否有邻居(我使用嵌套的for循环来遍历每个单元格)?
记住! 环绕在这里生效。
更新:这就是我所拥有的,但是当我测试它时,它会返回比应该存在的少1个邻居。 更新2:我删除了第一个if语句,因为我认为它没有意义。 但现在我不能上升1。
public int neighborCount(int row, int col) {
int count = 0;
for (int r = 0; r < society.length; r++) {
for (int c = 0; c < society[0].length; c++) {
// up and left
if ((society[(r - 1 + row) % row][(c - 1 + col) % col]) == cell) {
count++;
}
// up
if ((society[(r - 1 + row) % row][c]) == cell) {
count++;
}
// up and right
if ((society[(r - 1 + row) % row][(c + 1 + col) % col]) == cell) {
count++;
}
// left
if ((society[r][(c - 1 + col) % col]) == cell) {
count++;
}
// right
if ((society[r][(c + 1 + col) % col]) == cell) {
count++;
}
// down and left
if ((society[(r + 1 + row) % row][(c - 1 + col) % col]) == cell) {
count++;
}
// down
if ((society[(r + 1 + row) % row][c]) == cell) {
count++;
}
// down and right
if ((society[(r + 1 + row) % row][(c + 1 + col) % col]) == cell) {
count++;
}
}
}
return count;
}
我的测试:
@Test
public void testNeighborsWrapping() {
GameOfLife society = new GameOfLife(10, 16);
society.growCellAt(3, 3);
society.growCellAt(3, 4);
society.growCellAt(3, 5);
assertEquals(0, society.neighborCount(2, 1));
assertEquals(1, society.neighborCount(2, 2));
assertEquals(2, society.neighborCount(2, 3));
assertEquals(3, society.neighborCount(2, 4));
}
}
如果我正确理解问题,代码可能是这样的
Object[] getNeighbors(int i, int j) {
// put code to return the neighbors given an index
}
boolean allNeighborsFull(int i, int j) {
Object[] neighbors = getNeighbors(i, j);
boolean allFull = true;
for (Object neighbor : neighbors) {
if (!neighbor.full()) {
allFull = false;
break;
}
}
return allFull;
}
boolean allNeighborsSurrounded() {
Object[] neighbors = getNeighbors(i, j);
// check each one of these using the method above
}
这可行:
public Cell[] getNeighbours(int i, int j) {
int i2 = i - 1;
int i3 = i + 1;
int j2 = j - 1;
int j3 = j + 1;
if (i2 == -1)
i2 = board.length - 1;
if (i3 == board.length)
i3 = 0;
if (j2 == -1)
j2 = board[i].length - 1;
if (j3 == board[i].length)
j3 = 0;
return new Cell[] {
board[i2][j2], board[i2][j], board[i2][j3],
board[i][j2], board[i][j3], board[i3][j2],
board[i3][j], board[i3][j3]
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.