我有一些方法可以运行康威的生活游戏,但在我的邻居计数方法中,我不知道如何解释环绕。我将提出执行此操作的方法。同样,我主要只需要我的 neighborCount 方法的帮助。我已经测试了其他方法,它们似乎工作得很好,但是当我测试问题方法时,它返回的值真的很假。
public class GameOfLife {
private boolean[][] society;
private boolean cell = true;
private boolean empty = false;
public GameOfLife(int rows, int cols) {
// Complete this method.
society = new boolean[rows][cols];
for (int r = 0; r < society.length; r++) {
for (int c = 0; c < society[0].length; c++) {
society[r][c] = empty;
}
}
}
public void growCellAt(int row, int col) {
// Complete this method
society[row][col] = cell;
}
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++;
}
// right
if (society[r][(c + 1 + col) % col] == cell) {
count++;
}
// down and right
if (society[(r + 1 + row) % row][(c + 1 + col) % col] == cell) {
count++;
}
// down
if (society[(r + 1 + row) % row][c]){
count++;
}
// down and left
if (society[(r + 1 + row) % row][(c - 1 + col) % col] == cell) {
count++;
}
// left
if (society[r][(c - 1 + col) % col] == cell) {
count++;
}
}
}
return count;
}
}