Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use struct'
- const height = 64;
- const width = 64;
- const cellColor = 'green';
- const noneColor = "rgba(255, 255, 255, 0.1)";
- APP = {};
- window.onload = () => {
- APP.canvas = document.getElementById('canvas');
- APP.context = APP.canvas.getContext('2d');
- const cell = new Array(height).fill(null).map(_ => new Array(width).fill(null).map(_ => Math.random() < 0.5));
- draw(update(cell));
- };
- const draw = (cell) => {
- const cellSize = {x: APP.canvas.width / width, y: APP.canvas.height / height};
- cell.forEach((y, p_y) => {
- y.forEach((x, p_x) => {
- APP.context.fillStyle = x ? cellColor : noneColor;
- APP.context.fillRect(p_x * cellSize.x, p_y * cellSize.y, cellSize.x, cellSize.y);
- });
- });
- setTimeout(() => draw(update(cell)), 10);
- };
- const update = (cells) => {
- const newCells = cells.map((w, y) => {
- return w.map((cell, x) => {
- const befor = getArrayBefor(cells, y).filter((_, n) => n >= x-1 && n <= x+1);
- const after = getArrayAfter(cells, y).filter((_, n) => n >= x-1 && n <= x+1);
- const left = cells[y].filter((_, n) => n == x-1);
- const right = cells[y].filter((_, n) => n == x+1);
- const counter = befor.reduce((acc, x) => x ? acc+1 : acc, 0) +
- after.reduce((acc, x) => x ? acc+1 : acc, 0) +
- left.reduce((acc, x) => x ? acc+1 : acc, 0) +
- right.reduce((acc, x) => x ? acc+1 : acc, 0);
- if (cell) {
- return counter == 2 || counter == 3;
- } else {
- return counter == 3;
- }
- });
- });
- return newCells;
- };
- const getArrayBefor = (arr, index) => {
- if (index > 0) return arr[index-1];
- else return [];
- };
- const getArrayAfter = (arr, index) => {
- if (index < arr.length-1) return arr[index+1];
- else return [];
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement