# 🚧 Broken on Mobile 🏗️ Link to heading

‘Life’ is a cellular automata invented by the late John Conway. It is a discrete simulation consisting of a (theoretically) infinite two-dimensional grid of cells. Each of these cells can be either alive or dead and has eight neighbours which affects its next state. There are three rules that define life, outlined as:

- Any living cell with two or three live neighbours will continue living. ❤️
- Any dead cell with three live neighbours will be brought to life. 🌱
- All other cells will die, dead cells will remain dead. ☠️

I have written an implementation of the game of life in JavaScript below:

To understand what’s going on here, we can look at the source code (link down the bottom! 😉). The constructor method creats a grid of cells, then randomises the state.

```
constructor() {
this.cell = 5;
this.grid = 160;
this.board = new Array(this.grid);
this.friends = new Array(this.grid);
for (let x = 0; x < this.grid; x++) {
this.board[x] = new Array(this.grid);
this.friends[x] = new Array(this.grid);
}
}
```

And then the next board state is calculated entirely before drawing the next frame. This is important as cell states need to be considered holistically to ensure that the next board state can be effectively calculated.

```
update() {
//count neighbours
for (let x = 0; x < this.grid; x++) {
for (let y = 0; y < this.grid; y++) {
this.friends[x][y] = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
//ignore self-comparison case
if ((i == 0) && (j == 0)) {
continue;
}
this.friends[x][y] += this.alive(x + i, y + j);
}
}
}
}
//implement rules
for (let x = 0; x < this.grid; x++) {
for (let y = 0; y < this.grid; y++) {
if (this.friends[x][y] < 2) {
this.set(x, y, 0);
}
else if (this.friends[x][y] > 3) {
this.set(x, y, 0);
}
else if (this.friends[x][y] === 3) {
this.set(x, y, 1);
}
}
}
this.draw();
}
```

Perhaps unsurprisingly, there are actually two types of stable life, those that remain in place (static on the board) and those that move (these are a bit more exciting to observe in action)… See if you can spot both types 🧐.

Some additional reading material(s):