Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 44.78 KB | None | 0 0
  1. /*Поиск пути*/
  2. function aOneHand(lab, io, type) {
  3.  
  4. let matrix = [];
  5. for (let j = 0; j < lab.length; j++) {
  6. matrix[j] = [];
  7. for (let n = 0; n < lab[1].length; n++) {
  8. if (lab[j][n] === 'wall')
  9. matrix[j][n] = {
  10. y: j,
  11. x: n,
  12. label: undefined,
  13. wall: true
  14. };
  15. else
  16. matrix[j][n] = {
  17. y: j,
  18. x: n,
  19. label: undefined,
  20. wall: false
  21. };
  22. }
  23. }
  24.  
  25. /*Проверка на валидность*/
  26. let validCell = function (y, x) {
  27. if (y < 0 || x < 0 || y >= lab.length || x >= lab[1].length || matrix[y][x].wall === true)
  28. return false;
  29. else return true;
  30. };
  31.  
  32. let y = io.enter[0];
  33. let x = io.enter[1];
  34.  
  35. matrix[y][x].label = true;
  36.  
  37. let stack = [];
  38. let current = {};
  39.  
  40. if (type === 'dynamic-time') {
  41. let intervalID = setInterval(function () {
  42. if ((validCell(y - 1, x) && matrix[y - 1][x].label === undefined) || (validCell(y + 1, x) && matrix[y + 1][x].label === undefined) || (validCell(y, x - 1) && matrix[y][x - 1].label === undefined) || (validCell(y, x + 1) && matrix[y][x + 1].label === undefined)) {
  43. stack.push(matrix[y][x]);
  44. if (/*!$('#' + y + '-' + x).hasClass("start") && */!$('#' + y + '-' + x).hasClass('finish')) {
  45. $('#' + y + '-' + x).addClass("foot");
  46. }
  47. $('#' + y + '-' + x).removeClass('me');
  48. if (validCell(y, x - 1) && matrix[y][x - 1].label === undefined) {
  49. x = x - 1;
  50. } else if (validCell(y + 1, x) && matrix[y + 1][x].label === undefined) {
  51. y = y + 1;
  52. } else if (validCell(y, x + 1) && matrix[y][x + 1].label === undefined) {
  53. x = x + 1;
  54. } else {
  55. y = y - 1;
  56. }
  57. matrix[y][x].label = true;
  58. $('#' + y + '-' + x).addClass('me');
  59. } else if (stack.length !== 0) {
  60. current = stack.pop();
  61. $('#' + y + '-' + x).removeClass('me');
  62. $('#' + y + '-' + x).addClass("blue");
  63. y = parseInt(current.y);
  64. x = parseInt(current.x);
  65. $('#' + y + '-' + x).addClass("me");
  66. } else {
  67. console.log('Выхода нет... Скоро рассвет. Ключ поверни и по-ле-те-ли.');
  68. clearInterval(intervalID);
  69. }
  70. if ($('#' + y + '-' + x).hasClass('finish')) {
  71. clearInterval(intervalID);
  72. }
  73. }, $('#OH-Interval').val());
  74. } else {
  75. /*Пока не найден выход*/
  76. for (;!$('#' + y + '-' + x).hasClass('finish');) {
  77. /*Если текущая клетка имеет непосещенных «соседей»*/
  78. if ((validCell(y - 1, x) && matrix[y - 1][x].label === undefined) || (validCell(y + 1, x) && matrix[y + 1][x].label === undefined) || (validCell(y, x - 1) && matrix[y][x - 1].label === undefined) || (validCell(y, x + 1) && matrix[y][x + 1].label === undefined)) {
  79. stack.push(matrix[y][x]);
  80. if (/*!$('#' + y + '-' + x).hasClass("start") && */!$('#' + y + '-' + x).hasClass('finish')) {
  81. $('#' + y + '-' + x).addClass("foot");
  82. }
  83. $('#' + y + '-' + x).removeClass('me');
  84. if (validCell(y, x - 1) && matrix[y][x - 1].label === undefined) {
  85. x = x - 1;
  86. } else if (validCell(y + 1, x) && matrix[y + 1][x].label === undefined) {
  87. y = y + 1;
  88. } else if (validCell(y, x + 1) && matrix[y][x + 1].label === undefined) {
  89. x = x + 1;
  90. } else {
  91. y = y - 1;
  92. }
  93. matrix[y][x].label = true;
  94. $('#' + y + '-' + x).addClass('me');
  95. } else if (stack.length !== 0) {
  96. current = stack.pop();
  97. $('#' + y + '-' + x).removeClass('me');
  98. $('#' + y + '-' + x).addClass("blue");
  99. y = parseInt(current.y);
  100. x = parseInt(current.x);
  101. } else {
  102. console.log('Выхода нет... Скоро рассвет. Ключ поверни и по-ле-те-ли.');
  103. break;
  104. }
  105. }
  106. }
  107.  
  108. }
  109. /*Поиск пути*/
  110. function aTrace(lab, io, timeout) {
  111. /*Алгоритм-трассировка*/
  112. /*Инициализация*/
  113. let matrix = [];
  114. let str = '';
  115.  
  116. for (let j = 0; j < lab.length; j++) {
  117. matrix[j] = [];
  118. for (let n = 0; n < lab[1].length; n++) {
  119. if (lab[j][n] === 'wall')
  120. matrix[j][n] = {
  121. y: j,
  122. x: n,
  123. label: undefined,
  124. wall: true
  125. };
  126. else
  127. matrix[j][n] = {
  128. y: j,
  129. x: n,
  130. label: undefined,
  131. wall: false
  132. };
  133. str = str + matrix[j][n].wall + ' ';
  134. }
  135. console.log(str);
  136. str = '';
  137. }
  138.  
  139. /*Функция проверки ячейки*/
  140. let checkCell = function (cell) {
  141. //console.log(cell);
  142. if (cell !== undefined) {
  143. if (cell.wall === false && cell.label === undefined) {
  144. // cell.label = label;
  145. return true;
  146. } else return false;
  147. } else return false;
  148. };
  149.  
  150. /*Проверка на валидность*/
  151. let validCell = function (y, x) {
  152. if (y < 0 || x < 0 || y >= lab.length || x >= lab[1].length)
  153. return false;
  154. else return true;
  155. };
  156.  
  157. /*Присваивание div метки*/
  158. function setDivLabel(y, x, label) {
  159. $("#" + y + '-' + x + '-label').text(label);
  160. }
  161.  
  162. /*Присваиваем метки*/
  163. function setLabel(y, x, label) {
  164. setTimeout(function () {
  165. matrix[y][x].label = label;
  166. setDivLabel(y, x, label);
  167. console.log(matrix[y][x].label);
  168. label = label + 1;
  169. if (validCell(y - 1, x) && checkCell(matrix[y - 1][x])) {
  170. setLabel(y - 1, x, label);
  171. }
  172. if (validCell(y + 1, x) && checkCell(matrix[y + 1][x])) {
  173. setLabel(y + 1, x, label);
  174. }
  175. if (validCell(y, x - 1) && checkCell(matrix[y][x - 1])) {
  176. setLabel(y, x - 1, label);
  177. }
  178. if (validCell(y, x + 1) && checkCell(matrix[y][x + 1])) {
  179. setLabel(y, x + 1, label);
  180. }
  181. label = label - 1;
  182. if ($('#' + y + '-' + x).hasClass('finish')) {
  183. trace(io.exit[0], io.exit[1]);
  184. }
  185. }, timeout);
  186. }
  187.  
  188. setLabel(io.enter[0], io.enter[1], 0);
  189.  
  190. /*Восстанавливаем путь*/
  191. let path = [];
  192.  
  193. function trace(y, x) {
  194. setTimeout(function () {
  195. path.push(matrix[y][x]);
  196. if (!$("#" + y + "-" + x).hasClass('finish')) {
  197. $("#" + y + "-" + x).addClass("foot");
  198. }
  199. if (matrix[y][x].label !== 0) {
  200. if (validCell(y + 1, x) && matrix[y + 1][x].label === matrix[y][x].label - 1) {
  201. trace(y + 1, x);
  202. }
  203. if (validCell(y, x - 1) && matrix[y][x - 1].label === matrix[y][x].label - 1) {
  204. trace(y, x - 1);
  205. }
  206.  
  207. if (validCell(y - 1, x) && matrix[y - 1][x].label === matrix[y][x].label - 1) {
  208. trace(y - 1, x);
  209. }
  210. if (validCell(y, x + 1) && matrix[y][x + 1].label === matrix[y][x].label - 1) {
  211. trace(y, x + 1);
  212. }
  213. }
  214. }, timeout);
  215. }
  216.  
  217. //trace(io.exit[0], io.exit[1]);
  218. }
  219. let lab;
  220. let objMaze = {};
  221. let io = {};
  222.  
  223. $('#btn-gen').click(function () {
  224. $('#select-themes').prop('disabled', false);
  225. $('#btn-auto').prop('disabled', false);
  226. $('#btn-manual').prop('disabled', false);
  227.  
  228. $('#btn-manual-apply').prop('disabled', true);
  229. /*aOneHand Block*/
  230. $('#OH-Interval').prop('disabled', true);
  231. $('#btn-aOneHand-Dynamic-Time').prop('disabled', true);
  232. $('#btn-aOneHand-Static').prop('disabled', true);
  233. /**/
  234. /*aTrace Block*/
  235. $('#Trace-Timeout').prop('disabled', true);
  236. $('#btn-aTrace-Timeout').prop('disabled', true);
  237. $('#btn-aTrace-Static').prop('disabled', true);
  238. /**/
  239. $('#btn-save').prop('disabled', true);
  240.  
  241. let width = parseInt($('#width').val()) + 2;
  242. let height = parseInt($('#height').val()) + 2;
  243. lab = genLab(width, height);
  244. drawLab(lab);
  245. selectIOManual(lab, io);
  246. });
  247.  
  248. $('#btn-auto').click(function () {
  249. /*aOneHand Block*/
  250. $('#OH-Interval').prop('disabled', false);
  251. $('#btn-aOneHand-Dynamic-Time').prop('disabled', false);
  252. $('#btn-aOneHand-Static').prop('disabled', false);
  253. /**/
  254. /*aTrace Block*/
  255. $('#Trace-Timeout').prop('disabled', false);
  256. $('#btn-aTrace-Timeout').prop('disabled', false);
  257. $('#btn-aTrace-Static').prop('disabled', false);
  258. /**/
  259.  
  260. $('#btn-save').prop('disabled', false);
  261.  
  262. $('#btn-auto').prop('disabled', true);
  263. $('#btn-manual').prop('disabled', true);
  264. $('#btn-manual-apply').prop('disabled', true);
  265.  
  266. $('.wall').unbind();
  267. io = selectIOAuto(lab);
  268. setIO(lab, io);
  269. meWalker(lab, io);
  270. });
  271.  
  272. // $('#btn-manual').click(function () {
  273. // $('#btn-auto').prop('disabled', true);
  274. // $('#btn-manual').prop('disabled', true);
  275. // $('#btn-manual-apply').prop('disabled', false);
  276. //
  277. // selectIOManual(lab, io);
  278. // });
  279.  
  280. $('#btn-manual-apply').click(function () {
  281. /*aOneHand Block*/
  282. $('#OH-Interval').prop('disabled', false);
  283. $('#btn-aOneHand-Dynamic-Time').prop('disabled', false);
  284. $('#btn-aOneHand-Static').prop('disabled', false);
  285. /**/
  286. /*aTrace Block*/
  287. $('#Trace-Timeout').prop('disabled', false);
  288. $('#btn-aTrace-Timeout').prop('disabled', false);
  289. $('#btn-aTrace-Static').prop('disabled', false);
  290. /**/
  291. $('#btn-save').prop('disabled', false);
  292.  
  293. $('#btn-manual-apply').prop('disabled', true);
  294.  
  295. console.log(io);
  296. setIO(lab, io);
  297. meWalker(lab, io);
  298. });
  299.  
  300. $('#btn-aOneHand-Static').click(function () {
  301. aOneHand(lab, io, 'static');
  302. });
  303.  
  304. $('#btn-aOneHand-Dynamic-Time').click(function () {
  305. aOneHand(lab, io, 'dynamic-time');
  306. });
  307.  
  308.  
  309. $('#btn-aTrace-Timeout').click(function () {
  310. aTrace(lab, io, $('#Trace-Timeout').val());
  311. });
  312.  
  313. $('#btn-aTrace-Static').click(function () {
  314. aTrace(lab, io, 0);
  315. });
  316.  
  317. $(function () {
  318. $('.b-popup').hide();
  319. $('#btn-auto').prop('disabled', true);
  320. $('#btn-manual').prop('disabled', true);
  321. $('#btn-manual-apply').prop('disabled', true);
  322. $('#select-themes').prop('disabled', true);
  323. /*aOneHand Block*/
  324. $('#OH-Interval').prop('disabled', true);
  325. $('#btn-aOneHand-Dynamic-Time').prop('disabled', true);
  326. $('#btn-aOneHand-Static').prop('disabled', true);
  327. /**/
  328. /*aTrace Block*/
  329. $('#Trace-Timeout').prop('disabled', true);
  330. $('#btn-aTrace-Timeout').prop('disabled', true);
  331. $('#btn-aTrace-Static').prop('disabled', true);
  332. /**/
  333. $('#btn-save').prop('disabled', true);
  334. });
  335.  
  336. $('#btn-save').click(function () {
  337. $('.b-popup').show();
  338. //$('.b-popup-content').append($('<button></button>').text('Cancel').attr('id', 'btn-cancel-save'));
  339. $('#btn-cancel-save').click(function () {
  340. $('.b-popup').hide();
  341. });
  342.  
  343. $('#btn-save-apply').click(function () {
  344. objMaze.name = $('#labName').val();
  345. objMaze.theme = $('#select-themes').val();
  346. objMaze.enter = io.enter;
  347. objMaze.exit = io.exit;
  348. objMaze.maze = lab;
  349.  
  350. let jsonMaze = JSON.stringify(objMaze);
  351.  
  352. $.ajax({
  353. type: 'POST',
  354. url: '/',
  355. headers: {'button': 'save'},
  356. contentType: 'application/json',
  357. data: jsonMaze
  358. })
  359. .done(function () {
  360. alert('Maze saved.');
  361. $('.b-popup').hide();
  362. });
  363. });
  364. });
  365.  
  366.  
  367. $('#btn-load').click(function () {
  368. let jqXHR = $.ajax({
  369. type: 'POST',
  370. url: '/getDocuments'
  371. })
  372. .done(function () {
  373. $('body').append($('<div></div>').addClass('b-popup-load').append($('<div></div>').addClass('b-popup-labs')));
  374. $('.b-popup-labs').append($('<div></div>').addClass('rowLabHeader').append($('<span></span>').text('Name').addClass('name')).append($('<span></span>').text('Theme').addClass('theme')).append($('<span></span>').text('Size').addClass('size')));
  375. let docs = JSON.parse(jqXHR.responseText);
  376. for (let i = 0; i < docs.length; i++) {
  377. $('.b-popup-labs').append($('<div></div>').attr('id', docs[i]._id).addClass('rowLab'));
  378. $('#' + docs[i]._id).append($('<span></span>').text(docs[i].name).addClass('name')).append($('<span></span>').text(docs[i].theme).addClass('theme')).append($('<span></span>').text(Number(docs[i].maze.length - 2) + 'x' + Number(docs[i].maze[1].length - 2)).addClass('size'));
  379. }
  380. $('.b-popup-labs').append($('<button></button>').text('Cancel').attr('id', 'btn-cancel-load'));
  381. console.log(JSON.parse(jqXHR.responseText));
  382.  
  383. $('#btn-cancel-load').click(function () {
  384. $('.b-popup-load').remove();
  385. });
  386.  
  387. $('.rowLab').click(function () {
  388. let id = $(this).attr('id');
  389. let jqXHR = $.ajax({
  390. type: 'POST',
  391. url: '/',
  392. headers: {'button': 'load'},
  393. data: {
  394. id: id
  395. }
  396. })
  397. .done(function () {
  398. console.log(JSON.parse(jqXHR.responseText));
  399. objMaze = JSON.parse(jqXHR.responseText);
  400. lab = objMaze.maze;
  401. io.enter = objMaze.enter;
  402. io.exit = objMaze.exit;
  403. drawLab(lab);
  404. drawIO(io);
  405. $('.b-popup-load').remove();
  406. $('#select-themes').val(objMaze.theme);
  407. if (objMaze.theme === 'Stone') {
  408. $('#theme').attr('href', '/stylesheets/themes/theme_stone.css');
  409. }
  410. if (objMaze.theme === 'Sand') {
  411. $('#theme').attr('href', '/stylesheets/themes/theme_sand.css');
  412. }
  413. if (objMaze.theme === 'Wood') {
  414. $('#theme').attr('href', '/stylesheets/themes/theme_wood.css');
  415. }
  416. if (objMaze.theme === 'Dirt') {
  417. $('#theme').attr('href', '/stylesheets/themes/theme_dirt.css');
  418. }
  419.  
  420. $('#select-themes').prop('disabled', false);
  421. $('#btn-auto').prop('disabled', true);
  422. $('#btn-manual').prop('disabled', true);
  423. $('#btn-manual-apply').prop('disabled', true);
  424.  
  425. /*aOneHand Block*/
  426. $('#OH-Interval').prop('disabled', false);
  427. $('#btn-aOneHand-Dynamic-Time').prop('disabled', false);
  428. $('#btn-aOneHand-Static').prop('disabled', false);
  429. /**/
  430.  
  431. /*aTrace Block*/
  432. $('#Trace-Timeout').prop('disabled', false);
  433. $('#btn-aTrace-Timeout').prop('disabled', false);
  434. $('#btn-aTrace-Static').prop('disabled', false);
  435. /**/
  436. $('#btn-save').prop('disabled', true);
  437. })
  438. .fail(function () {
  439. alert(jqXHR.statusText);
  440. })
  441. .always(function () {
  442. });
  443. });
  444. });
  445.  
  446.  
  447. });
  448. $(function () {
  449. $('#label-width').text('Width: ' + $('#width').val());
  450. $('#label-height').text('Height: ' + $('#height').val());
  451. $('#width').change(function () {
  452. $('#label-width').text('Width: ' + $('#width').val());
  453. });
  454. $('#height').change(function () {
  455. $('#label-height').text('Height: ' + $('#height').val());
  456. });
  457.  
  458. $('#label-OH-Time').text('Interval: ' + $('#OH-Interval').val() + ' ms');
  459. $('#OH-Interval').change(function () {
  460. $('#label-OH-Time').text('Interval: ' + $('#OH-Interval').val() + ' ms');
  461. });
  462.  
  463. $('#label-Trace-Timeout').text('Timeout: ' + $('#Trace-Timeout').val() + ' ms');
  464. $('#Trace-Timeout').change(function () {
  465. $('#label-Trace-Timeout').text('Interval: ' + $('#Trace-Timeout').val() + ' ms');
  466. });
  467.  
  468.  
  469.  
  470.  
  471. $("select").change(function () {
  472. if ($(this).val() === 'Stone') {
  473. $('#theme').attr('href', '/stylesheets/themes/theme_stone.css');
  474. // $('.block').attr('background-image', 'url("/images/Gray_Brick_Wall.png")');
  475. // $('.wall').attr('background-image', 'url("/images/Gray_Brick.png")');
  476. // $('.block').removeClass('yellow_stucco_wall', 'dirt-wall', 'wood-wall').addClass('gray-brick-wall');
  477. // $('.wall').removeClass('sand-block', 'dirt-block', 'wood-block').addClass('gray-brick');
  478. }
  479. if ($(this).val() === 'Sand') {
  480. $('#theme').attr('href', '/stylesheets/themes/theme_sand.css');
  481. // $('.block').attr('background-image', 'url(/images/Yellow_Stucco_Wall.png)');
  482. // $('.wall').attr('background-image', 'url("/images/Gray_Brick.png")');
  483. // $('.block').removeClass('gray-brick-wall', 'dirt-wall', 'wood-wall').addClass('yellow_stucco_wall');
  484. // $('.wall').removeClass('gray-brick', 'dirt-block', 'wood-block').addClass('sand-block');
  485. }
  486. if ($(this).val() === 'Wood') {
  487. $('#theme').attr('href', '/stylesheets/themes/theme_wood.css');
  488. // $('.block').attr('background-image', 'url(/images/Wood_Wall.png)');
  489. // $('.wall').attr('background-image', 'url(/images/Wood.png)');
  490. // $('.block').removeClass('yellow_stucco_wall', 'dirt-wall', 'gray-brick-wall').addClass('wood-wall');
  491. // $('.wall').removeClass('sand-block', 'dirt-block', 'gray-brick').addClass('wood');
  492. }
  493. if ($(this).val() === 'Dirt') {
  494. $('#theme').attr('href', '/stylesheets/themes/theme_dirt.css');
  495. // $('.block').removeClass('yellow_stucco_wall', 'gray-brick-wall', 'wood-wall').addClass('dirt-wall');
  496. // $('.wall').removeClass('sand-block', 'gray-brick', 'wood-block').addClass('dirt-block');
  497. }
  498. });
  499.  
  500.  
  501. //Login
  502. $('.auth-form').on('submit', function () {
  503. const form = $(this);
  504.  
  505. const jqXHR = $.ajax({
  506. url: '/login',
  507. type: 'POST',
  508. data: form.serialize()
  509. })
  510. .done(function () {
  511. alert("success");
  512. window.location.href = "/";
  513. })
  514. .fail(function () {
  515. alert(JSON.parse(jqXHR.responseText));
  516. })
  517. .always(function () {
  518. alert("complete");
  519. });
  520. return false;
  521. });
  522.  
  523. $('#logout').click(function () {
  524. $.post("/logout", function () {
  525. window.location.href = "/login";
  526. alert("success");
  527. })
  528. .fail(function () {
  529. alert("error");
  530. });
  531. return false;
  532. });
  533.  
  534. $('#btn-about').click(function () {
  535. $('.b-popup').show();
  536. $('.b-popup-content').hide();
  537. $('.about').show();
  538. });
  539.  
  540. $('#btn-in-about-ok').click(function () {
  541. $('.about').hide();
  542. $('.b-popup').hide();
  543. $('.b-popup-content').show();
  544. })
  545. });
  546.  
  547. function meWalker(lab, io) {
  548. let currentPosition = io.enter;
  549. console.log(currentPosition);
  550.  
  551. $("body").on("keydown", function (event) {
  552. let newPosition = [currentPosition[0] + ((event.which - 39) % 2), currentPosition[1] + ((event.which - 38) % 2)];
  553. if (valid(newPosition[0], newPosition[1]) && lab[newPosition[0]][newPosition[1]] !== 'wall') {
  554. $("#" + currentPosition[0] + "-" + currentPosition[1]).removeClass("me");
  555. /*Путь*/
  556. if (!$("#" + newPosition[0] + "-" + newPosition[1]).hasClass("foot") && !$("#" + currentPosition[0] + "-" + currentPosition[1]).hasClass("start") && !$("#" + newPosition[0] + "-" + newPosition[1]).hasClass("start"))
  557. $("#" + currentPosition[0] + "-" + currentPosition[1]).addClass("foot");
  558. else $("#" + newPosition[0] + "-" + newPosition[1]).removeClass("foot");
  559. /*End Путь*/
  560. currentPosition = newPosition;
  561. $("#" + currentPosition[0] + "-" + currentPosition[1]).addClass("me");
  562. //if (currentPosition[0] == hate - 2 && currentPosition[1] == width - 2) document.getElementById('complete').setAttribute('style', 'display:block');
  563. }
  564. });
  565.  
  566. function valid(a, b) {
  567. return (a < lab.length && a >= 0 && b < lab[1].length && b >= 0);
  568. }
  569. }
  570.  
  571.  
  572.  
  573. function drawLab(lab) {
  574. $('#maze').empty().attr('style', 'height:' + lab.length * 25 + 'px; width:' + lab[1].length * 25 + 'px');
  575. for (let y = 0; y < lab.length; y++) {
  576. for (let x = 0; x < lab[y].length; x++) {
  577. if (lab[y][x] === 'wall') {
  578. $('#maze').append($("<div></div>").attr('id', y + '-' + x).addClass('wall'));
  579. } else {
  580. $('#maze').append($("<div></div>").attr('id', y + '-' + x).addClass('block'));
  581. }
  582. $("#" + y + "-" + x).append($("<div></div>").addClass('label').attr('id', y + '-' + x + '-label'));
  583. }
  584. }
  585. }
  586.  
  587. function genLab(w, h) {
  588. let lab = [];
  589. for (let i = 0; i < h; i++) {
  590. lab[i] = [];
  591. for (let j = 0; j < w; j++) {
  592. lab[i][j] = 'wall';
  593. }
  594. }
  595.  
  596. function valid(a, b) {
  597. return (a < h && a >= 0 && b < w && b >= 0);
  598. }
  599.  
  600. /*Проверка соседних стен*/
  601. function amaze(y, x, addBlockWalls) {
  602. lab[y][x] = 'maze';
  603. if (addBlockWalls && valid(y + 1, x) && (lab[y + 1][x] === 'wall')) walls.push([y + 1, x, [y, x]]);
  604. if (addBlockWalls && valid(y - 1, x) && (lab[y - 1][x] === 'wall')) walls.push([y - 1, x, [y, x]]);
  605. if (addBlockWalls && valid(y, x + 1) && (lab[y][x + 1] === 'wall')) walls.push([y, x + 1, [y, x]]);
  606. if (addBlockWalls && valid(y, x - 1) && (lab[y][x - 1] === 'wall')) walls.push([y, x - 1, [y, x]]);
  607. }
  608.  
  609. let currentPosition = [1, 1];
  610. let walls = [];
  611. amaze(currentPosition[0], currentPosition[1], true);
  612. while (walls.length !== 0) {
  613. let randomWall = walls[Math.floor(Math.random() * walls.length)],
  614. host = randomWall[2],
  615. opposite = [(host[0] + (randomWall[0] - host[0]) * 2), (host[1] + (randomWall[1] - host[1]) * 2)];
  616. if (valid(opposite[0], opposite[1])) {
  617. if (lab[opposite[0]][opposite[1]] === 'maze') walls.splice(walls.indexOf(randomWall), 1);
  618. else amaze(randomWall[0], randomWall[1], false), amaze(opposite[0], opposite[1], true);
  619. } else walls.splice(walls.indexOf(randomWall), 1);
  620. }
  621.  
  622. return lab;
  623. }
  624.  
  625. function toConsole(lab) {
  626. let row;
  627. for (let i = 0; i < lab.length; i++) {
  628. for (let j = 0; j < lab[i].length; j++) {
  629. row = row + lab[i][j] + ' ';
  630. }
  631. console.log(row);
  632. row = '';
  633. }
  634. }
  635.  
  636. function selectIOAuto(lab) {
  637. let io = {
  638. enter: [0, 1],
  639. exit: [lab.length - 2, lab[1].length - 1]
  640. };
  641. $('#' + io.enter[0] + '-' + io.enter[1]).removeClass('wall').addClass('start me');
  642. $('#' + io.exit[0] + '-' + io.exit[1]).removeClass('wall').addClass('finish');
  643.  
  644. return io;
  645. }
  646.  
  647. function selectIOManual(lab, io) {
  648. let toggler = 0;
  649. $('.wall').click(function () {
  650. let id = $(this).attr('id').split('-');
  651. let y = parseInt(id[0]);
  652. let x = parseInt(id[1]);
  653. let yDown = y + 1;
  654. let yUp = y - 1;
  655. let xRight = x + 1;
  656. let xLeft = x - 1;
  657. if ((y === 0 && !$('#' + yDown + '-' + x).hasClass('wall')) || (y === lab.length - 1 && !$('#' + yUp + '-' + x).hasClass('wall')) || (x === 0 && !$('#' + y + '-' + xRight).hasClass('wall')) || (x === lab[1].length - 1 && !$('#' + y + '-' + xLeft).hasClass('wall'))) {
  658. if (toggler === 0) {
  659. io.enter = [y, x];
  660. toggler = 1;
  661. $('#' + y + '-' + x).removeClass('wall').addClass('start me');
  662.  
  663. $('#btn-auto').prop('disabled', true);
  664. //$('#btn-manual').prop('disabled', true);
  665.  
  666. } else {
  667. io.exit = [y, x];
  668. toggler = 2;
  669. $('#' + y + '-' + x).removeClass('wall').addClass('finish');
  670. $('.wall').unbind();
  671.  
  672. $('#btn-manual-apply').prop('disabled', false);
  673. //return io;
  674. }
  675. } else alert('В данной точке нельзя установить вход или выход.');
  676. });
  677.  
  678. }
  679.  
  680. function setIO(lab, io) {
  681. lab[io.enter[0]][io.enter[1]] = 'maze'; //Добавление входа в массив, т.е. удаление его из массива стен
  682. lab[io.exit[0]][io.exit[1]] = 'maze';
  683. }
  684.  
  685. function drawIO(io) {
  686. $('#' + io.enter[0] + '-' + io.enter[1]).removeClass('wall').removeClass('block').addClass('start me');
  687. $('#' + io.exit[0] + '-' + io.exit[1]).removeClass('wall').removeClass('block').addClass('finish');
  688. }
  689.  
  690. CSS
  691. html, body {
  692. display: flex;
  693. align-items: center;
  694. justify-content: center;
  695. width: 100%;
  696. height: 100%;
  697. min-height: 100%;
  698. font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
  699. }
  700.  
  701. .auth {
  702. display: flex;
  703. flex-direction: column;
  704. align-items: center;
  705. color: #495057;
  706. border: 1px solid #495057;
  707. position: relative;
  708. width: 25%;
  709. height: 40%;
  710. box-shadow: 0 0 10px rgba(0,0,0,0.8); /* Параметры тени */
  711. }
  712.  
  713. .auth-form {
  714. display: flex;
  715. align-items: center;
  716. flex-direction: column;
  717. width: 80%;
  718. }
  719.  
  720. .auth-form input {
  721. text-align: center;
  722. height: 2rem;
  723. width: 100%;
  724. margin-bottom: 1rem;
  725. }
  726.  
  727. .auth-text {
  728. text-align: center;
  729. font-size: 24px;
  730. margin: 2rem;
  731. }
  732.  
  733.  
  734. .form-control:focus {
  735. color: #495057;
  736. background-color: #fff;
  737. border-color: #80bdff;
  738. outline: 0;
  739. box-shadow: 0 0 0 .2rem rgba(0,123,255,.25);
  740. }
  741. html {
  742. font-size: 16px;
  743. font-family: 'Major Mono Display', monospace;
  744. text-transform: lowercase;
  745. /*color: rgba(73, 80, 87, 1);*/
  746. color: rgba(0, 0, 0, 0.87);
  747. }
  748.  
  749. body {
  750. background-color: #f8f9fa;
  751. margin: 0;
  752. }
  753.  
  754. header {
  755. background: #ffffff;
  756. color: rgba(73, 80, 87, 0.6);
  757. height: 8%;
  758. display: flex;
  759. align-items: stretch;
  760. justify-content: space-between;
  761. padding: 0 1rem;
  762. box-shadow: 0 3px 5px rgba(57, 63, 72, 0.3);
  763. }
  764.  
  765. .username {
  766. margin: auto 0.5rem;
  767. }
  768.  
  769. main {
  770. width: 70%;
  771. margin: 0 auto;
  772. }
  773.  
  774. .container-maze {
  775. display: flex;
  776. margin: 2rem 0;
  777. }
  778.  
  779. .container-side {
  780. display: flex;
  781. flex-direction: column;
  782. width: 25%;
  783. }
  784.  
  785. .container-center {
  786. width: 50%;
  787. display: flex;
  788. justify-content: center;
  789. }
  790.  
  791. main button {
  792. font-family: 'Major Mono Display', monospace;
  793. text-transform: lowercase;
  794. height: 30px;
  795. }
  796.  
  797. .btn {
  798. cursor: pointer;
  799. }
  800.  
  801. .btn-link {
  802. border: 1px solid transparent;
  803. border-radius: 0.25rem;
  804. }
  805.  
  806. .btn-header {
  807. background: transparent;
  808. opacity: .6;
  809. }
  810.  
  811. .btn-header:hover {
  812. /*background-color: rgba(0, 0, 0, 0.5);*/
  813. opacity: 1;
  814. }
  815.  
  816. #maze {
  817. /*border-style: solid;*/
  818. }
  819.  
  820. .block {
  821. background-size: cover;
  822. float: left;
  823. height: 25px;
  824. width: 25px;
  825. }
  826.  
  827. .wall {
  828. background-size: cover;
  829. float: left;
  830. height: 25px;
  831. width: 25px;
  832. }
  833.  
  834. .label {
  835. position: absolute;
  836. font-size: 12px;
  837. color: white;
  838. z-index: 2;
  839. }
  840.  
  841. .invisible {
  842. display: none;
  843. }
  844.  
  845. .foot {
  846. position: relative;
  847. }
  848.  
  849. .foot:after {
  850. background-color: green;
  851. content: '';
  852. height: 20px;
  853. position: absolute;
  854. top: 0;
  855. width: 20px;
  856. }
  857.  
  858. .blue {
  859. position: relative;
  860. }
  861.  
  862. .blue:after {
  863. background-color: deepskyblue;
  864. content: '';
  865. height: 20px;
  866. position: absolute;
  867. top: 0;
  868. width: 20px;
  869. }
  870.  
  871. .me {
  872. position: relative;
  873. }
  874.  
  875. .me:after {
  876. content: '';
  877. background-repeat: no-repeat;
  878. background-size: contain;
  879. background-position: center;
  880. height: 25px;
  881. position: absolute;
  882. top: 0;
  883. max-width: 25px;
  884. width: 25px;
  885. }
  886.  
  887. .start {
  888. background-size: cover;
  889. float: left;
  890. height: 25px;
  891. width: 25px;
  892. }
  893.  
  894. .finish {
  895. background-image: url("/images/Exit.jpg");
  896. background-size: cover;
  897. float: left;
  898. height: 25px;
  899. width: 25px;
  900. }
  901.  
  902. #complete {
  903. display: none;
  904. height: 360px;
  905. left: 20%;
  906. position: absolute;
  907. right: 20%;
  908. top: 50px;
  909. width: 640px;
  910. z-index: 1000;
  911. }
  912.  
  913. #complete img {
  914. height: 100%;
  915. width: 100%;
  916. }
  917.  
  918. select {
  919. font-family: 'Major Mono Display', monospace;
  920. text-transform: lowercase;
  921. }
  922.  
  923. option {
  924. font-family: 'Major Mono Display', monospace;
  925. text-transform: lowercase;
  926. }
  927.  
  928. .dashed {
  929. display: flex;
  930. flex-direction: column;
  931. padding: 1rem;
  932. margin-bottom: 1.5rem;
  933. border: 1px dashed rgba(73, 80, 87, .6);
  934. }
  935.  
  936. .dashed * {
  937. margin: .5rem 0;
  938. }
  939.  
  940. .dashed *:first-child {
  941. margin-top: 0;
  942. }
  943.  
  944. .dashed *:last-child {
  945. margin-bottom: 0;
  946. }
  947.  
  948. .dashed-title {
  949. display: flex;
  950. justify-content: center;
  951. align-items: center;
  952. height: 30px;
  953. border-top: 1px dashed rgba(73, 80, 87, .6);
  954. border-left: 1px dashed rgba(73, 80, 87, .6);
  955. border-right: 1px dashed rgba(73, 80, 87, .6);
  956. }
  957.  
  958. .b-popup {
  959. width: 100%;
  960. min-height: 100%;
  961. background-color: rgba(0, 0, 0, 0.5);
  962. overflow: hidden;
  963. position: fixed;
  964. top: 0;
  965. display: flex;
  966. align-items: center;
  967. justify-content: center;
  968. text-transform: none;
  969. }
  970.  
  971. .b-popup .b-popup-content {
  972. font-family: 'Roboto', sans-serif;
  973. margin: auto;
  974. width: 20%;
  975. height: 20%;
  976. padding: 10px;
  977. background-color: #c5c5c5;
  978. box-shadow: 0 0 10px #000;
  979. }
  980.  
  981. .b-popup .about {
  982. font-family: 'Roboto', sans-serif;
  983. margin: auto;
  984. width: 35%;
  985. height: 35%;
  986. padding: 10px;
  987. background-color: #c5c5c5;
  988. box-shadow: 0 0 10px #000;
  989. }
  990.  
  991. .b-popup .about .about-title {
  992. display: flex;
  993. justify-content: center;
  994. align-items: center;
  995. height: 30px;
  996. border-bottom: 1px dashed rgba(73, 80, 87, .6);
  997. }
  998.  
  999. .b-popup-load {
  1000. width: 100%;
  1001. min-height: 100%;
  1002. background-color: rgba(0, 0, 0, 0.5);
  1003. overflow: hidden;
  1004. position: fixed;
  1005. top: 0;
  1006. display: flex;
  1007. align-items: center;
  1008. justify-content: center;
  1009. text-transform: none;
  1010. }
  1011.  
  1012. .b-popup-load .b-popup-labs {
  1013. font-family: 'Roboto', sans-serif;
  1014. display: flex;
  1015. flex-direction: column;
  1016. margin: auto;
  1017. width: 30%;
  1018. height: 60%;
  1019. padding: 10px;
  1020. background-color: #c5c5c5;
  1021. box-shadow: 0 0 10px #000;
  1022. }
  1023.  
  1024. .rowLabHeader {
  1025. display: flex;
  1026. flex-direction: row;
  1027. align-items: center;
  1028. border-bottom: 1px dashed rgba(73, 80, 87, .6);
  1029. }
  1030.  
  1031. .rowLab {
  1032. display: flex;
  1033. flex-direction: row;
  1034. border-bottom: 1px dashed rgba(73, 80, 87, .6);
  1035. cursor: pointer;
  1036. }
  1037.  
  1038. .rowLab:hover {
  1039. outline: 1px solid lightseagreen;
  1040. }
  1041.  
  1042. .name {
  1043. border-right: 1px dashed rgba(73, 80, 87, .6);
  1044. text-align: center;
  1045. min-width: 33.33%;
  1046. }
  1047.  
  1048. .theme {
  1049. border-right: 1px dashed rgba(73, 80, 87, .6);
  1050. text-align: center;
  1051. min-width: 33.33%;
  1052. }
  1053.  
  1054. .size {
  1055. text-align: center;
  1056. min-width: 33.33%;
  1057. }
  1058.  
  1059. EJS
  1060. <html>
  1061. <head>
  1062. <link rel="stylesheet" href='/stylesheets/main.css'>
  1063. <link id="theme" rel="stylesheet" href='/stylesheets/themes/theme_stone.css'>
  1064.  
  1065. <script
  1066. src="https://code.jquery.com/jquery-3.3.1.js"
  1067. integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  1068. crossorigin="anonymous"></script>
  1069. <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  1070. <link href="https://fonts.googleapis.com/css?family=Major+Mono+Display" rel="stylesheet">
  1071. <link href="https://fonts.googleapis.com/css?family=Roboto&amp;subset=cyrillic" rel="stylesheet">
  1072.  
  1073. </head>
  1074. <body>
  1075. <header>
  1076. <button id="btn-about" class="btn btn-link btn-header" type="button"><i class="fas fa-question fa-2x"></i></button>
  1077. <div class="username"><%= user.get('username') %></div><button id="logout" class="btn btn-link btn-header" type="button"><i class="fas fa-sign-out-alt fa-2x"></i></button>
  1078. </header>
  1079. <main>
  1080. <div class="container-maze">
  1081. <div class="container-side">
  1082. <div class="dashed-title">
  1083. Maze
  1084. </div>
  1085. <div class="dashed">
  1086. <label id="label-width" for="width">Width: 5</label>
  1087. <input id="width" type="range" min="5" max="15" step="2" value="5">
  1088.  
  1089. <label id="label-height" for="height">Height: 5</label>
  1090. <input id="height" type="range" min="5" max="15" step="2" value="5">
  1091.  
  1092. <button id="btn-gen" class="btn" type="button">Generate</button>
  1093. </div>
  1094.  
  1095. <div class="dashed-title">
  1096. Enter/Exit
  1097. </div>
  1098. <div class="dashed">
  1099. <button id="btn-auto" type="button">Auto</button>
  1100. <!--<button id="btn-manual" type="button">Manual</button>-->
  1101. <button id="btn-manual-apply" type="button">Manual Apply</button>
  1102.  
  1103. </div>
  1104. </div>
  1105.  
  1106. <div class="container-center">
  1107. <div id='maze'></div>
  1108. <div id='complete'>
  1109. MISSION ACCOMPLISHED
  1110. </div>
  1111. </div>
  1112.  
  1113. <div class="container-side">
  1114. <div class="dashed-title">
  1115. Theme
  1116. </div>
  1117. <div class="dashed">
  1118. <select id="select-themes" autocomplete="off">
  1119. <option selected value="Stone">Stone</option>
  1120. <option value="Sand">Sand</option>
  1121. <option value="Wood">Wood</option>
  1122. <option value="Dirt">Dirt</option>
  1123. </select>
  1124. </div>
  1125. <div class="dashed-title">
  1126. OneHand
  1127. </div>
  1128. <div id="aOneHand" class="dashed">
  1129. <label id="label-OH-Time" for="OH-Interval"></label>
  1130. <input id="OH-Interval" type="range" min="100" max="1000" step="100" value="100">
  1131.  
  1132. <button id="btn-aOneHand-Dynamic-Time" type="button">Dynamic Time</button>
  1133.  
  1134. <button id="btn-aOneHand-Static" type="button">Static</button>
  1135. </div>
  1136.  
  1137. <div class="dashed-title">
  1138. Trace
  1139. </div>
  1140. <div class="dashed">
  1141. <label id="label-Trace-Timeout" for="Trace-Timeout"></label>
  1142. <input id="Trace-Timeout" type="range" min="100" max="1000" step="100" value="100">
  1143.  
  1144. <button id="btn-aTrace-Timeout" type="button">Dynamic Time</button>
  1145. <button id="btn-aTrace-Static" type="button">Static</button>
  1146. </div>
  1147. </div>
  1148. </div>
  1149. <div style = "text-align: center;">
  1150. <button id="btn-save" type="button">save</button>
  1151. <button id="btn-load" type="button">load</button>
  1152. </div>
  1153.  
  1154. <script src='/javascripts/game.js' type="text/javascript"></script>
  1155. <script src='/javascripts/listener.js' type="text/javascript"></script>
  1156. <script src='/javascripts/aTrace.js' type="text/javascript"></script>
  1157. <script src='/javascripts/aOneHand.js' type="text/javascript"></script>
  1158.  
  1159. <script src="/javascripts/mazeGenerator.js" type="text/javascript"></script>
  1160.  
  1161.  
  1162. </main>
  1163. <div class="b-popup">
  1164. <div class="b-popup-content">
  1165. <span>Name</span>
  1166. <input id="labName" type="text">
  1167. <button id="btn-save-apply" type="button">Save</button>
  1168. <button id="btn-cancel-save" type="button">Cancel</button>
  1169. </div>
  1170. <div class="about">
  1171. <div class="about-title">Справка</div>
  1172. <p>Система генерирования структуры лабиринта и нахождение выхода из него</p>
  1173. <p>Для генерирования структуры лабиринта необходимо:</p>
  1174. <ol>
  1175. <li>Выбрать ширину и высоту лабиринта в блоке "Maze" и нажать кнопку "Generate".</li>
  1176. <li>Выбрать способ расстановки входа и выхода в блоке "Enter/Exit".</li>
  1177. <li>Выбрать тему лабиринта в блоке "Theme".</li>
  1178. <li>Выбрать один из алгоритмов нахождения пути и способов визуализации работы алгоритма.</li>
  1179. </ol>
  1180. <p>Для сохранения и загрузки лабиринта используются кнопки "Save" и "Load".</p>
  1181. <button id="btn-in-about-ok" type="button">OK</button>
  1182.  
  1183. </div>
  1184. </div>
  1185. <footer>
  1186.  
  1187. </footer>
  1188. </body>
  1189. </html>
  1190. <!DOCTYPE html>
  1191. <html lang='ru'>
  1192. <head>
  1193. <title></title>
  1194. <link rel='stylesheet' href='/stylesheets/login.css'/>
  1195. <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"
  1196. integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  1197. <script
  1198. src="https://code.jquery.com/jquery-3.3.1.js"
  1199. integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  1200. crossorigin="anonymous"></script>
  1201. </head>
  1202. <body>
  1203. <div class="auth">
  1204. <div class="auth-text">Авторизация</div>
  1205. <form class="auth-form">
  1206. <input name="username" type="text" id="inputLogin" placeholder="Логин...">
  1207.  
  1208. <input name="password" type="text" id="inputPassword" placeholder="Пароль...">
  1209.  
  1210. <!--<input type="text" id="inputPassword2" placeholder="Повторить пароль...">-->
  1211.  
  1212. <input type = "submit" data-loading-text="Проверка..." value = "Sign In">
  1213. </form>
  1214. </div>
  1215. <script src="/javascripts/listener.js"></script>
  1216. </body>
  1217. </html>
  1218.  
  1219. Models
  1220.  
  1221. var crypto = require('crypto');
  1222. var async = require('async');
  1223. var util = require('util');
  1224.  
  1225. const mongoose = require('../lib/mongoose'),
  1226. Schema = mongoose.Schema;
  1227.  
  1228. var schema = new Schema({
  1229. username: {
  1230. type: String,
  1231. unique: true, //уникальность
  1232. required: true //поле обязательно должно быть
  1233. },
  1234. hashedPassword: {
  1235. type: String,
  1236. required: true
  1237. },
  1238. salt: {
  1239. type: String,
  1240. required: true
  1241. },
  1242. created: {
  1243. type: Date,
  1244. default: Date.now
  1245. }
  1246. });
  1247.  
  1248. schema.methods.encryptPassword = function(password) {
  1249. return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
  1250. };
  1251.  
  1252. schema.virtual('password')
  1253. .set(function(password) {
  1254. this._plainPassword = password;
  1255. this.salt = Math.random() + '';
  1256. this.hashedPassword = this.encryptPassword(password);
  1257. })
  1258. .get(function() { return this._plainPassword; });
  1259.  
  1260.  
  1261. schema.methods.checkPassword = function(password) {
  1262. return this.encryptPassword(password) === this.hashedPassword;
  1263. };
  1264.  
  1265. schema.statics.authorize = function(username, password, callback) {
  1266. var User = this;
  1267.  
  1268. async.waterfall([
  1269. function(callback) {
  1270. User.findOne({username: username}, callback);
  1271. },
  1272. function(user, callback) {
  1273. if (user) {
  1274. if (user.checkPassword(password)) {
  1275. callback(null, user);
  1276. } else {
  1277. callback(new AuthError("Пароль неверен"));
  1278. }
  1279. } else {
  1280. var user = new User({username: username, password: password});
  1281. user.save(function(err) {
  1282. if (err) return callback(err);
  1283. callback(null, user);
  1284. });
  1285. }
  1286. }
  1287. ], callback);
  1288. };
  1289.  
  1290. exports.User = mongoose.model('User', schema);
  1291.  
  1292.  
  1293. function AuthError(message) {
  1294. Error.apply(this, arguments);
  1295. Error.captureStackTrace(this, AuthError);
  1296.  
  1297. this.message = message;
  1298. }
  1299.  
  1300. util.inherits(AuthError, Error);
  1301.  
  1302. AuthError.prototype.name = 'AuthError';
  1303.  
  1304. exports.AuthError = AuthError;
  1305.  
  1306.  
  1307. const createError = require('http-errors');
  1308. const mongoose = require('../lib/mongoose');
  1309.  
  1310. const mazeSchema = new mongoose.Schema({
  1311. name: {
  1312. type: String,
  1313. unique: true, //уникальность
  1314. required: true //поле обязательно должно быть
  1315. },
  1316. theme: String,
  1317. enter: Array,
  1318. exit: Array,
  1319. maze: [[]],
  1320. owner: {
  1321. type: mongoose.Schema.Types.ObjectId,
  1322. ref: 'User'
  1323. },
  1324. created: {
  1325. type: Date,
  1326. default: Date.now
  1327. }
  1328. });
  1329.  
  1330. exports.Maze = mongoose.model('Maze', mazeSchema);
  1331. Routes
  1332. var express = require('express');
  1333. var router = express.Router();
  1334. const User = require('../models/user.js').User;
  1335. const createError = require('http-errors');
  1336. var AuthError = require('../models/user').AuthError;
  1337.  
  1338.  
  1339. router.get('/', function (req, res) {
  1340. res.render('login');
  1341. });
  1342.  
  1343. router.post('/', function (req, res, next) {
  1344. var username = req.body.username;
  1345. var password = req.body.password;
  1346.  
  1347. User.authorize(username, password, function (err, user) {
  1348. if (err) {
  1349. if (err instanceof AuthError) {
  1350. return next(createError(403));
  1351. } else {
  1352. return next(err);
  1353. }
  1354. }
  1355.  
  1356. req.session.user = user._id;
  1357. res.send({});
  1358. });
  1359. });
  1360.  
  1361. module.exports = router;
  1362. const express = require('express');
  1363. const router = express.Router();
  1364. const createError = require('http-errors');
  1365. const checkAuth = require('../middleware/checkAuth');
  1366. const Maze = require('../models/modMaze.js').Maze;
  1367.  
  1368. router.get('/', checkAuth, function(req, res) {
  1369. res.render('index');
  1370. });
  1371.  
  1372. router.post('/', function (req, res) {
  1373. if (req.headers.button === 'save') {
  1374. let objMaze = req.body;
  1375. let maze = new Maze(
  1376. {
  1377. name: objMaze.name,
  1378. theme: objMaze.theme,
  1379. enter: objMaze.enter,
  1380. exit: objMaze.exit,
  1381. maze: objMaze.maze,
  1382. owner: req.session.user
  1383. }
  1384. );
  1385. maze.save(function (err) {
  1386. if (err) return createError(err);
  1387. });
  1388. res.setHeader('Status', 'Saved!');
  1389. res.send();
  1390. } else {
  1391. let id = req.body.id;
  1392. console.log(id);
  1393. Maze.findById(id, function (err, maze) {
  1394. if (err) {
  1395. createError(err);
  1396. } else {
  1397. console.log(maze);
  1398. res.json(maze);
  1399. }
  1400. });
  1401. }
  1402. });
  1403.  
  1404. router.post('/getDocuments', function (req, res) {
  1405. Maze.find({owner: req.session.user}, function (err, docs) {
  1406. if (err) {
  1407. createError(err);
  1408. } else {
  1409. res.json(docs);
  1410. }
  1411. });
  1412. });
  1413. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement