main.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const fs = require('fs');
  2. const readline = require('readline');
  3. const SCREEN_WIDTH = 40;
  4. function visible(line, reg, allLines) {
  5. const cursor = line.length;
  6. line += (cursor === reg -1 || cursor === reg || cursor === reg +1) ? '#' : ' ';
  7. if (cursor === SCREEN_WIDTH -1) {
  8. allLines.push(line);
  9. line = "";
  10. }
  11. return line;
  12. }
  13. function doColorize(lines, x, y, color) {
  14. if (!lines[x] || lines[x][y] !== true)
  15. return;
  16. lines[x][y] = color;
  17. doColorize(lines, x -1, y, color);
  18. doColorize(lines, x +1, y, color);
  19. doColorize(lines, x -1, y -1, color);
  20. doColorize(lines, x +1, y -1, color);
  21. doColorize(lines, x -1, y +1, color);
  22. doColorize(lines, x +1, y +1, color);
  23. doColorize(lines, x, y -1, color);
  24. doColorize(lines, x, y +1, color);
  25. }
  26. function colorize(lines) {
  27. const colors = [ '\033[31m', '\033[32m', '\033[33m', '\033[34m', '\033[35m', '\033[36m' ];
  28. let colorIndex = 0;
  29. for (let i =0; i < lines.length; ++i)
  30. for (let j =0; j < lines[i].length; ++j)
  31. if (lines[i][j] === true) {
  32. doColorize(lines, i, j, colors[colorIndex % colors.length] +'#');
  33. ++colorIndex;
  34. }
  35. }
  36. async function main() {
  37. let currentTick = 1;
  38. let register = 1;
  39. let sum = 0;
  40. let data = "";
  41. let allLines = [];
  42. for await (let line of readline.createInterface({ input: process.stdin })) {
  43. let tickInc = 1;
  44. let prevValue = register;
  45. if (!line || !line.length)
  46. continue;
  47. if (line.startsWith('addx ')) {
  48. data = visible(data, register, allLines);
  49. data = visible(data, register, allLines);
  50. register += parseInt(line.substring(5));
  51. tickInc = 2;
  52. } else {
  53. data = visible(data, register, allLines);
  54. }
  55. if ((20+currentTick+tickInc) %40 < tickInc) {
  56. let currentValue = (20+currentTick+tickInc) %40 === 0 ? register : prevValue;
  57. sum += ((tickInc+currentTick)-((tickInc+currentTick+20)%40)) * currentValue;
  58. }
  59. currentTick += tickInc;
  60. }
  61. allLines = allLines.map(i => (i.split('').map(x => x === '#')));
  62. colorize(allLines);
  63. allLines.forEach(i => console.log(i.map(i => i || ' ').join('')));
  64. console.log('\033[39msum: ', sum);
  65. };
  66. (main());