0

だから私は人生のゲームプログラムを構築しようとしています.私は一般的に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));

}

}

4

2 に答える 2

1

これはうまくいきます:

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]
    };
}
于 2015-01-29T06:38:11.657 に答える