I am working on recreating Game of Life in different ways, taking Coding Train’s video as the starting point. What I am trying to add is ‘color inheritance’: A newborn cell ‘inheriting’ the color from the average of the neighbouring cells’ colours.
I have made two versions: The first one has a 2D grid array for cells, and each cell is an array with RGB values.
grid[i][j] = [255,0,100]
A for loop iterates through the grid array and draws boxes of the right colour on the right position on the canvas. It then checks if the cell should be alive or dead next generation. This works fine without any slowdown, no matter the size of the grid.
https://editor.p5js.org/umutreldem/sketches/1qCmEzHlY
The second version fills each element of the grid array with Cell objects. This object receives its coordinates on the grid and its size. The color is given relative to its position on the grid.
function Cell(x, y, size) {
this.x = x * size;
this.y = y * size;
this.size = size;
//...
this.r = x * 10;
this.g = y * 10;
this.b = x+y;
The Cell object has functions for determining how many alive neighbours it has, inheriting colour from neighbours, etc. It is the same process as the first version. Then in draw() the grid is looped twice: once for determining the next status of each cell, and once for changing the cells to their new state.
function draw() {
background(0);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j].show();
grid[i][j].evolve(countNeighbors(grid, i, j), i, j, grid);
}
}
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j].swap(i, j, grid);
}
}
}
This version experiences massive slowdown, especially at higher resolutions.
https://editor.p5js.org/umutreldem/sketches/2skO6-2Cm
I would like to add more features to this, such as keeping count of the age of each cell (for how long it is alive,) and using making an object for each cell makes more sense to me.
With my limited experience with p5.js / JavaScript in general, I cannot understand why this is the case. The function of both versions is the same (apart from one extra loop in the second version), so why does the second version tax the computer this much?