styke
styke

Reputation: 2174

Can't work out why array updating when it shouldn't be?

I'm building Conway's game of life with Javascript and HTML5 Canvas. The code here is within the context of a gameOfLife object:

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

After populating this.cells with my cell objects, I populate this.nextCellState like so:

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

On mouse click, the corresponding cell object property isAlive is turned 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');
        }
    }
}

The problem is, having a look at cells and nextCellState arrays at the breakpoint, both of them have the clicked cell activated to true.

What is causing this?

Upvotes: 0

Views: 75

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

When you copy the contents of cells into nextCellState, you are making a shallow copy of the array. The objects themselves are now aliased by the two arrays (that is, cells[0] and nextCellState[0] refer to the same object).

You need to create new objects in nextCellState to be able to change the objects' internal states independently. The easiest would be if your cell objects had a copy constructor function. Then you could do something like this:

this.nextCellState = this.nextCellState.concat(
    this.cells.map(function(cell) {
        return cell.copy();  // or whatever your copy constructor is
    })
);

Upvotes: 2

Related Questions