0

Javascript と HTML5 Canvas を使用して、コンウェイの人生ゲームを作成しています。ここのコードは、gameOfLife オブジェクトのコンテキスト内にあります。

this.cells = [];
this.nextCellState = [];

this.cellsセル オブジェクトを入力した後、次this.nextCellStateのように入力します。

this.nextCellState = this.nextCellState.concat(this.cells);

マウスをクリックすると、対応するセル オブジェクト プロパティ isAlive が true になります。

function clickAlive(x, y) {
    for (var i in this.cells) {
        if (x.between(this.cells[i].x, this.cells[i].x + cellsize) && y.between(this.cells[i].y, this.cells[i].y + cellsize)) {
            this.cells[i].isAlive = true;
            console.log('Breakpoint');
        }
    }
}

問題は、ブレークポイントでcellsnextCellState配列を見ると、どちらもクリックされたセルが にアクティブになっていることtrueです。

これは何が原因ですか?

4

1 に答える 1

2

の内容をにコピーすると、配列の浅いコピーが作成されますcellsnextCellStateオブジェクト自体は、2 つの配列によってエイリアス化されます (つまり、同じオブジェクトcells[0]を参照します)。nextCellState[0]

nextCellStateオブジェクトの内部状態を個別に変更できるようにするには、新しいオブジェクトを作成する必要があります。最も簡単なのは、セル オブジェクトにコピー コンストラクター関数がある場合です。次に、次のようなことができます。

this.nextCellState = this.nextCellState.concat(
    this.cells.map(function(cell) {
        return cell.copy();  // or whatever your copy constructor is
    })
);
于 2013-04-24T18:15:40.787 に答える