# Cellular Automata (From Coding Train

Hi All!

So I was playing around with the coding train code for Dan’s Game of Life Simulation.

I wanted to change the rules, I did, and it worked great. I started to think about tracking state changes with a counter and decided to replace the states in the array with PVectors.

grid[i][j].x tracks the state, grid[i][j].y is a counter which increases by 1 every time there is a state change.

I keep getting a nullpointeracception on line 38 (first IF statement, for drawing the cells as rectangles if active) and I am not sure what I am missing.

My coding abilities are “new hobbyist” at best, so technical phrases unless to point me to reading and articles etc will go over my head :-/ lol

``````//Just like Daniel's Game of live
//except new rule set (tested and works)
//and replacing states with PVectors
//grid.x tracks state
//grid.y is a counter of the total number of
//state changes. (when state updated, .add(0,1) to vector)

float sum;
int cols;
int rows;
int resolution = 10;
PVector [][] grid;

void setup() {
frameRate(3);
size(1010, 1010);
cols = width / resolution;
rows = height / resolution;

PVector [][] grid = new PVector[cols][rows];
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
grid[i][j] = new PVector (0,0);
}
}

grid[50][50] = new PVector (1,0);
}

void draw() {
background(51);

for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
int x = i * resolution;
int y = j * resolution;
if (grid[i][j].x == 1) {
fill(220);
noStroke();
rect(x, y, resolution, resolution);
}
}
}

PVector[][] next = new PVector[cols][rows];

// Compute next based on grid
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
float state = grid[i][j].x;
// Count live neighbors!
int sum = countNeighbors(grid, i, j);

if (state == 0 && (sum%2) == 1 ) {
next[i][j].x = 1;

}

else if (state == 1 && (sum%2) == 0) {
next[i][j].x = 0;
}

else {
next[i][j] = grid[i][j];

}
}
}

grid = next;

//noLoop();
}

int countNeighbors(PVector [][] grid, int x, int y) {
int sum = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
int col = (x + i + cols) % cols;
int row = (y + j + rows) % rows;
sum += grid[col][row].x;
}
}
sum -= grid[x][y].x;
return sum;
}
``````

thanks in advance for anyone able to help!

Change the above line in setup to
`grid = new PVector[cols][rows];`

Effectively you had two grids, the ‘global’ grid from line 5 and a ‘local’ in setup() that is only visible in setup

1 Like

Thank you! That fixed it. I also went ahead and did the same changes to next[][] array.

Needed a few more tweeks after that but all is well!