Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. 'use struct'
  2.  
  3. const height = 64;
  4. const width = 64;
  5. const cellColor = 'green';
  6. const noneColor = "rgba(255, 255, 255, 0.1)";
  7.  
  8. APP = {};
  9.  
  10. window.onload = () => {
  11. APP.canvas = document.getElementById('canvas');
  12. APP.context = APP.canvas.getContext('2d');
  13. const cell = new Array(height).fill(null).map(_ => new Array(width).fill(null).map(_ => Math.random() < 0.5));
  14. draw(update(cell));
  15. };
  16.  
  17. const draw = (cell) => {
  18. const cellSize = {x: APP.canvas.width / width, y: APP.canvas.height / height};
  19. cell.forEach((y, p_y) => {
  20. y.forEach((x, p_x) => {
  21. APP.context.fillStyle = x ? cellColor : noneColor;
  22. APP.context.fillRect(p_x * cellSize.x, p_y * cellSize.y, cellSize.x, cellSize.y);
  23. });
  24. });
  25. setTimeout(() => draw(update(cell)), 10);
  26. };
  27.  
  28. const update = (cells) => {
  29. const newCells = cells.map((w, y) => {
  30. return w.map((cell, x) => {
  31. const befor = getArrayBefor(cells, y).filter((_, n) => n >= x-1 && n <= x+1);
  32. const after = getArrayAfter(cells, y).filter((_, n) => n >= x-1 && n <= x+1);
  33. const left = cells[y].filter((_, n) => n == x-1);
  34. const right = cells[y].filter((_, n) => n == x+1);
  35. const counter = befor.reduce((acc, x) => x ? acc+1 : acc, 0) +
  36. after.reduce((acc, x) => x ? acc+1 : acc, 0) +
  37. left.reduce((acc, x) => x ? acc+1 : acc, 0) +
  38. right.reduce((acc, x) => x ? acc+1 : acc, 0);
  39. if (cell) {
  40. return counter == 2 || counter == 3;
  41. } else {
  42. return counter == 3;
  43. }
  44. });
  45. });
  46.  
  47. return newCells;
  48. };
  49.  
  50. const getArrayBefor = (arr, index) => {
  51. if (index > 0) return arr[index-1];
  52. else return [];
  53. };
  54.  
  55. const getArrayAfter = (arr, index) => {
  56. if (index < arr.length-1) return arr[index+1];
  57. else return [];
  58. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement