Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Поиск пути*/
- function aOneHand(lab, io, type) {
- let matrix = [];
- for (let j = 0; j < lab.length; j++) {
- matrix[j] = [];
- for (let n = 0; n < lab[1].length; n++) {
- if (lab[j][n] === 'wall')
- matrix[j][n] = {
- y: j,
- x: n,
- label: undefined,
- wall: true
- };
- else
- matrix[j][n] = {
- y: j,
- x: n,
- label: undefined,
- wall: false
- };
- }
- }
- /*Проверка на валидность*/
- let validCell = function (y, x) {
- if (y < 0 || x < 0 || y >= lab.length || x >= lab[1].length || matrix[y][x].wall === true)
- return false;
- else return true;
- };
- let y = io.enter[0];
- let x = io.enter[1];
- matrix[y][x].label = true;
- let stack = [];
- let current = {};
- if (type === 'dynamic-time') {
- let intervalID = setInterval(function () {
- 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)) {
- stack.push(matrix[y][x]);
- if (/*!$('#' + y + '-' + x).hasClass("start") && */!$('#' + y + '-' + x).hasClass('finish')) {
- $('#' + y + '-' + x).addClass("foot");
- }
- $('#' + y + '-' + x).removeClass('me');
- if (validCell(y, x - 1) && matrix[y][x - 1].label === undefined) {
- x = x - 1;
- } else if (validCell(y + 1, x) && matrix[y + 1][x].label === undefined) {
- y = y + 1;
- } else if (validCell(y, x + 1) && matrix[y][x + 1].label === undefined) {
- x = x + 1;
- } else {
- y = y - 1;
- }
- matrix[y][x].label = true;
- $('#' + y + '-' + x).addClass('me');
- } else if (stack.length !== 0) {
- current = stack.pop();
- $('#' + y + '-' + x).removeClass('me');
- $('#' + y + '-' + x).addClass("blue");
- y = parseInt(current.y);
- x = parseInt(current.x);
- $('#' + y + '-' + x).addClass("me");
- } else {
- console.log('Выхода нет... Скоро рассвет. Ключ поверни и по-ле-те-ли.');
- clearInterval(intervalID);
- }
- if ($('#' + y + '-' + x).hasClass('finish')) {
- clearInterval(intervalID);
- }
- }, $('#OH-Interval').val());
- } else {
- /*Пока не найден выход*/
- for (;!$('#' + y + '-' + x).hasClass('finish');) {
- /*Если текущая клетка имеет непосещенных «соседей»*/
- 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)) {
- stack.push(matrix[y][x]);
- if (/*!$('#' + y + '-' + x).hasClass("start") && */!$('#' + y + '-' + x).hasClass('finish')) {
- $('#' + y + '-' + x).addClass("foot");
- }
- $('#' + y + '-' + x).removeClass('me');
- if (validCell(y, x - 1) && matrix[y][x - 1].label === undefined) {
- x = x - 1;
- } else if (validCell(y + 1, x) && matrix[y + 1][x].label === undefined) {
- y = y + 1;
- } else if (validCell(y, x + 1) && matrix[y][x + 1].label === undefined) {
- x = x + 1;
- } else {
- y = y - 1;
- }
- matrix[y][x].label = true;
- $('#' + y + '-' + x).addClass('me');
- } else if (stack.length !== 0) {
- current = stack.pop();
- $('#' + y + '-' + x).removeClass('me');
- $('#' + y + '-' + x).addClass("blue");
- y = parseInt(current.y);
- x = parseInt(current.x);
- } else {
- console.log('Выхода нет... Скоро рассвет. Ключ поверни и по-ле-те-ли.');
- break;
- }
- }
- }
- }
- /*Поиск пути*/
- function aTrace(lab, io, timeout) {
- /*Алгоритм-трассировка*/
- /*Инициализация*/
- let matrix = [];
- let str = '';
- for (let j = 0; j < lab.length; j++) {
- matrix[j] = [];
- for (let n = 0; n < lab[1].length; n++) {
- if (lab[j][n] === 'wall')
- matrix[j][n] = {
- y: j,
- x: n,
- label: undefined,
- wall: true
- };
- else
- matrix[j][n] = {
- y: j,
- x: n,
- label: undefined,
- wall: false
- };
- str = str + matrix[j][n].wall + ' ';
- }
- console.log(str);
- str = '';
- }
- /*Функция проверки ячейки*/
- let checkCell = function (cell) {
- //console.log(cell);
- if (cell !== undefined) {
- if (cell.wall === false && cell.label === undefined) {
- // cell.label = label;
- return true;
- } else return false;
- } else return false;
- };
- /*Проверка на валидность*/
- let validCell = function (y, x) {
- if (y < 0 || x < 0 || y >= lab.length || x >= lab[1].length)
- return false;
- else return true;
- };
- /*Присваивание div метки*/
- function setDivLabel(y, x, label) {
- $("#" + y + '-' + x + '-label').text(label);
- }
- /*Присваиваем метки*/
- function setLabel(y, x, label) {
- setTimeout(function () {
- matrix[y][x].label = label;
- setDivLabel(y, x, label);
- console.log(matrix[y][x].label);
- label = label + 1;
- if (validCell(y - 1, x) && checkCell(matrix[y - 1][x])) {
- setLabel(y - 1, x, label);
- }
- if (validCell(y + 1, x) && checkCell(matrix[y + 1][x])) {
- setLabel(y + 1, x, label);
- }
- if (validCell(y, x - 1) && checkCell(matrix[y][x - 1])) {
- setLabel(y, x - 1, label);
- }
- if (validCell(y, x + 1) && checkCell(matrix[y][x + 1])) {
- setLabel(y, x + 1, label);
- }
- label = label - 1;
- if ($('#' + y + '-' + x).hasClass('finish')) {
- trace(io.exit[0], io.exit[1]);
- }
- }, timeout);
- }
- setLabel(io.enter[0], io.enter[1], 0);
- /*Восстанавливаем путь*/
- let path = [];
- function trace(y, x) {
- setTimeout(function () {
- path.push(matrix[y][x]);
- if (!$("#" + y + "-" + x).hasClass('finish')) {
- $("#" + y + "-" + x).addClass("foot");
- }
- if (matrix[y][x].label !== 0) {
- if (validCell(y + 1, x) && matrix[y + 1][x].label === matrix[y][x].label - 1) {
- trace(y + 1, x);
- }
- if (validCell(y, x - 1) && matrix[y][x - 1].label === matrix[y][x].label - 1) {
- trace(y, x - 1);
- }
- if (validCell(y - 1, x) && matrix[y - 1][x].label === matrix[y][x].label - 1) {
- trace(y - 1, x);
- }
- if (validCell(y, x + 1) && matrix[y][x + 1].label === matrix[y][x].label - 1) {
- trace(y, x + 1);
- }
- }
- }, timeout);
- }
- //trace(io.exit[0], io.exit[1]);
- }
- let lab;
- let objMaze = {};
- let io = {};
- $('#btn-gen').click(function () {
- $('#select-themes').prop('disabled', false);
- $('#btn-auto').prop('disabled', false);
- $('#btn-manual').prop('disabled', false);
- $('#btn-manual-apply').prop('disabled', true);
- /*aOneHand Block*/
- $('#OH-Interval').prop('disabled', true);
- $('#btn-aOneHand-Dynamic-Time').prop('disabled', true);
- $('#btn-aOneHand-Static').prop('disabled', true);
- /**/
- /*aTrace Block*/
- $('#Trace-Timeout').prop('disabled', true);
- $('#btn-aTrace-Timeout').prop('disabled', true);
- $('#btn-aTrace-Static').prop('disabled', true);
- /**/
- $('#btn-save').prop('disabled', true);
- let width = parseInt($('#width').val()) + 2;
- let height = parseInt($('#height').val()) + 2;
- lab = genLab(width, height);
- drawLab(lab);
- selectIOManual(lab, io);
- });
- $('#btn-auto').click(function () {
- /*aOneHand Block*/
- $('#OH-Interval').prop('disabled', false);
- $('#btn-aOneHand-Dynamic-Time').prop('disabled', false);
- $('#btn-aOneHand-Static').prop('disabled', false);
- /**/
- /*aTrace Block*/
- $('#Trace-Timeout').prop('disabled', false);
- $('#btn-aTrace-Timeout').prop('disabled', false);
- $('#btn-aTrace-Static').prop('disabled', false);
- /**/
- $('#btn-save').prop('disabled', false);
- $('#btn-auto').prop('disabled', true);
- $('#btn-manual').prop('disabled', true);
- $('#btn-manual-apply').prop('disabled', true);
- $('.wall').unbind();
- io = selectIOAuto(lab);
- setIO(lab, io);
- meWalker(lab, io);
- });
- // $('#btn-manual').click(function () {
- // $('#btn-auto').prop('disabled', true);
- // $('#btn-manual').prop('disabled', true);
- // $('#btn-manual-apply').prop('disabled', false);
- //
- // selectIOManual(lab, io);
- // });
- $('#btn-manual-apply').click(function () {
- /*aOneHand Block*/
- $('#OH-Interval').prop('disabled', false);
- $('#btn-aOneHand-Dynamic-Time').prop('disabled', false);
- $('#btn-aOneHand-Static').prop('disabled', false);
- /**/
- /*aTrace Block*/
- $('#Trace-Timeout').prop('disabled', false);
- $('#btn-aTrace-Timeout').prop('disabled', false);
- $('#btn-aTrace-Static').prop('disabled', false);
- /**/
- $('#btn-save').prop('disabled', false);
- $('#btn-manual-apply').prop('disabled', true);
- console.log(io);
- setIO(lab, io);
- meWalker(lab, io);
- });
- $('#btn-aOneHand-Static').click(function () {
- aOneHand(lab, io, 'static');
- });
- $('#btn-aOneHand-Dynamic-Time').click(function () {
- aOneHand(lab, io, 'dynamic-time');
- });
- $('#btn-aTrace-Timeout').click(function () {
- aTrace(lab, io, $('#Trace-Timeout').val());
- });
- $('#btn-aTrace-Static').click(function () {
- aTrace(lab, io, 0);
- });
- $(function () {
- $('.b-popup').hide();
- $('#btn-auto').prop('disabled', true);
- $('#btn-manual').prop('disabled', true);
- $('#btn-manual-apply').prop('disabled', true);
- $('#select-themes').prop('disabled', true);
- /*aOneHand Block*/
- $('#OH-Interval').prop('disabled', true);
- $('#btn-aOneHand-Dynamic-Time').prop('disabled', true);
- $('#btn-aOneHand-Static').prop('disabled', true);
- /**/
- /*aTrace Block*/
- $('#Trace-Timeout').prop('disabled', true);
- $('#btn-aTrace-Timeout').prop('disabled', true);
- $('#btn-aTrace-Static').prop('disabled', true);
- /**/
- $('#btn-save').prop('disabled', true);
- });
- $('#btn-save').click(function () {
- $('.b-popup').show();
- //$('.b-popup-content').append($('<button></button>').text('Cancel').attr('id', 'btn-cancel-save'));
- $('#btn-cancel-save').click(function () {
- $('.b-popup').hide();
- });
- $('#btn-save-apply').click(function () {
- objMaze.name = $('#labName').val();
- objMaze.theme = $('#select-themes').val();
- objMaze.enter = io.enter;
- objMaze.exit = io.exit;
- objMaze.maze = lab;
- let jsonMaze = JSON.stringify(objMaze);
- $.ajax({
- type: 'POST',
- url: '/',
- headers: {'button': 'save'},
- contentType: 'application/json',
- data: jsonMaze
- })
- .done(function () {
- alert('Maze saved.');
- $('.b-popup').hide();
- });
- });
- });
- $('#btn-load').click(function () {
- let jqXHR = $.ajax({
- type: 'POST',
- url: '/getDocuments'
- })
- .done(function () {
- $('body').append($('<div></div>').addClass('b-popup-load').append($('<div></div>').addClass('b-popup-labs')));
- $('.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')));
- let docs = JSON.parse(jqXHR.responseText);
- for (let i = 0; i < docs.length; i++) {
- $('.b-popup-labs').append($('<div></div>').attr('id', docs[i]._id).addClass('rowLab'));
- $('#' + 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'));
- }
- $('.b-popup-labs').append($('<button></button>').text('Cancel').attr('id', 'btn-cancel-load'));
- console.log(JSON.parse(jqXHR.responseText));
- $('#btn-cancel-load').click(function () {
- $('.b-popup-load').remove();
- });
- $('.rowLab').click(function () {
- let id = $(this).attr('id');
- let jqXHR = $.ajax({
- type: 'POST',
- url: '/',
- headers: {'button': 'load'},
- data: {
- id: id
- }
- })
- .done(function () {
- console.log(JSON.parse(jqXHR.responseText));
- objMaze = JSON.parse(jqXHR.responseText);
- lab = objMaze.maze;
- io.enter = objMaze.enter;
- io.exit = objMaze.exit;
- drawLab(lab);
- drawIO(io);
- $('.b-popup-load').remove();
- $('#select-themes').val(objMaze.theme);
- if (objMaze.theme === 'Stone') {
- $('#theme').attr('href', '/stylesheets/themes/theme_stone.css');
- }
- if (objMaze.theme === 'Sand') {
- $('#theme').attr('href', '/stylesheets/themes/theme_sand.css');
- }
- if (objMaze.theme === 'Wood') {
- $('#theme').attr('href', '/stylesheets/themes/theme_wood.css');
- }
- if (objMaze.theme === 'Dirt') {
- $('#theme').attr('href', '/stylesheets/themes/theme_dirt.css');
- }
- $('#select-themes').prop('disabled', false);
- $('#btn-auto').prop('disabled', true);
- $('#btn-manual').prop('disabled', true);
- $('#btn-manual-apply').prop('disabled', true);
- /*aOneHand Block*/
- $('#OH-Interval').prop('disabled', false);
- $('#btn-aOneHand-Dynamic-Time').prop('disabled', false);
- $('#btn-aOneHand-Static').prop('disabled', false);
- /**/
- /*aTrace Block*/
- $('#Trace-Timeout').prop('disabled', false);
- $('#btn-aTrace-Timeout').prop('disabled', false);
- $('#btn-aTrace-Static').prop('disabled', false);
- /**/
- $('#btn-save').prop('disabled', true);
- })
- .fail(function () {
- alert(jqXHR.statusText);
- })
- .always(function () {
- });
- });
- });
- });
- $(function () {
- $('#label-width').text('Width: ' + $('#width').val());
- $('#label-height').text('Height: ' + $('#height').val());
- $('#width').change(function () {
- $('#label-width').text('Width: ' + $('#width').val());
- });
- $('#height').change(function () {
- $('#label-height').text('Height: ' + $('#height').val());
- });
- $('#label-OH-Time').text('Interval: ' + $('#OH-Interval').val() + ' ms');
- $('#OH-Interval').change(function () {
- $('#label-OH-Time').text('Interval: ' + $('#OH-Interval').val() + ' ms');
- });
- $('#label-Trace-Timeout').text('Timeout: ' + $('#Trace-Timeout').val() + ' ms');
- $('#Trace-Timeout').change(function () {
- $('#label-Trace-Timeout').text('Interval: ' + $('#Trace-Timeout').val() + ' ms');
- });
- $("select").change(function () {
- if ($(this).val() === 'Stone') {
- $('#theme').attr('href', '/stylesheets/themes/theme_stone.css');
- // $('.block').attr('background-image', 'url("/images/Gray_Brick_Wall.png")');
- // $('.wall').attr('background-image', 'url("/images/Gray_Brick.png")');
- // $('.block').removeClass('yellow_stucco_wall', 'dirt-wall', 'wood-wall').addClass('gray-brick-wall');
- // $('.wall').removeClass('sand-block', 'dirt-block', 'wood-block').addClass('gray-brick');
- }
- if ($(this).val() === 'Sand') {
- $('#theme').attr('href', '/stylesheets/themes/theme_sand.css');
- // $('.block').attr('background-image', 'url(/images/Yellow_Stucco_Wall.png)');
- // $('.wall').attr('background-image', 'url("/images/Gray_Brick.png")');
- // $('.block').removeClass('gray-brick-wall', 'dirt-wall', 'wood-wall').addClass('yellow_stucco_wall');
- // $('.wall').removeClass('gray-brick', 'dirt-block', 'wood-block').addClass('sand-block');
- }
- if ($(this).val() === 'Wood') {
- $('#theme').attr('href', '/stylesheets/themes/theme_wood.css');
- // $('.block').attr('background-image', 'url(/images/Wood_Wall.png)');
- // $('.wall').attr('background-image', 'url(/images/Wood.png)');
- // $('.block').removeClass('yellow_stucco_wall', 'dirt-wall', 'gray-brick-wall').addClass('wood-wall');
- // $('.wall').removeClass('sand-block', 'dirt-block', 'gray-brick').addClass('wood');
- }
- if ($(this).val() === 'Dirt') {
- $('#theme').attr('href', '/stylesheets/themes/theme_dirt.css');
- // $('.block').removeClass('yellow_stucco_wall', 'gray-brick-wall', 'wood-wall').addClass('dirt-wall');
- // $('.wall').removeClass('sand-block', 'gray-brick', 'wood-block').addClass('dirt-block');
- }
- });
- //Login
- $('.auth-form').on('submit', function () {
- const form = $(this);
- const jqXHR = $.ajax({
- url: '/login',
- type: 'POST',
- data: form.serialize()
- })
- .done(function () {
- alert("success");
- window.location.href = "/";
- })
- .fail(function () {
- alert(JSON.parse(jqXHR.responseText));
- })
- .always(function () {
- alert("complete");
- });
- return false;
- });
- $('#logout').click(function () {
- $.post("/logout", function () {
- window.location.href = "/login";
- alert("success");
- })
- .fail(function () {
- alert("error");
- });
- return false;
- });
- $('#btn-about').click(function () {
- $('.b-popup').show();
- $('.b-popup-content').hide();
- $('.about').show();
- });
- $('#btn-in-about-ok').click(function () {
- $('.about').hide();
- $('.b-popup').hide();
- $('.b-popup-content').show();
- })
- });
- function meWalker(lab, io) {
- let currentPosition = io.enter;
- console.log(currentPosition);
- $("body").on("keydown", function (event) {
- let newPosition = [currentPosition[0] + ((event.which - 39) % 2), currentPosition[1] + ((event.which - 38) % 2)];
- if (valid(newPosition[0], newPosition[1]) && lab[newPosition[0]][newPosition[1]] !== 'wall') {
- $("#" + currentPosition[0] + "-" + currentPosition[1]).removeClass("me");
- /*Путь*/
- if (!$("#" + newPosition[0] + "-" + newPosition[1]).hasClass("foot") && !$("#" + currentPosition[0] + "-" + currentPosition[1]).hasClass("start") && !$("#" + newPosition[0] + "-" + newPosition[1]).hasClass("start"))
- $("#" + currentPosition[0] + "-" + currentPosition[1]).addClass("foot");
- else $("#" + newPosition[0] + "-" + newPosition[1]).removeClass("foot");
- /*End Путь*/
- currentPosition = newPosition;
- $("#" + currentPosition[0] + "-" + currentPosition[1]).addClass("me");
- //if (currentPosition[0] == hate - 2 && currentPosition[1] == width - 2) document.getElementById('complete').setAttribute('style', 'display:block');
- }
- });
- function valid(a, b) {
- return (a < lab.length && a >= 0 && b < lab[1].length && b >= 0);
- }
- }
- function drawLab(lab) {
- $('#maze').empty().attr('style', 'height:' + lab.length * 25 + 'px; width:' + lab[1].length * 25 + 'px');
- for (let y = 0; y < lab.length; y++) {
- for (let x = 0; x < lab[y].length; x++) {
- if (lab[y][x] === 'wall') {
- $('#maze').append($("<div></div>").attr('id', y + '-' + x).addClass('wall'));
- } else {
- $('#maze').append($("<div></div>").attr('id', y + '-' + x).addClass('block'));
- }
- $("#" + y + "-" + x).append($("<div></div>").addClass('label').attr('id', y + '-' + x + '-label'));
- }
- }
- }
- function genLab(w, h) {
- let lab = [];
- for (let i = 0; i < h; i++) {
- lab[i] = [];
- for (let j = 0; j < w; j++) {
- lab[i][j] = 'wall';
- }
- }
- function valid(a, b) {
- return (a < h && a >= 0 && b < w && b >= 0);
- }
- /*Проверка соседних стен*/
- function amaze(y, x, addBlockWalls) {
- lab[y][x] = 'maze';
- if (addBlockWalls && valid(y + 1, x) && (lab[y + 1][x] === 'wall')) walls.push([y + 1, x, [y, x]]);
- if (addBlockWalls && valid(y - 1, x) && (lab[y - 1][x] === 'wall')) walls.push([y - 1, x, [y, x]]);
- if (addBlockWalls && valid(y, x + 1) && (lab[y][x + 1] === 'wall')) walls.push([y, x + 1, [y, x]]);
- if (addBlockWalls && valid(y, x - 1) && (lab[y][x - 1] === 'wall')) walls.push([y, x - 1, [y, x]]);
- }
- let currentPosition = [1, 1];
- let walls = [];
- amaze(currentPosition[0], currentPosition[1], true);
- while (walls.length !== 0) {
- let randomWall = walls[Math.floor(Math.random() * walls.length)],
- host = randomWall[2],
- opposite = [(host[0] + (randomWall[0] - host[0]) * 2), (host[1] + (randomWall[1] - host[1]) * 2)];
- if (valid(opposite[0], opposite[1])) {
- if (lab[opposite[0]][opposite[1]] === 'maze') walls.splice(walls.indexOf(randomWall), 1);
- else amaze(randomWall[0], randomWall[1], false), amaze(opposite[0], opposite[1], true);
- } else walls.splice(walls.indexOf(randomWall), 1);
- }
- return lab;
- }
- function toConsole(lab) {
- let row;
- for (let i = 0; i < lab.length; i++) {
- for (let j = 0; j < lab[i].length; j++) {
- row = row + lab[i][j] + ' ';
- }
- console.log(row);
- row = '';
- }
- }
- function selectIOAuto(lab) {
- let io = {
- enter: [0, 1],
- exit: [lab.length - 2, lab[1].length - 1]
- };
- $('#' + io.enter[0] + '-' + io.enter[1]).removeClass('wall').addClass('start me');
- $('#' + io.exit[0] + '-' + io.exit[1]).removeClass('wall').addClass('finish');
- return io;
- }
- function selectIOManual(lab, io) {
- let toggler = 0;
- $('.wall').click(function () {
- let id = $(this).attr('id').split('-');
- let y = parseInt(id[0]);
- let x = parseInt(id[1]);
- let yDown = y + 1;
- let yUp = y - 1;
- let xRight = x + 1;
- let xLeft = x - 1;
- 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'))) {
- if (toggler === 0) {
- io.enter = [y, x];
- toggler = 1;
- $('#' + y + '-' + x).removeClass('wall').addClass('start me');
- $('#btn-auto').prop('disabled', true);
- //$('#btn-manual').prop('disabled', true);
- } else {
- io.exit = [y, x];
- toggler = 2;
- $('#' + y + '-' + x).removeClass('wall').addClass('finish');
- $('.wall').unbind();
- $('#btn-manual-apply').prop('disabled', false);
- //return io;
- }
- } else alert('В данной точке нельзя установить вход или выход.');
- });
- }
- function setIO(lab, io) {
- lab[io.enter[0]][io.enter[1]] = 'maze'; //Добавление входа в массив, т.е. удаление его из массива стен
- lab[io.exit[0]][io.exit[1]] = 'maze';
- }
- function drawIO(io) {
- $('#' + io.enter[0] + '-' + io.enter[1]).removeClass('wall').removeClass('block').addClass('start me');
- $('#' + io.exit[0] + '-' + io.exit[1]).removeClass('wall').removeClass('block').addClass('finish');
- }
- CSS
- html, body {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 100%;
- height: 100%;
- min-height: 100%;
- font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
- }
- .auth {
- display: flex;
- flex-direction: column;
- align-items: center;
- color: #495057;
- border: 1px solid #495057;
- position: relative;
- width: 25%;
- height: 40%;
- box-shadow: 0 0 10px rgba(0,0,0,0.8); /* Параметры тени */
- }
- .auth-form {
- display: flex;
- align-items: center;
- flex-direction: column;
- width: 80%;
- }
- .auth-form input {
- text-align: center;
- height: 2rem;
- width: 100%;
- margin-bottom: 1rem;
- }
- .auth-text {
- text-align: center;
- font-size: 24px;
- margin: 2rem;
- }
- .form-control:focus {
- color: #495057;
- background-color: #fff;
- border-color: #80bdff;
- outline: 0;
- box-shadow: 0 0 0 .2rem rgba(0,123,255,.25);
- }
- html {
- font-size: 16px;
- font-family: 'Major Mono Display', monospace;
- text-transform: lowercase;
- /*color: rgba(73, 80, 87, 1);*/
- color: rgba(0, 0, 0, 0.87);
- }
- body {
- background-color: #f8f9fa;
- margin: 0;
- }
- header {
- background: #ffffff;
- color: rgba(73, 80, 87, 0.6);
- height: 8%;
- display: flex;
- align-items: stretch;
- justify-content: space-between;
- padding: 0 1rem;
- box-shadow: 0 3px 5px rgba(57, 63, 72, 0.3);
- }
- .username {
- margin: auto 0.5rem;
- }
- main {
- width: 70%;
- margin: 0 auto;
- }
- .container-maze {
- display: flex;
- margin: 2rem 0;
- }
- .container-side {
- display: flex;
- flex-direction: column;
- width: 25%;
- }
- .container-center {
- width: 50%;
- display: flex;
- justify-content: center;
- }
- main button {
- font-family: 'Major Mono Display', monospace;
- text-transform: lowercase;
- height: 30px;
- }
- .btn {
- cursor: pointer;
- }
- .btn-link {
- border: 1px solid transparent;
- border-radius: 0.25rem;
- }
- .btn-header {
- background: transparent;
- opacity: .6;
- }
- .btn-header:hover {
- /*background-color: rgba(0, 0, 0, 0.5);*/
- opacity: 1;
- }
- #maze {
- /*border-style: solid;*/
- }
- .block {
- background-size: cover;
- float: left;
- height: 25px;
- width: 25px;
- }
- .wall {
- background-size: cover;
- float: left;
- height: 25px;
- width: 25px;
- }
- .label {
- position: absolute;
- font-size: 12px;
- color: white;
- z-index: 2;
- }
- .invisible {
- display: none;
- }
- .foot {
- position: relative;
- }
- .foot:after {
- background-color: green;
- content: '';
- height: 20px;
- position: absolute;
- top: 0;
- width: 20px;
- }
- .blue {
- position: relative;
- }
- .blue:after {
- background-color: deepskyblue;
- content: '';
- height: 20px;
- position: absolute;
- top: 0;
- width: 20px;
- }
- .me {
- position: relative;
- }
- .me:after {
- content: '';
- background-repeat: no-repeat;
- background-size: contain;
- background-position: center;
- height: 25px;
- position: absolute;
- top: 0;
- max-width: 25px;
- width: 25px;
- }
- .start {
- background-size: cover;
- float: left;
- height: 25px;
- width: 25px;
- }
- .finish {
- background-image: url("/images/Exit.jpg");
- background-size: cover;
- float: left;
- height: 25px;
- width: 25px;
- }
- #complete {
- display: none;
- height: 360px;
- left: 20%;
- position: absolute;
- right: 20%;
- top: 50px;
- width: 640px;
- z-index: 1000;
- }
- #complete img {
- height: 100%;
- width: 100%;
- }
- select {
- font-family: 'Major Mono Display', monospace;
- text-transform: lowercase;
- }
- option {
- font-family: 'Major Mono Display', monospace;
- text-transform: lowercase;
- }
- .dashed {
- display: flex;
- flex-direction: column;
- padding: 1rem;
- margin-bottom: 1.5rem;
- border: 1px dashed rgba(73, 80, 87, .6);
- }
- .dashed * {
- margin: .5rem 0;
- }
- .dashed *:first-child {
- margin-top: 0;
- }
- .dashed *:last-child {
- margin-bottom: 0;
- }
- .dashed-title {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 30px;
- border-top: 1px dashed rgba(73, 80, 87, .6);
- border-left: 1px dashed rgba(73, 80, 87, .6);
- border-right: 1px dashed rgba(73, 80, 87, .6);
- }
- .b-popup {
- width: 100%;
- min-height: 100%;
- background-color: rgba(0, 0, 0, 0.5);
- overflow: hidden;
- position: fixed;
- top: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- text-transform: none;
- }
- .b-popup .b-popup-content {
- font-family: 'Roboto', sans-serif;
- margin: auto;
- width: 20%;
- height: 20%;
- padding: 10px;
- background-color: #c5c5c5;
- box-shadow: 0 0 10px #000;
- }
- .b-popup .about {
- font-family: 'Roboto', sans-serif;
- margin: auto;
- width: 35%;
- height: 35%;
- padding: 10px;
- background-color: #c5c5c5;
- box-shadow: 0 0 10px #000;
- }
- .b-popup .about .about-title {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 30px;
- border-bottom: 1px dashed rgba(73, 80, 87, .6);
- }
- .b-popup-load {
- width: 100%;
- min-height: 100%;
- background-color: rgba(0, 0, 0, 0.5);
- overflow: hidden;
- position: fixed;
- top: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- text-transform: none;
- }
- .b-popup-load .b-popup-labs {
- font-family: 'Roboto', sans-serif;
- display: flex;
- flex-direction: column;
- margin: auto;
- width: 30%;
- height: 60%;
- padding: 10px;
- background-color: #c5c5c5;
- box-shadow: 0 0 10px #000;
- }
- .rowLabHeader {
- display: flex;
- flex-direction: row;
- align-items: center;
- border-bottom: 1px dashed rgba(73, 80, 87, .6);
- }
- .rowLab {
- display: flex;
- flex-direction: row;
- border-bottom: 1px dashed rgba(73, 80, 87, .6);
- cursor: pointer;
- }
- .rowLab:hover {
- outline: 1px solid lightseagreen;
- }
- .name {
- border-right: 1px dashed rgba(73, 80, 87, .6);
- text-align: center;
- min-width: 33.33%;
- }
- .theme {
- border-right: 1px dashed rgba(73, 80, 87, .6);
- text-align: center;
- min-width: 33.33%;
- }
- .size {
- text-align: center;
- min-width: 33.33%;
- }
- EJS
- <html>
- <head>
- <link rel="stylesheet" href='/stylesheets/main.css'>
- <link id="theme" rel="stylesheet" href='/stylesheets/themes/theme_stone.css'>
- <script
- src="https://code.jquery.com/jquery-3.3.1.js"
- integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
- crossorigin="anonymous"></script>
- <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
- <link href="https://fonts.googleapis.com/css?family=Major+Mono+Display" rel="stylesheet">
- <link href="https://fonts.googleapis.com/css?family=Roboto&subset=cyrillic" rel="stylesheet">
- </head>
- <body>
- <header>
- <button id="btn-about" class="btn btn-link btn-header" type="button"><i class="fas fa-question fa-2x"></i></button>
- <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>
- </header>
- <main>
- <div class="container-maze">
- <div class="container-side">
- <div class="dashed-title">
- Maze
- </div>
- <div class="dashed">
- <label id="label-width" for="width">Width: 5</label>
- <input id="width" type="range" min="5" max="15" step="2" value="5">
- <label id="label-height" for="height">Height: 5</label>
- <input id="height" type="range" min="5" max="15" step="2" value="5">
- <button id="btn-gen" class="btn" type="button">Generate</button>
- </div>
- <div class="dashed-title">
- Enter/Exit
- </div>
- <div class="dashed">
- <button id="btn-auto" type="button">Auto</button>
- <!--<button id="btn-manual" type="button">Manual</button>-->
- <button id="btn-manual-apply" type="button">Manual Apply</button>
- </div>
- </div>
- <div class="container-center">
- <div id='maze'></div>
- <div id='complete'>
- MISSION ACCOMPLISHED
- </div>
- </div>
- <div class="container-side">
- <div class="dashed-title">
- Theme
- </div>
- <div class="dashed">
- <select id="select-themes" autocomplete="off">
- <option selected value="Stone">Stone</option>
- <option value="Sand">Sand</option>
- <option value="Wood">Wood</option>
- <option value="Dirt">Dirt</option>
- </select>
- </div>
- <div class="dashed-title">
- OneHand
- </div>
- <div id="aOneHand" class="dashed">
- <label id="label-OH-Time" for="OH-Interval"></label>
- <input id="OH-Interval" type="range" min="100" max="1000" step="100" value="100">
- <button id="btn-aOneHand-Dynamic-Time" type="button">Dynamic Time</button>
- <button id="btn-aOneHand-Static" type="button">Static</button>
- </div>
- <div class="dashed-title">
- Trace
- </div>
- <div class="dashed">
- <label id="label-Trace-Timeout" for="Trace-Timeout"></label>
- <input id="Trace-Timeout" type="range" min="100" max="1000" step="100" value="100">
- <button id="btn-aTrace-Timeout" type="button">Dynamic Time</button>
- <button id="btn-aTrace-Static" type="button">Static</button>
- </div>
- </div>
- </div>
- <div style = "text-align: center;">
- <button id="btn-save" type="button">save</button>
- <button id="btn-load" type="button">load</button>
- </div>
- <script src='/javascripts/game.js' type="text/javascript"></script>
- <script src='/javascripts/listener.js' type="text/javascript"></script>
- <script src='/javascripts/aTrace.js' type="text/javascript"></script>
- <script src='/javascripts/aOneHand.js' type="text/javascript"></script>
- <script src="/javascripts/mazeGenerator.js" type="text/javascript"></script>
- </main>
- <div class="b-popup">
- <div class="b-popup-content">
- <span>Name</span>
- <input id="labName" type="text">
- <button id="btn-save-apply" type="button">Save</button>
- <button id="btn-cancel-save" type="button">Cancel</button>
- </div>
- <div class="about">
- <div class="about-title">Справка</div>
- <p>Система генерирования структуры лабиринта и нахождение выхода из него</p>
- <p>Для генерирования структуры лабиринта необходимо:</p>
- <ol>
- <li>Выбрать ширину и высоту лабиринта в блоке "Maze" и нажать кнопку "Generate".</li>
- <li>Выбрать способ расстановки входа и выхода в блоке "Enter/Exit".</li>
- <li>Выбрать тему лабиринта в блоке "Theme".</li>
- <li>Выбрать один из алгоритмов нахождения пути и способов визуализации работы алгоритма.</li>
- </ol>
- <p>Для сохранения и загрузки лабиринта используются кнопки "Save" и "Load".</p>
- <button id="btn-in-about-ok" type="button">OK</button>
- </div>
- </div>
- <footer>
- </footer>
- </body>
- </html>
- <!DOCTYPE html>
- <html lang='ru'>
- <head>
- <title></title>
- <link rel='stylesheet' href='/stylesheets/login.css'/>
- <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"
- integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
- <script
- src="https://code.jquery.com/jquery-3.3.1.js"
- integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
- crossorigin="anonymous"></script>
- </head>
- <body>
- <div class="auth">
- <div class="auth-text">Авторизация</div>
- <form class="auth-form">
- <input name="username" type="text" id="inputLogin" placeholder="Логин...">
- <input name="password" type="text" id="inputPassword" placeholder="Пароль...">
- <!--<input type="text" id="inputPassword2" placeholder="Повторить пароль...">-->
- <input type = "submit" data-loading-text="Проверка..." value = "Sign In">
- </form>
- </div>
- <script src="/javascripts/listener.js"></script>
- </body>
- </html>
- Models
- var crypto = require('crypto');
- var async = require('async');
- var util = require('util');
- const mongoose = require('../lib/mongoose'),
- Schema = mongoose.Schema;
- var schema = new Schema({
- username: {
- type: String,
- unique: true, //уникальность
- required: true //поле обязательно должно быть
- },
- hashedPassword: {
- type: String,
- required: true
- },
- salt: {
- type: String,
- required: true
- },
- created: {
- type: Date,
- default: Date.now
- }
- });
- schema.methods.encryptPassword = function(password) {
- return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
- };
- schema.virtual('password')
- .set(function(password) {
- this._plainPassword = password;
- this.salt = Math.random() + '';
- this.hashedPassword = this.encryptPassword(password);
- })
- .get(function() { return this._plainPassword; });
- schema.methods.checkPassword = function(password) {
- return this.encryptPassword(password) === this.hashedPassword;
- };
- schema.statics.authorize = function(username, password, callback) {
- var User = this;
- async.waterfall([
- function(callback) {
- User.findOne({username: username}, callback);
- },
- function(user, callback) {
- if (user) {
- if (user.checkPassword(password)) {
- callback(null, user);
- } else {
- callback(new AuthError("Пароль неверен"));
- }
- } else {
- var user = new User({username: username, password: password});
- user.save(function(err) {
- if (err) return callback(err);
- callback(null, user);
- });
- }
- }
- ], callback);
- };
- exports.User = mongoose.model('User', schema);
- function AuthError(message) {
- Error.apply(this, arguments);
- Error.captureStackTrace(this, AuthError);
- this.message = message;
- }
- util.inherits(AuthError, Error);
- AuthError.prototype.name = 'AuthError';
- exports.AuthError = AuthError;
- const createError = require('http-errors');
- const mongoose = require('../lib/mongoose');
- const mazeSchema = new mongoose.Schema({
- name: {
- type: String,
- unique: true, //уникальность
- required: true //поле обязательно должно быть
- },
- theme: String,
- enter: Array,
- exit: Array,
- maze: [[]],
- owner: {
- type: mongoose.Schema.Types.ObjectId,
- ref: 'User'
- },
- created: {
- type: Date,
- default: Date.now
- }
- });
- exports.Maze = mongoose.model('Maze', mazeSchema);
- Routes
- var express = require('express');
- var router = express.Router();
- const User = require('../models/user.js').User;
- const createError = require('http-errors');
- var AuthError = require('../models/user').AuthError;
- router.get('/', function (req, res) {
- res.render('login');
- });
- router.post('/', function (req, res, next) {
- var username = req.body.username;
- var password = req.body.password;
- User.authorize(username, password, function (err, user) {
- if (err) {
- if (err instanceof AuthError) {
- return next(createError(403));
- } else {
- return next(err);
- }
- }
- req.session.user = user._id;
- res.send({});
- });
- });
- module.exports = router;
- const express = require('express');
- const router = express.Router();
- const createError = require('http-errors');
- const checkAuth = require('../middleware/checkAuth');
- const Maze = require('../models/modMaze.js').Maze;
- router.get('/', checkAuth, function(req, res) {
- res.render('index');
- });
- router.post('/', function (req, res) {
- if (req.headers.button === 'save') {
- let objMaze = req.body;
- let maze = new Maze(
- {
- name: objMaze.name,
- theme: objMaze.theme,
- enter: objMaze.enter,
- exit: objMaze.exit,
- maze: objMaze.maze,
- owner: req.session.user
- }
- );
- maze.save(function (err) {
- if (err) return createError(err);
- });
- res.setHeader('Status', 'Saved!');
- res.send();
- } else {
- let id = req.body.id;
- console.log(id);
- Maze.findById(id, function (err, maze) {
- if (err) {
- createError(err);
- } else {
- console.log(maze);
- res.json(maze);
- }
- });
- }
- });
- router.post('/getDocuments', function (req, res) {
- Maze.find({owner: req.session.user}, function (err, docs) {
- if (err) {
- createError(err);
- } else {
- res.json(docs);
- }
- });
- });
- module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement