Game of life
The Conway game of life is a brilliant cellular automate.
It have got simple rules:
We count neighbours of cell
- If there is zero or one — cell dies
- If there are more than three — cell dies
- If cell is already dead and have exact three neighbours — it resurrect
Here is an implementation. I made just born cells blue and added randomly spawning cells for more action. Look!
let field = [], swapField = [];
for(let i = 0; i < h; i++){
field[i] = [];
swapField[i] = [];
for(let j = 0; j < w; j++){
field[i][j] = i%j%8 === 1;
swapField[i][j] = 0;
}
}
px.frameRate = 10;
let colors = [0x000000, 0xFFFFFF, 0x0088bb, 0x00FF00];
const countNeighbours = (x, y) => {
let i, j, count = 0;
for(i = -1; i < 2; i++)
for(j = -1; j < 2; j++)
if(i !== 0 || j !== 0)
count += field[(y+i+h)%h][(x+j+w)%w] ? 1:0;
return count;
};
const update = () => {
let x, y, neighbours;
for(x = 0; x < w; x++)
for(y = 0; y < h; y++)
point(x,y, colors[field[y][x]]);
for(x = 0; x < w; x++)
for(y = 0; y < h; y++){
neighbours = countNeighbours(x, y);
if(field[y][x] !== 0){
// Any live cell
// with fewer than two live neighbours dies
swapField[y][x] = neighbours < 2 ? 0 :
// with more than three live neighbours dies
neighbours > 3 ? 0 : 1;
}else{
// Any dead cell with exactly three live neighbours becomes a live cell
swapField[y][x] = neighbours === 3 ? 2 : 0;
}
}
// selfborn cells
for(x = 0; x < 20;x++)
rand(115) === 1 && (swapField[rand(h)][rand(w)] = 3);
[field, swapField] = [swapField, field];
}
Pulsar for the icon
I want to make a beautiful icon for this article, so I've looked through the list of known pulsars and find one that attracts me
px.frameRate = 6
let field = [], swapField = [];
for(let i = 0; i < h; i++){
field[i] = [];
swapField[i] = [];
for(let j = 0; j < w; j++){
field[i][j] = false;//i%j%8 === 1;
swapField[i][j] = 0;
}
}
const spriteSheet = px.spriteSheet('/img/gameOfLifeIcon.png', 48, 48);
spriteSheet.onload(function(){
var sprite = spriteSheet.get(0,0);
for(var x = 0; x < spriteSheet.fullWidth; x++)
for(var y = 0; y < spriteSheet.fullWidth; y++)
field[y][x] = sprite.getPoint(x,y) === 0 ? 1 : 0;
draw();
});
let colors = [0x0A2938, 0xFFFFFF, 0xAaC9F8, 0x00FF00];
const countNeighbours = (x, y) => {
let i, j, count = 0;
for(i = -1; i < 2; i++)
for(j = -1; j < 2; j++)
if(i !== 0 || j !== 0)
count += field[(y+i+h)%h][(x+j+w)%w] ? 1:0;
return count;
};
const draw = () => {
let x, y, neighbours;
for(x = 0; x < w; x++)
for(y = 0; y < h; y++)
point(x,y, colors[field[y][x]]);
}
const update = () => {
draw();
let x, y, neighbours;
for(x = 0; x < w; x++)
for(y = 0; y < h; y++){
neighbours = countNeighbours(x, y);
if(field[y][x] !== 0){
// Any live cell
// with fewer than two live neighbours dies
swapField[y][x] = neighbours < 2 ? 0 :
// with more than three live neighbours dies
neighbours > 3 ? 0 : 1;
}else{
// Any dead cell with exactly three live neighbours becomes a live cell
swapField[y][x] = neighbours === 3 ? 2 : 0;
}
}
[field, swapField] = [swapField, field];
}