-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIDFS.js
72 lines (60 loc) · 2.01 KB
/
IDFS.js
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
class IDFS {
constructor(game) {
this.game = game;
}
solve() {
console.log("Solving...");
let depth = 0;
let initialState = new State(
{ row: this.game.player.row, col: this.game.player.col },
this.game.findBoxesAndGoals(JSON.parse(JSON.stringify(this.game.stage.map))).boxes,
0
);
while (true) {
let visited = new Set();
if (this.depthLimitedSearch(initialState, depth, visited)) {
break;
}
depth++;
}
}
depthLimitedSearch(state, depth, visited) {
if (this.game.stateIsWin(state)) {
alert(`Solved in ${state.moves} moves!`);
console.log(state);
let moves = [];
while (state.parent != null) {
moves.push(state.direction);
state = state.parent;
}
moves.reverse();
document.getElementById("path").innerText = `Moves: ${moves.length} \n Path: ${moves.toString()}`;
let index = 0;
const intervalId = setInterval(() => {
if (index < moves.length) {
state = this.game.player.move(state, moves[index]);
if (state !== null) {
this.game.movePlayer(state.direction);
}
index++;
} else {
clearInterval(intervalId);
}
}, 50);
return true;
}
if (depth === 0) {
return false;
}
visited.add(state.getStateHash());
for (let direction of this.game.directions) {
let newState = this.game.player.move(state, direction);
if (newState != null && !visited.has(newState.getStateHash())) {
if (this.depthLimitedSearch(newState, depth - 1, visited)) {
return true;
}
}
}
return false;
}
}