qwarden @
henlo
Welcome to qwarden's Sandbox.
View Other Sites from qwarden
Toggle Full-Width
HTML
<canvas></canvas>
JavaScript
let grid; let cols; let rows; let res = 20; const cvs = document.querySelector('canvas'); const c = cvs.getContext('2d'); function array2D(cols, rows) { let ret = new Array(cols); for (let i = 0; i < ret.length; i++) { ret[i] = new Array(rows); } return ret; } cvs.width = 600; cvs.height = 600; cols = Math.round(cvs.width / res); rows = Math.round(cvs.height / res); grid = array2D(cols, rows); for (let i = 0; i < cols; i++) { for (let j = 0; j < rows; j++) { grid[i][j] = Math.round(Math.random(2)); } } function draw() { c.clearRect(0, 0, cvs.width, cvs.height); for (let i = 0; i < cols; i++) { for (let j = 0; j < rows; j++) { let x = i * res; let y = j * res; if (grid[i][j] == 1) { c.fillStyle = 'black'; c.strokeStyle = 'white'; c.fillRect(x, y, res - 1, res - 1); } } } let next = array2D(cols, rows); for (let i = 0; i < cols; i++) { for (let j = 0; j < rows; j++) { let state = grid[i][j]; let neighbors = countNeighbors(grid, i, j); if (state === 0 && neighbors === 3) { next[i][j] = 1; } else if (state === 1 && !(neighbors === 2 || neighbors === 3)) { next[i][j] = 0; } else { next[i][j] = state; } } } grid = next; } function countNeighbors(grid, x, y) { let sum = 0; for (let i = -1; i < 2; i++) { for (let j = -1; j < 2; j++) { let col = (x + i + cols) % cols; let row = (y + j + rows) % rows; sum += grid[col][row]; } } sum -= grid[x][y]; return sum; } window.onload = () => { setInterval(draw, 1000 / 10); };
CSS
canvas { background-color: white; max-height: 100%; max-width: 100%; height: 95vmin; width: 95vmin; box-sizing: border-box; }