prototip,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<style type="text/css">
#canvas {
width: 300;
height: 300;
border: 2px solid black;
margin: 40px;
}
</style>
<title>life</title>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<label for="height">Высота:</label>
<input type="text" class="inputText" id="height" value="500"/>
<label for="width">Ширина:</label>
<input type="text" class="inputText" id="width" value="500"/>
<input type="button" value="Создать поле" class="btn red" id="create" />
<p>Таймер: <span id="count">0</span></p>
<button id="start">Start</button>
<script>
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let width = document.getElementById("width");
let height = document.getElementById("height");
let mas = [];
let count = 0;
let timer;
canvas.onclick = function(event) {
let x = event.offsetX;
let y = event.offsetY;
x = Math.floor(x / 10);
y = Math.floor(y / 10);
mas[y][x] = 1;
drawField();
};
function resizeCanvas() {
canvas.width = width.value;
canvas.height = height.value;
goLife();
}
function goLife() {
let width = canvas.width;
let height = canvas.height;
let n = width / 10;
let m = height / 10;
for (let i = 0; i < m; i++) {
mas[i] = [];
for (let j = 0; j < n; j++) {
mas[i][j] = 0;
}
}
}
goLife();
function drawField() {
let width = canvas.width;
let height = canvas.height;
ctx.clearRect(0, 0, width, height);
for (let i = 0; i < height / 10; i++) {
for (let j = 0; j < width / 10; j++) {
if (mas[i][j] == 1) {
ctx.fillRect(j * 10, i * 10, 10, 10);
}
}
}
}
function startLife() {
let mas2 = [];
let width = canvas.width;
let height = canvas.height;
for (let i = 0; i < height / 10; i++) {
mas2[i] = [];
for (let j = 0; j < width / 10; j++) {
let neighbors = [-1, 1].reduce((a, b) => {
b = mas[i + b];
if(b === void(0)) return a;
let num = b[j];
if(b[j + 1] !== void(0)) num += b[j + 1];
if(b[j - 1] !== void(0)) num += b[j - 1];
return a + num;
}, 0);
neighbors = [-1, 1].reduce((a, b) => a += mas[i][j + b] !== void(0) && mas[i][j + b], neighbors);
if (neighbors == 2 || neighbors == 3) {
mas2[i][j] = 1;
} else {
mas2[i][j] = 0;
};
}
}
mas = mas2;
drawField();
count++;
document.getElementById('count').innerHTML = count;
timer = setTimeout(startLife, 300);
}
document.getElementById("create").onclick = resizeCanvas;
document.getElementById("start").onclick = startLife;
</script>
</body>
</html>