-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathai.js
72 lines (62 loc) · 2.09 KB
/
ai.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
72
/****
* GameAI class
*
* Simple implementation of minimax algorithm to determine best move to
* play.
*
* Execute a WebWorker to prevent freezing the main UI.
*/
let totalCalcs = 0;
class GameAI {
constructor(board){
this.board = board;
}
getNextMove(){
return new Promise((resolve, reject) => {
let matrix = this.board.getRawMatrix();
let off = null;
({matrix, off} = Board.pruneMatrix(matrix, 5));
let worker = new Worker('worker.js');
worker.onmessage = event => {
if(!event.data){
reject('could not calculate move');
}
switch(event.data.type){
case 'move':
let [y, x] = event.data.val;
resolve([y+off.y, x+off.x]);
worker.terminate();
break;
case 'progress':
let percent = event.data.val.completed * 100;
percent /= event.data.val.total;
percent = Math.round(percent);
document.dispatchEvent(new CustomEvent("progress", {"detail": percent}));
break;
case 'console':
// todo add console messages to sidebar
break;
case 'debug':
// debug events
break;
}
}
worker.onError = error => {
reject(error);
}
worker.postMessage({
matrix: matrix,
fn: serializedFn(Board.checkWinner3)
});
});
function serializedFn(fn){
let name = fn.name;
fn = fn.toString();
return {
name: name,
args: fn.substring(fn.indexOf("(") + 1, fn.indexOf(")")),
body: fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}"))
}
}
}
}