Github's Game of Life

Plays Conways' Game of Life with user's Github activity

当前为 2016-06-07 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Github's Game of Life
  3. // @namespace https://github.com/ryanml/Github-Game-of-Life/
  4. // @description Plays Conways' Game of Life with user's Github activity
  5. // @include https://github.com/*
  6. // @version 1.2
  7. // @grant GM_addStyle
  8. // ==/UserScript==
  9. (function() {
  10. // Constant hex values
  11. const INACTIVE_HEX = '#eeeeee';
  12. const ACTIVE_HEX_ARR = ['#d6e685', '#8cc665', '#44a340', '#1e6823'];
  13. // Interval by default is 200ms
  14. var IT_INTERVAL = 200;
  15. // Gets the <rect> wrapper tag <g> elements
  16. var columns = document.getElementsByTagName('g');
  17. var colDepth = 7;
  18. var play = false;
  19. var colorize = false;
  20. var generationCount = 0;
  21. var liveCellNum = 0;
  22. var fillColumnGaps = fillGaps();
  23. var ui = buildUI();
  24. var grid = buildGrid();
  25. var originalState = buildGrid();
  26. var fillGrid = fillGrid();
  27. // Builds grid of appropriate length
  28. function buildGrid() {
  29. var grid = [];
  30. for (col = 0; col < columns.length - 1; col++) {
  31. grid.push([]);
  32. }
  33. return grid;
  34. }
  35. // Resets grid to original state
  36. function resetGrid() {
  37. for (var x = 0; x < originalState.length; x++) {
  38. for (var y = 0; y < originalState[x].length; y++) {
  39. grid[x][y] = originalState[x][y][1];
  40. document.getElementById(x + ',' + y).setAttribute('fill', originalState[x][y][0]);
  41. }
  42. }
  43. document.getElementById('gol-info').innerHTML = '';
  44. }
  45. // Fills grid with initial states
  46. function fillGrid() {
  47. for (var y = 0; y < colDepth; y++) {
  48. for (var k = 1; k < columns.length; k++) {
  49. var x = k - 1;
  50. var cell = columns[k].children[y];
  51. cell.addEventListener('click', clickUpdateCell);
  52. cell.id = x + ',' + y;
  53. // If cell is default color (Not filled) push 0 to the grid, else 1
  54. var fill = cell.getAttribute('fill');
  55. var active = fill == INACTIVE_HEX ? 0 : 1;
  56. originalState[x].push([fill, active]);
  57. grid[x].push(active);
  58. }
  59. }
  60. }
  61. // Click event function for play/pause button. Starts and stops execution of the algorithm
  62. function controlSim() {
  63. if (!play) {
  64. this.id = 'pause';
  65. this.innerHTML = 'Pause';
  66. document.getElementById('gol-info').innerHTML = '';
  67. play = true;
  68. loop = setInterval(checkGrid, IT_INTERVAL);
  69. }
  70. else {
  71. this.id = 'play';
  72. this.innerHTML = 'Play';
  73. play = false;
  74. clearInterval(loop);
  75. }
  76. }
  77. // Applies one sweep of the algorithm to the grid
  78. function step() {
  79. if (!play) {
  80. checkGrid();
  81. }
  82. }
  83. // Sets all cells to dead (0)
  84. function clearGrid() {
  85. for (var x = 0; x < grid.length; x++) {
  86. for (var y = 0; y < grid[x].length; y++) {
  87. updateCellAt(x, y, grid[x][y] = 0);
  88. }
  89. }
  90. updateLiveCellCount();
  91. document.getElementById('gcc').innerHTML = (generationCount = 0);
  92. }
  93. // Updates the interval on change of the range input
  94. function updateInterval() {
  95. IT_INTERVAL = this.value == 0 ? ((this.value + 1) * 10) : (this.value * 10);
  96. // If animation is playing, set new interval loop
  97. if (play) {
  98. clearInterval(loop);
  99. loop = setInterval(checkGrid, IT_INTERVAL);
  100. }
  101. document.getElementById('icc').innerHTML = IT_INTERVAL;
  102. }
  103. // Returns the number of live cells in the grid
  104. function updateLiveCellCount() {
  105. liveCellNum = 0;
  106. for (var x = 0; x < grid.length; x++) {
  107. for (var y = 0; y < grid[x].length; y++) {
  108. if (grid[x][y] == 1) {
  109. liveCellNum++;
  110. }
  111. }
  112. }
  113. document.getElementById('lcc').innerHTML = liveCellNum;
  114. }
  115. // Checks if all cells are dead, displays message
  116. function checkForCellDeaths() {
  117. // Check for no cells
  118. if (liveCellNum == 0) {
  119. // If the simulation is being run it needs to stop
  120. if (play) {
  121. document.getElementById('pause').click();
  122. }
  123. document.getElementById('gol-info').innerHTML = ' - Mass Death! All your cells have died.';
  124. }
  125. }
  126. // Loops through grid and applies Conway's algorithm to cells
  127. function checkGrid() {
  128. for (var x = 0; x < grid.length; x++) {
  129. for (var y = 0; y < grid[x].length; y++) {
  130. var isAlive = grid[x][y] == 1 ? true : false;
  131. var nC = getNumNeighbors(x, y);
  132. if (isAlive && nC < 2) {
  133. grid[x][y] = 0;
  134. }
  135. else if (isAlive && nC == 2 || nC == 3) {
  136. grid[x][y] = 1;
  137. }
  138. else if (isAlive && nC > 3) {
  139. grid[x][y] = 0;
  140. }
  141. else if (!isAlive && nC == 3) {
  142. grid[x][y] = 1;
  143. }
  144. updateCellAt(x, y, grid[x][y]);
  145. }
  146. }
  147. updateLiveCellCount();
  148. checkForCellDeaths();
  149. document.getElementById('gcc').innerHTML = ++generationCount;
  150. }
  151. // Checks neighbors
  152. function getNumNeighbors(x, y) {
  153. // All possible coordinates of neighbors
  154. var fullCoords = [[x-1,y-1],[x,y-1],[x+1,y-1],[x+1,y],[x+1,y+1],[x,y+1],[x-1,y+1],[x-1,y]];
  155. var neighborCells = [];
  156. // Checks to make sure the coordinates aren't out of bounds, if not, push to neighborCells
  157. for (var f = 0; f < fullCoords.length; f++) {
  158. if (fullCoords[f][0] >= 0 && fullCoords[f][0] <= (grid.length - 1)
  159. && fullCoords[f][1] >= 0 && fullCoords[f][1] <= colDepth - 1) {
  160. neighborCells.push(grid[fullCoords[f][0]][fullCoords[f][1]]);
  161. }
  162. }
  163. // Adds neighBorCell values via reduce, each live cell is represented by 1
  164. return neighborCells.reduce((c, p) => c + p);
  165. }
  166. // Updates the <rect> markup at given coordinates
  167. function updateCellAt(x, y, newState) {
  168. var cell = document.getElementById(x + ',' + y);
  169. var stateHex = newState == 0 ? INACTIVE_HEX : genRandomHex();
  170. cell.setAttribute('fill', stateHex);
  171. }
  172. // Given a click event on the cell, sets grid at cell to opposite stateHex
  173. function clickUpdateCell() {
  174. var slc = this.id.split(',');
  175. var x = slc[0], y = slc[1];
  176. grid[x][y] = grid[x][y] == 0 ? 1 : 0;
  177. updateCellAt(x, y, grid[x][y]);
  178. updateLiveCellCount();
  179. }
  180. // Generates/gets the appropriate random hex value
  181. function genRandomHex() {
  182. var chars = 'ABCDEF0123456789';
  183. var hex = '#';
  184. if (!colorize) {
  185. return ACTIVE_HEX_ARR[Math.floor(Math.random() * ACTIVE_HEX_ARR.length)];
  186. }
  187. else {
  188. for (var n = 0; n < 6; n++) {
  189. hex += chars[Math.floor(Math.random() * chars.length)];
  190. }
  191. return hex;
  192. }
  193. }
  194. // Fills gaps in the markup
  195. function fillGaps() {
  196. // Gets the needed number of cells and most recent y value for first row
  197. var fCol = columns[1];
  198. var fNodes = fCol.children;
  199. var fCellNo = (colDepth - fNodes.length);
  200. var fCellY = fNodes[0].getAttribute('y');
  201. var nextfCellY = parseInt(fCellY) - 13;
  202. // Gets the needed number of cells and most recent y value for last row
  203. var lCol = columns[columns.length - 1];
  204. var lNodes = lCol.children;
  205. var lCellNo = (colDepth - lNodes.length);
  206. var lCellY = lNodes[lNodes.length - 1].getAttribute('y');
  207. var nextlCellY = parseInt(lCellY) + 13;
  208. for (f = 0; f < fCellNo; f++) {
  209. fCol.innerHTML = ('<rect class="day" width="11" height="11" y="' + nextfCellY + '" fill="' + INACTIVE_HEX + '"></rect>' + fCol.innerHTML);
  210. nextfCellY -= 13;
  211. }
  212. for (l = 0; l < lCellNo; l++) {
  213. lCol.innerHTML += '<rect class="day" width="11" height="11" y="' + nextlCellY + '" fill="' + INACTIVE_HEX + '"></rect>';
  214. nextlCellY += 13;
  215. }
  216. }
  217. // Sets colorize variable on change
  218. function setColorize() {
  219. colorize = this.checked ? true : false;
  220. }
  221. // Builds UI and adds it to the document.
  222. function buildUI() {
  223. // Appends needed <style> to <head>
  224. GM_addStyle(" .calendar-graph.days-selected rect.day { opacity: 1 !important; } " +
  225. " .gol-span { display: inline-block; width: 125px; margin: 0px 7px; } " +
  226. " .gol-button { margin: 0px 3px; width: 50px; height: 35px; border-radius: 5px; color: #ffffff; font-weight:bold; font-size: 11px; } " +
  227. " .gol-button:focus { outline: none; } " +
  228. " #play { background: #66ff33; border: 2px solid #208000; } " +
  229. " #pause { background: #ff4d4d; border: 2px solid #cc0000; } " +
  230. " #step { background: #0066ff; border: 2px solid #003380; } " +
  231. " #clear { background: #e6e600; border: 2px solid #b3b300; } " +
  232. " #reset { background: #ff9900; border: 2px solid #cc7a00; } " +
  233. " #gol-range-span { width: 190px; } " +
  234. " #gol-range-lbl { margin-right: 5px; } " +
  235. " #gol-range { vertical-align:middle; width: 100px; } ");
  236. // Contributions tab will be the parent div
  237. var overTab = document.getElementsByClassName('overview-tab')[0];
  238. var contAct = document.getElementsByClassName('js-contribution-activity')[0];
  239. contAct.style.display = 'none';
  240. // Control panel container
  241. var golCont = document.createElement('div');
  242. golCont.className = 'boxed-group flush';
  243. var markUp = "<h3>Github's Game of Life Control Panel <span id='gol-info' style='color:#ff0000'></span></h3>" +
  244. "<div class='boxed-group-inner' style='padding:10px'>" +
  245. "<button class='gol-button' id='play'>Play</button>" +
  246. "<button class='gol-button' id='step'>Step</button>" +
  247. "<button class='gol-button' id='clear'>Clear</button>" +
  248. "<button class='gol-button' id='reset'>Reset</button>" +
  249. "<span class='gol-span'><strong>Live Cell Count: </strong><span id='lcc'></span></span>" +
  250. "<span class='gol-span' style='width:105px'><strong>Generation: </strong><span id='gcc'>0</span></span>" +
  251. "<span class='gol-span' id='gol-range-span'>" +
  252. "<span id='gol-range-lbl'><strong>Int (ms): </strong><span id='icc'>200</span></span>" +
  253. "<input type='range' id='gol-range' value='20'/>" +
  254. "</span>" +
  255. "<input type='checkbox' id='color-check' style='vertical-align:middle'/>" +
  256. "</div>";
  257. golCont.innerHTML = markUp;
  258. overTab.insertBefore(golCont, contAct);
  259. // Add events
  260. document.getElementById('play').addEventListener('click', controlSim);
  261. document.getElementById('step').addEventListener('click', step);
  262. document.getElementById('clear').addEventListener('click', clearGrid);
  263. document.getElementById('gol-range').addEventListener('change', updateInterval);
  264. document.getElementById('color-check').addEventListener('change', setColorize);
  265. document.getElementById('reset').addEventListener('click', resetGrid);
  266. }
  267. })();