だから私は人生のゲームプログラムを構築しようとしています.私は一般的にJava/コーディングにかなり慣れていません.2D配列で頭を包み込むのに問題があります. 配列を作成し、必要な場所に「セル」を配置するコンストラクターとメソッドがありますが、セルに隣接するセルの数を確認する方法がわかりません。
要約すると:
あらゆるタイプの 2D 配列を作成できます。
配列内のさまざまな要素に「セル」を配置できます
チェックされているセルの隣のスペースがすべての側に隣接していることを確認するにはどうすればよいですか (ネストされた for ループを使用して各セルを通過します)。
心に留めておいてください!ここではラップアラウンドが有効です。
更新: これは私が持っているものですが、テストすると、本来あるべきよりも 1 つ少ないネイバーが返されます。更新 2: 最初の if ステートメントは意味がないと思うので削除しました。しかし、今は c を 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));
}
}