Repository navigation
Expand file tree
/
Copy pathmazeSolver.js
More file actions
89 lines (73 loc) · 2.21 KB
/
Copy pathmazeSolver.js
File metadata and controls
89 lines (73 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
(function(global) {
"use strict";
var jsmaze = global.jsmaze;
if (!jsmaze) {
jsmaze = {};
global.jsmaze = jsmaze;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
jsmaze.solveMaze = async function(maze) {
var pos = createPos(1, 0);
var pathStack = [];
pathStack.push(pos);
var drawCount = 0;
while (true) {
maze.cells[pos.x][pos.y] = maze.TRACE;
jsmaze.drawBlock(maze, pos.x, pos.y, maze.TRACE);
var moves = getMoves(moveOperations, maze, pos);
while (moves.length > 0) {
pathStack.push(moves.pop());
}
drawCount++;
if (drawCount % 10 === 0) {
await sleep(10);
}
pos = pathStack.pop();
if (pos == undefined) {
return false;
} else if (maze.cells[pos.x][pos.y] == maze.EXIT) {
return true;
}
}
}
function getMoves(operations, maze, pos) {
var moves = [];
for (var operationPos = 0; operationPos < operations.length; operationPos++) {
var move = operations[operationPos](maze, pos);
if (move != undefined) {
moves.push(move);
}
}
return moves;
}
var moveOperations = [
function(maze, pos) {
if (maze.cells[pos.x + 1][pos.y] & (maze.PATH | maze.EXIT)) {
return createPos(pos.x + 1, pos.y);
}
},
function(maze, pos) {
if (maze.cells[pos.x][pos.y + 1] & (maze.PATH | maze.EXIT)) {
return createPos(pos.x, pos.y + 1);
}
},
function(maze, pos) {
if (maze.cells[pos.x - 1][pos.y] & (maze.PATH | maze.EXIT)) {
return createPos(pos.x - 1, pos.y);
}
},
function(maze, pos) {
if (maze.cells[pos.x][pos.y - 1] & (maze.PATH | maze.EXIT)) {
return createPos(pos.x, pos.y - 1);
}
}
];
function createPos(x, y) {
return {
'x': x,
'y': y
};
}
})(this);