0

I'm working on this assignment where I need to construct a version of The Game of Life. I'm having trouble getting this 2D array set up properly so that I can track whether or not cells are 'alive' or 'dead'. I've seem to have hit a wall and I need someone to just put me in the right direction.

var grid;

function setup () {
 createCanvas(400, 400);
 grid = new Grid(20);
}

function draw () {
 background(245);

   grid.draw();
}

class Grid {
  constructor (cellSize) {
   this.cellSize = cellSize;
   this.numberOfColumns = height/this.cellSize;
   this.numberOfRows = width/this.cellSize;

   this.cells = new Array(this.numberOfColumns);
   this.rows = new Array(this.numberOfRows);
   this.twoDArray = new Array(this.cells);

  for (var i = 0; i < this.cells; i++) {
   this.twoDArray[i] = new Array(this.rows);
  }


 // for (var column = 0; column < this.numberOfColumns; column ++) {
  // for (var row = 0; row < this.numberOfRows; row++) {
   // this.cells[column][row] = new Cell(column, row, cellSize);
  //}
  // }

 print(this.cells);
}

draw() {
 for (var column = 0; column < this.numberOfColumns; column ++) {
   for (var row = 0; row < this.numberOfRows; row++) {
     fill(240); 
     noStroke();
     rect(column * this.cellSize + 1, row * this.cellSize + 1, this.cellSize - 1, this.cellSize - 1);
    }
  }
 }
}
   class Cell {
    contructor (column, row, cellSize) {
     this.column = column;
     this.row = row;
     this.cellSize = cellSize;
     isAlive = false;
    }
  }

Whenever I try to uncomment the code I have commented above, the console says: TypeError: Cannot set property of '0' undefined. I'm certain I'm missing something obvious but I can't seem to see what it is. Any help that you could give would be greatly appreciated.

1
  • 1
    You have to explicitly initialize each row to its own new array. The Array() constructor just gives you a single empty array. Commented Jun 3, 2018 at 15:06

1 Answer 1

3

You cant use this.cells as a multi dimensional array, since it is populated with empty elements as per the new Array does.

You should change your code to something like:

for (var column = 0; column < this.numberOfColumns; column ++) {
  this.cells[column] = []; // or use here new Array or similar
  for (var row = 0; row < this.numberOfRows; row++) {
    this.cells[column][row] = new Cell(column, row, cellSize);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.