-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathai.js
315 lines (236 loc) · 8.56 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
'use strict';
///////////////////////////////////////////////////////////////
// Debug stuff for counting nodes and branching factors etc.
let nodeCount = 0;
let rounds = 0;
let branching = 0;
///////////////////////////////////////////////////////////////
function constructStateTree(gameState, board, maxDepth){
rounds++;
let root = {
state : gameState,
child: undefined,
score: undefined,
optimalMove: undefined
}
let useAlphaBeta = true;
if (useAlphaBeta) {
let alpha = Number.NEGATIVE_INFINITY;
let beta = Number.POSITIVE_INFINITY;
let maxScore = alphaBetaTreeSearch(root, board, maxDepth, maxDepth, alpha, beta, true);
console.log("Average nodes: " + (nodeCount/rounds));
console.log("Average branching factor: " + (nodeCount/branching));
return root;
} else {
let tree = iterativelyConstructStateTree(root, board, maxDepth);
assignScoresToNodes(root, board);
console.log("Average nodes: " + (nodeCount/rounds));
console.log("Average branching factor: " + (nodeCount/branching));
return tree;
}
}
//
// TODO: Need cleanup! A lot of redundant code for min vs. max branch.
//
function alphaBetaTreeSearch(node, board, depth, maxDepth, alpha, beta, maximizing){
// TODO: Should we penalize the AI if the human/other player is winning also?
if (board.playerHasAllMarblesInGoal(node.state, NELLY)) {
// Make sure that win states that can be achieved in a lower amount of moves is rewarded
// higher than win states found in other branches at higher depth
const largePositiveReward = 10000;
return largePositiveReward / (maxDepth - depth);
}
if (depth == 0) {
return evaluateState(node.state, board);
}
branching++;
if(maximizing) {
var value = Number.NEGATIVE_INFINITY;
let player = NELLY;
let marble = GameBoard.marbleForPlayer(player);
for(let i = 0; i < node.state.length; i++){
if(node.state[i] == marble){
for (let target of board.getPotentialTargets(node.state, i)) {
let lastMove = {src: i, dest: target};
// Prune moves that move mostly backwards away from the goal. This is not mathematically sound
// but we have observed that the non-pruned AI never performs backwards moves, so doing this heavily
// reduces the branching factor of the search tree.
let goalIndex = board.targetLocationIndexForPlayer(player);
let earnedDistance = board.holeDistance(i, goalIndex) - board.holeDistance(target, goalIndex);
if (earnedDistance < -0.5 * board.stepLength) {
continue;
}
// Make copy of the state and perform the move/swap
let newState = node.state.slice();
GameBoard.moveMarble(newState, i, target);
let childNode = {
state: newState,
child: undefined,
score: undefined,
optimalMove: undefined
};
nodeCount++;
let newVal = alphaBetaTreeSearch(childNode, board, depth - 1, maxDepth, alpha, beta, false);
if (newVal > value) {
value = newVal;
node.optimalMove = lastMove;
node.child = childNode;
node.score = value;
}
alpha = Math.max(alpha, value);
if(alpha >= beta){
return value; //No need to continue
}
}
}
}
return node.score;
} else {
let value = Number.POSITIVE_INFINITY;
let player = HUMAN;
let marble = GameBoard.marbleForPlayer(player);
for(let i = 0; i < node.state.length; i++){
if(node.state[i] == marble){
for (let target of board.getPotentialTargets(node.state, i)) {
let lastMove = {src: i, dest: target};
// Prune moves that move mostly backwards away from the goal. This is not mathematically sound
// but we have observed that the non-pruned AI never performs backwards moves, so doing this heavily
// reduces the branching factor of the search tree.
let goalIndex = board.targetLocationIndexForPlayer(player);
let earnedDistance = board.holeDistance(i, goalIndex) - board.holeDistance(target, goalIndex);
if (earnedDistance < -0.5 * board.stepLength) {
continue;
}
// Make copy of the state and perform the move/swap
let newState = node.state.slice();
GameBoard.moveMarble(newState, i, target);
let childNode = {
state: newState,
child: undefined,
score: undefined,
optimalMove: undefined
};
nodeCount++;
let newVal = alphaBetaTreeSearch(childNode, board, depth - 1, maxDepth, alpha, beta, true);
if (newVal < value) {
value = newVal;
node.optimalMove = lastMove;
node.child = childNode;
node.score = newVal;
}
beta = Math.min(value, beta);
if(alpha >= beta){
return value;
}
}
}
}
return node.score;
}
}
// This function gives a score for the given state of a board. To use for evaluating
// states in partially evaluated tree minimax searching.
function evaluateState(gameState, board) {
let distances = [0.0, 0.0];
for (let i = 0; i < gameState.length; i++) {
let marble = gameState[i];
let player = GameBoard.playerForMarble(marble);
if (player != HUMAN && player != NELLY) {
continue;
}
let loc = board.holeLocations[i];
let targetIndex = board.targetLocationIndexForPlayer(player);
let targetLoc = board.holeLocations[targetIndex];
let dx = loc.x - targetLoc.x;
let dy = loc.y - targetLoc.y;
distances[player] += Math.sqrt(dx * dx + dy * dy);
// TODO: Maybe some randomness..? Probably not mathematically sound, but could add some 'chaos' to the AI?
//distances[player] += (Math.random() - 0.5) * 10;
}
// As a minimax score/evaluation for a state we take the difference between the distances each player is towards
// winning. This isn't a truly zero sum or constant sum as both distances will generally decrease as a game plays.
// However, the maximizing player (NELLY) tries to minimize its own distance, while making sure the minimizing
// player (HUMAN, i.e. the human player) doesn't decrease its distance. In essence, it works fine.
let score = distances[HUMAN] - distances[NELLY];
return score;
}
function iterativelyConstructStateTree(root, board, maxDepth) {
root.moves = [];
root.children = [];
root.score = undefined;
let queue = new FifoQueue();
queue.push({node: root, depth: 0});
while (queue.length() != 0) {
let current = queue.pop();
if (current.depth >= maxDepth) {
continue;
}
// Win state here, don't continue along this path!
if (board.playerHasAllMarblesInGoal(current.node.state, NELLY)) {
console.log('found win state at depth: ' + current.depth);
continue;
}
branching++;
let player = (current.depth + 1) % 2;
let marble = GameBoard.marbleForPlayer(player);
for(let i = 0; i < current.node.state.length; i++){
if(current.node.state[i] == marble){
for (let target of board.getPotentialTargets(current.node.state, i)) {
current.node.moves.push({src: i, dest: target});
// Make copy of the state and perform the move/swap
let newState = current.node.state.slice();
GameBoard.moveMarble(newState, i, target);
let childNode = {
state : newState,
children : [],
moves : [],
score : undefined,
optimalMove : undefined
};
current.node.children.push(childNode);
nodeCount++;
queue.push({
node: childNode,
depth: current.depth + 1
});
}
}
}
}
return root;
}
function assignScoresToNodes(root, board) {
recAssignScoresToNodes(root, board, 0);
}
//
// TODO: This needs cleanup! A lot of old unused stuff..
//
function recAssignScoresToNodes(current, board, depth) {
let maximize = (depth % 2) == 0;
let optScore = (maximize) ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
let optMove = undefined;
if (current.children.length == 0) {
current.score = evaluateState(current.state, board);
} else {
// This is needed if all possible future moves makes the state worse, i.e when enetring the last gole hole with only one move...
// However, I have a suspicion that it might not allways risk pervent if all future is worse than one move. So I would like to check
// depth > 1 instead to always account for opponent moves, but for some reason we again get problems at end game... Please check into this :)
if (depth > 0) {
optScore = evaluateState(current.state, board);
}
for (var i = 0; i < current.children.length; i++) {
let child = current.children[i];
recAssignScoresToNodes(child, board, depth + 1)
if (maximize && child.score > optScore) {
optScore = child.score;
optMove = current.moves[i];
}
if (!maximize && child.score < optScore) {
optScore = child.score;
optMove = current.moves[i];
}
}
current.score = optScore;
current.optimalMove = optMove;
}
}