// Get the canvas element.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Set the width and height of the canvas.
canvas.width = 600;
canvas.height = 600;
function Cell(x, y, size, state) {
this.x = x;
this.y = y;
this.size = size;
this.state = state;
}
Cell.prototype.setState = function(state) {
this.state = state;
}
Cell.prototype.draw = function() {
ctx.beginPath();
ctx.rect(this.x, this.y, this.size, this.size);
ctx.fillStyle = this.state === 1 ? 'red' : 'white';
ctx.fill();
ctx.stroke();
}
function Grid(rows, cols, size) {
this.rows = rows;
this.cols = cols;
this.size = size;
this.cells = this.createCells();
}
Grid.prototype.createCells = function() {
const cells = [];
for (let i = 0; i < this.rows; i++) {
cells[i] = [];
for (let j = 0; j < this.cols; j++) {
cells[i][j] = new Cell(j * this.size, i * this.size, this.size, Math.round(Math.random()));
}
}
return cells;
}
Grid.prototype.draw = function() {
this.cells.forEach(row => row.forEach(cell => cell.draw()));
}
Grid.prototype.update = function() {
const next = this.createCells();
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
const cell = this.cells[i][j];
const neighbours = this.countNeighbours(i, j);
if (cell.state === 1 && (neighbours < 2 || neighbours > 3)) {
next[i][j].state = 0;
} else if (cell.state === 0 && neighbours === 3) {
next[i][j].state = 1;
} else {
next[i][j].state = cell.state;
}
}
}
this.cells = next;
}
Grid.prototype.countNeighbours = function(x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
const row = (x + i + this.rows) % this.rows;
const col = (y + j + this.cols) % this.cols;
sum += this.cells[row][col].state;
}
}
sum -= this.cells[x][y].state;
return sum;
}
const grid = new Grid(50, 50, 10);
grid.draw();
setInterval(() => {
grid.update();
grid.draw();
}, 1000);