-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHexAgentCastillo.js
1286 lines (1130 loc) · 35.8 KB
/
HexAgentCastillo.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
//const tf = require('@tensorflow/tfjs-node');
class Agent {
constructor(name) {
this.id = name;
if (!name) {
this.id = Math.round(Math.random() * 10e8);
}
this.state = null;
this.perception = null;
this.table = { "default": 0 };
}
/**
* Setup of the agent. Could be override by the class extension
* @param {*} parameters
*/
setup(initialState = {}) {
this.initialState = initialState;
}
/**
* Function that receive and store the perception of the world that is sent by the agent controller. This data is stored internally
* in the this.perception variable
* @param {Object} inputs
*/
receive(inputs) {
this.perception = inputs;
}
/**
* Inform to the Agent controller about the action to perform
*/
send() {
return table["deafult"];
}
/**
* Return the agent id
*/
getLocalName() {
return this.id;
}
/**
* Return the agent id
*/
getID() {
return this.id;
}
/**
* Do whatever you do when the agent is stoped. Close connections to databases, write files etc.
*/
stop() {}
}
module.exports = Agent;
},{}],2:[function(require,module,exports){
class AgentController {
constructor() {
this.agents = {};
this.world0 = null;
this.world = null;
this.actions = [];
this.data = { states: [], world: {} };
}
/**
* Setup the configuration for the agent controller
* @param {Object} parameter
*/
setup(parameter) {
this.problem = parameter.problem;
this.world0 = JSON.parse(JSON.stringify(parameter.world));
this.data.world = JSON.parse(JSON.stringify(parameter.world));
}
/**
* Register the given agent in the controller pool. The second parameter stand for the initial state of the agent
* @param {Agent} agent
* @param {Object} state0
*/
register(agent, state0) {
if (this.agents[agent.getID()]) {
throw 'AgentIDAlreadyExists';
} else {
this.agents[agent.getID()] = agent;
this.data.states[agent.getID()] = state0;
//TODO conver state0 to an inmutable object
agent.setup(state0);
}
}
/**
* Remove the given agent from the controller pool
* @param {Object} input
*/
unregister(input) {
let id = "";
if (typeof input == 'string') {
id = input;
} else if (typeof input == 'object') {
id = input.getID();
} else {
throw 'InvalidAgentType';
}
let agent = this.agents[id];
agent.stop();
delete this.agents[id];
}
/**
* This function start the virtual life. It will continously execute the actions
* given by the agents in response to the perceptions. It stop when the solution function
* is satisfied or when the max number of iterations is reached.
* If it must to run in interactive mode, the start mode return this object, which is actually
* the controller
* @param {Array} callbacks
*/
start(callbacks, interactive = false) {
this.callbacks = callbacks;
this.currentAgentIndex = 0;
if (interactive === false) {
this.loop();
return null;
} else {
return this;
}
}
/**
* Executes the next iteration in the virtual life simulation
*/
next() {
if (!this.problem.goalTest(this.data)) {
let keys = Object.keys(this.agents);
let agent = this.agents[keys[this.currentAgentIndex]];
agent.receive(this.problem.perceptionForAgent(this.getData(), agent.getID()));
let action = agent.send();
this.actions.push({ agentID: agent.getID(), action });
this.problem.update(this.data, action, agent.getID());
if (this.problem.goalTest(this.data)) {
this.finishAll();
return false;
} else {
if (this.callbacks.onTurn) {
this.callbacks.onTurn({ actions: this.getActions(), data: this.data });
}
if (this.currentAgentIndex >= keys.length - 1) this.currentAgentIndex = 0;else this.currentAgentIndex++;
return true;
}
}
}
/**
* Virtual life loop. At the end of every step it executed the onTurn call back. It could b used for animations of login
*/
loop() {
let stop = false;
while (!stop) {
//Creates a thread for every single agent
Object.values(this.agents).forEach(agent => {
if (!this.problem.goalTest(this.data)) {
agent.receive(this.problem.perceptionForAgent(this.getData(), agent.getID()));
let action = agent.send();
this.actions.push({ agentID: agent.getID(), action });
this.problem.update(this.data, action, agent.getID());
if (this.problem.goalTest(this.data)) {
stop = true;
} else {
if (this.callbacks.onTurn) this.callbacks.onTurn({ actions: this.getActions(), data: this.data });
}
}
});
}
this.finishAll();
}
/**
* This function is executed once the virtual life loop is ended. It must stop every single agent in the pool
* and execute the onFinish callback
*/
finishAll() {
// Stop all the agents
Object.values(this.agents).forEach(agent => {
//agent.stop();
this.unregister(agent);
});
//Execute the callback
if (this.callbacks.onFinish) this.callbacks.onFinish({ actions: this.getActions(), data: this.data });
}
/**
* Return a copu of the agent controller data. The returned object contains the data of the problem (world) and the
* state of every single agent in the controller pool (states)
*/
getData() {
return this.data;
}
/**
* Return the history of the actions performed by the agents during the current virtual life loop
*/
getActions() {
return JSON.parse(JSON.stringify(this.actions));
}
/**
* This function stop all the threads started by the agent controller and stops registered agents
*/
stop() {
this.finishAll();
}
}
module.exports = AgentController;
},{}],3:[function(require,module,exports){
const AgentController = require('../core/AgentController');
/**
* This class specifies the problem to be solved
*/
class Problem {
constructor(initialState) {
this.controller = new AgentController();
}
/**
* Check if the given solution solves the problem. You must override
* @param {Object} solution
*/
goalTest(solution) {}
//TODO return boolean
/**
* The transition model. Tells how to change the state (data) based on the given actions. You must override
* @param {} data
* @param {*} action
* @param {*} agentID
*/
update(data, action, agentID) {}
//TODO modify data
/**
* Gives the world representation for the agent at the current stage
* @param {*} agentID
* @returns and object with the information to be sent to the agent
*/
perceptionForAgent(data, agentID) {}
//TODO return the perception
/**
* Add a new agent to solve the problem
* @param {*} agentID
* @param {*} agentClass
* @param {*} initialState
*/
addAgent(agentID, agentClass, initialState) {
let agent = new agentClass(agentID);
this.controller.register(agent, initialState);
}
/**
* Solve the given problem
* @param {*} world
* @param {*} callbacks
*/
solve(world, callbacks) {
this.controller.setup({ world: world, problem: this });
this.controller.start(callbacks, false);
}
/**
* Returns an interable function that allow to execute the simulation step by step
* @param {*} world
* @param {*} callbacks
*/
interactiveSolve(world, callbacks) {
this.controller.setup({ world: world, problem: this });
return this.controller.start(callbacks, true);
}
}
module.exports = Problem;
},{"../core/AgentController":2}],4:[function(require,module,exports){
const Problem = require('./core/Problem');
const Agent = require('./core/Agent');
const AgentController = require('./core/AgentController');
module.exports = { Problem, Agent, AgentController };
},{"./core/Agent":1,"./core/AgentController":2,"./core/Problem":3}],5:[function(require,module,exports){
const Queue = require('./PriorityQueue');
const removeDeepFromMap = require('./removeDeepFromMap');
const toDeepMap = require('./toDeepMap');
const validateDeep = require('./validateDeep');
/** Creates and manages a graph */
class Graph {
/**
* Creates a new Graph, optionally initializing it a nodes graph representation.
*
* A graph representation is an object that has as keys the name of the point and as values
* the points reacheable from that node, with the cost to get there:
*
* {
* node (Number|String): {
* neighbor (Number|String): cost (Number),
* ...,
* },
* }
*
* In alternative to an object, you can pass a `Map` of `Map`. This will
* allow you to specify numbers as keys.
*
* @param {Objec|Map} [graph] - Initial graph definition
* @example
*
* const route = new Graph();
*
* // Pre-populated graph
* const route = new Graph({
* A: { B: 1 },
* B: { A: 1, C: 2, D: 4 },
* });
*
* // Passing a Map
* const g = new Map()
*
* const a = new Map()
* a.set('B', 1)
*
* const b = new Map()
* b.set('A', 1)
* b.set('C', 2)
* b.set('D', 4)
*
* g.set('A', a)
* g.set('B', b)
*
* const route = new Graph(g)
*/
constructor(graph) {
if (graph instanceof Map) {
validateDeep(graph);
this.graph = graph;
} else if (graph) {
this.graph = toDeepMap(graph);
} else {
this.graph = new Map();
}
}
/**
* Adds a node to the graph
*
* @param {string} name - Name of the node
* @param {Object|Map} neighbors - Neighbouring nodes and cost to reach them
* @return {this}
* @example
*
* const route = new Graph();
*
* route.addNode('A', { B: 1 });
*
* // It's possible to chain the calls
* route
* .addNode('B', { A: 1 })
* .addNode('C', { A: 3 });
*
* // The neighbors can be expressed in a Map
* const d = new Map()
* d.set('A', 2)
* d.set('B', 8)
*
* route.addNode('D', d)
*/
addNode(name, neighbors) {
let nodes;
if (neighbors instanceof Map) {
validateDeep(neighbors);
nodes = neighbors;
} else {
nodes = toDeepMap(neighbors);
}
this.graph.set(name, nodes);
return this;
}
/**
* @deprecated since version 2.0, use `Graph#addNode` instead
*/
addVertex(name, neighbors) {
return this.addNode(name, neighbors);
}
/**
* Removes a node and all of its references from the graph
*
* @param {string|number} key - Key of the node to remove from the graph
* @return {this}
* @example
*
* const route = new Graph({
* A: { B: 1, C: 5 },
* B: { A: 3 },
* C: { B: 2, A: 2 },
* });
*
* route.removeNode('C');
* // The graph now is:
* // { A: { B: 1 }, B: { A: 3 } }
*/
removeNode(key) {
this.graph = removeDeepFromMap(this.graph, key);
return this;
}
/**
* Compute the shortest path between the specified nodes
*
* @param {string} start - Starting node
* @param {string} goal - Node we want to reach
* @param {object} [options] - Options
*
* @param {boolean} [options.trim] - Exclude the origin and destination nodes from the result
* @param {boolean} [options.reverse] - Return the path in reversed order
* @param {boolean} [options.cost] - Also return the cost of the path when set to true
*
* @return {array|object} Computed path between the nodes.
*
* When `option.cost` is set to true, the returned value will be an object with shape:
* - `path` *(Array)*: Computed path between the nodes
* - `cost` *(Number)*: Cost of the path
*
* @example
*
* const route = new Graph()
*
* route.addNode('A', { B: 1 })
* route.addNode('B', { A: 1, C: 2, D: 4 })
* route.addNode('C', { B: 2, D: 1 })
* route.addNode('D', { C: 1, B: 4 })
*
* route.path('A', 'D') // => ['A', 'B', 'C', 'D']
*
* // trimmed
* route.path('A', 'D', { trim: true }) // => [B', 'C']
*
* // reversed
* route.path('A', 'D', { reverse: true }) // => ['D', 'C', 'B', 'A']
*
* // include the cost
* route.path('A', 'D', { cost: true })
* // => {
* // path: [ 'A', 'B', 'C', 'D' ],
* // cost: 4
* // }
*/
path(start, goal, options = {}) {
// Don't run when we don't have nodes set
if (!this.graph.size) {
if (options.cost) return {
path: null,
cost: 0
};
return null;
}
const explored = new Set();
const frontier = new Queue();
const previous = new Map();
let path = [];
let totalCost = 0;
let avoid = [];
if (options.avoid) avoid = [].concat(options.avoid);
if (avoid.includes(start)) {
throw new Error(`Starting node (${start}) cannot be avoided`);
} else if (avoid.includes(goal)) {
throw new Error(`Ending node (${goal}) cannot be avoided`);
} // Add the starting point to the frontier, it will be the first node visited
frontier.set(start, 0); // Run until we have visited every node in the frontier
while (!frontier.isEmpty()) {
// Get the node in the frontier with the lowest cost (`priority`)
const node = frontier.next(); // When the node with the lowest cost in the frontier in our goal node,
// we can compute the path and exit the loop
if (node.key === goal) {
// Set the total cost to the current value
totalCost = node.priority;
let nodeKey = node.key;
while (previous.has(nodeKey)) {
path.push(nodeKey);
nodeKey = previous.get(nodeKey);
}
break;
} // Add the current node to the explored set
explored.add(node.key); // Loop all the neighboring nodes
const neighbors = this.graph.get(node.key) || new Map();
neighbors.forEach((nCost, nNode) => {
// If we already explored the node, or the node is to be avoided, skip it
if (explored.has(nNode) || avoid.includes(nNode)) return null; // If the neighboring node is not yet in the frontier, we add it with
// the correct cost
if (!frontier.has(nNode)) {
previous.set(nNode, node.key);
return frontier.set(nNode, node.priority + nCost);
}
const frontierPriority = frontier.get(nNode).priority;
const nodeCost = node.priority + nCost; // Otherwise we only update the cost of this node in the frontier when
// it's below what's currently set
if (nodeCost < frontierPriority) {
previous.set(nNode, node.key);
return frontier.set(nNode, nodeCost);
}
return null;
});
} // Return null when no path can be found
if (!path.length) {
if (options.cost) return {
path: null,
cost: 0
};
return null;
} // From now on, keep in mind that `path` is populated in reverse order,
// from destination to origin
// Remove the first value (the goal node) if we want a trimmed result
if (options.trim) {
path.shift();
} else {
// Add the origin waypoint at the end of the array
path = path.concat([start]);
} // Reverse the path if we don't want it reversed, so the result will be
// from `start` to `goal`
if (!options.reverse) {
path = path.reverse();
} // Return an object if we also want the cost
if (options.cost) {
return {
path,
cost: totalCost
};
}
return path;
}
/**
* @deprecated since version 2.0, use `Graph#path` instead
*/
shortestPath(...args) {
return this.path(...args);
}
}
module.exports = Graph;
},{"./PriorityQueue":6,"./removeDeepFromMap":7,"./toDeepMap":8,"./validateDeep":9}],6:[function(require,module,exports){
/**
* This very basic implementation of a priority queue is used to select the
* next node of the graph to walk to.
*
* The queue is always sorted to have the least expensive node on top.
* Some helper methods are also implemented.
*
* You should **never** modify the queue directly, but only using the methods
* provided by the class.
*/
class PriorityQueue {
/**
* Creates a new empty priority queue
*/
constructor() {
// The `keys` set is used to greatly improve the speed at which we can
// check the presence of a value in the queue
this.keys = new Set();
this.queue = [];
}
/**
* Sort the queue to have the least expensive node to visit on top
*
* @private
*/
sort() {
this.queue.sort((a, b) => a.priority - b.priority);
}
/**
* Sets a priority for a key in the queue.
* Inserts it in the queue if it does not already exists.
*
* @param {any} key Key to update or insert
* @param {number} value Priority of the key
* @return {number} Size of the queue
*/
set(key, value) {
const priority = Number(value);
if (isNaN(priority)) throw new TypeError('"priority" must be a number');
if (!this.keys.has(key)) {
// Insert a new entry if the key is not already in the queue
this.keys.add(key);
this.queue.push({
key,
priority
});
} else {
// Update the priority of an existing key
this.queue.map(element => {
if (element.key === key) {
Object.assign(element, {
priority
});
}
return element;
});
}
this.sort();
return this.queue.length;
}
/**
* The next method is used to dequeue a key:
* It removes the first element from the queue and returns it
*
* @return {object} First priority queue entry
*/
next() {
const element = this.queue.shift(); // Remove the key from the `_keys` set
this.keys.delete(element.key);
return element;
}
/**
* @return {boolean} `true` when the queue is empty
*/
isEmpty() {
return Boolean(this.queue.length === 0);
}
/**
* Check if the queue has a key in it
*
* @param {any} key Key to lookup
* @return {boolean}
*/
has(key) {
return this.keys.has(key);
}
/**
* Get the element in the queue with the specified key
*
* @param {any} key Key to lookup
* @return {object}
*/
get(key) {
return this.queue.find(element => element.key === key);
}
}
module.exports = PriorityQueue;
},{}],7:[function(require,module,exports){
/**
* Removes a key and all of its references from a map.
* This function has no side-effects as it returns
* a brand new map.
*
* @param {Map} map - Map to remove the key from
* @param {string} key - Key to remove from the map
* @return {Map} New map without the passed key
*/
function removeDeepFromMap(map, key) {
const newMap = new Map();
for (const [aKey, val] of map) {
if (aKey !== key && val instanceof Map) {
newMap.set(aKey, removeDeepFromMap(val, key));
} else if (aKey !== key) {
newMap.set(aKey, val);
}
}
return newMap;
}
module.exports = removeDeepFromMap;
},{}],8:[function(require,module,exports){
/**
* Validates a cost for a node
*
* @private
* @param {number} val - Cost to validate
* @return {bool}
*/
function isValidNode(val) {
const cost = Number(val);
if (isNaN(cost) || cost <= 0) {
return false;
}
return true;
}
/**
* Creates a deep `Map` from the passed object.
*
* @param {Object} source - Object to populate the map with
* @return {Map} New map with the passed object data
*/
function toDeepMap(source) {
const map = new Map();
const keys = Object.keys(source);
keys.forEach(key => {
const val = source[key];
if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
return map.set(key, toDeepMap(val));
}
if (!isValidNode(val)) {
throw new Error(`Could not add node at key "${key}", make sure it's a valid node`, val);
}
return map.set(key, Number(val));
});
return map;
}
module.exports = toDeepMap;
},{}],9:[function(require,module,exports){
/**
* Validate a map to ensure all it's values are either a number or a map
*
* @param {Map} map - Map to valiadte
*/
function validateDeep(map) {
if (!(map instanceof Map)) {
throw new Error(`Invalid graph: Expected Map instead found ${typeof map}`);
}
map.forEach((value, key) => {
if (typeof value === 'object' && value instanceof Map) {
validateDeep(value);
return;
}
if (typeof value !== 'number' || value <= 0) {
throw new Error(`Values must be numbers greater than 0. Found value ${value} at ${key}`);
}
});
}
module.exports = validateDeep;
},{}],10:[function(require,module,exports){
const Graph = require('node-dijkstra');
const transpose = require('./transposeHex');
let cache = {};
function boardScore(board, player) {
let path0 = boardPath(board);
let score = 0;
if (!path0) {
score = -(board.length * board.length);
} else {
if (path0.length === 2) {
score = (board.length * board.length);
} else {
let path1 = boardPath(transpose(board));
if (!path1) {
score = (board.length * board.length)
} else {
score = path1.length - path0.length;
}
}
}
return player === '1' ? score : -score;
}
function boardPath(board) {
let player = '1';
let size = board.length;
const route = new Graph();
let neighborsT = {};
let neighborsX = {};
cache = {};
// Build the graph out of the hex board
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
let key = i * size + j;
if (board[i][j] === 0) { // || board[i][j] === player
let list = getNeighborhood(key, player, board);
list = removeIfAny(board, list, i, j);
let neighbors = {};
let sideX = false;
let sideT = false;
list.forEach(x => {
switch (x) {
case -1:
neighbors[player + 'X'] = 1;
neighborsX[key + ''] = 1;
sideX = sideX || board[i][j] === player;
break;
case -2:
neighbors[player + 'T'] = 1;
neighborsT[key + ''] = 1;
sideT = sideT || board[i][j] === player;
break;
default:
neighbors[x + ''] = 1;
}
});
// This case occurs when the game has finished
if (sideT && sideX) {
neighborsX[player + 'T'] = 1;
neighborsT[player + 'X'] = 1;
}
route.addNode(key + '', neighbors);
}
}
}
route.addNode(player + 'T', neighborsT);
route.addNode(player + 'X', neighborsX);
return route.path(player + 'T', player + 'X');
}
function removeIfAny(board, list, row, col) {
let size = board.length;
if(row > 0 && col > 0 && row < size - 1 && col < size - 1 && list.length > 0) {
if (board[row - 1][col] === 0 && board[row - 1][col - 1] === '2' && board[row][col + 1] === '2') {
let k = list.findIndex(key => key === (row - 1) * size + col);
//console.log('x: ' + k + ' ' + ((row - 1) * size + col));
//console.log(list);
if (k >= 0)
list.splice(k, 1);
}
if (board[row][col + 1] === 0 && board[row - 1][col] === '2' && board[row + 1][col + 1] === '2') {
let k = list.findIndex(key => key === row * size + col + 1);
//console.log('x: ' + k + ' ' + (row * size + col + 1) );
//console.log(list);
if (k >= 0)
list.splice(k, 1);
}
if (board[row + 1][col + 1] === 0 && board[row][col + 1] === '2' && board[row + 1][col] === '2') {
let k = list.findIndex(key => key === (row + 1) * size + col + 1);
//console.log('x: ' + k + ' ' + ((row + 1) * size + col));
//console.log(list);
if (k >= 0)
list.splice(k, 1);
}
if (board[row + 1][col] === 0 && board[row + 1][col + 1] === '2' && board[row + 1][col - 1] === '2') {
let k = list.findIndex(key => key === (row + 1) * size + col);
//console.log('x: ' + k+ ' ' + ((row + 1) * size + col));
//console.log(list);
if (k >= 0)
list.splice(k, 1);
}
if (board[row][col - 1] === 0 && board[row + 1][col] === '2' && board[row -1 ][col - 1] === '2') {
let k = list.findIndex(key => key === row * size + col - 1);
//console.log('x: ' + k + ' ' + (row * size + col - 1));
//console.log(list);
if (k >= 0)
list.splice(k, 1);
}
if (board[row - 1][col - 1] === 0 && board[row - 1][col] === '2' && board[row][col - 1] === '2') {
let k = list.findIndex(key => key === (row - 1) * size + col - 1);
//console.log('x: ' + k + ' ' + ((row - 1) * size + col - 1));
//console.log(list);
if (k >= 0)
list.splice(k, 1);
}
}
return list;
}
/**
* Return an array of the neighbors of the currentHex that belongs to the same player. The
* array contains the id of the hex. id = row * size + col
* @param {Number} currentHex
* @param {Number} player
* @param {Matrix} board
*/
function getNeighborhood(currentHex, player, board) {
//Check if this value has been precalculated in this turn
if (cache[currentHex + player]) {
//console.log("Returned from cache");
return cache[currentHex + player];
}
let size = board.length;
let row = Math.floor(currentHex / size);
let col = currentHex % size;
let result = [];
let currentValue = board[row][col];
board[row][col] = 'x';
// Check the six neighbours of the current hex
pushIfAny(result, board, player, row - 1, col);
pushIfAny(result, board, player, row - 1, col + 1);
pushIfAny(result, board, player, row, col + 1);
pushIfAny(result, board, player, row, col - 1);
pushIfAny(result, board, player, row + 1, col);
pushIfAny(result, board, player, row + 1, col - 1);
// Add the edges if hex is at the border
if (col === size - 1) {
result.push(-1);
} else if (col === 0) {
result.push(-2);
}
board[row][col] = currentValue;
// Cache this result
cache[currentHex + player] = result;
return result;
}
function pushIfAny(result, board, player, row, col) {
let size = board.length;
if (row >= 0 && row < size && col >= 0 && col < size) {
if (board[row][col] === player || board[row][col] === 0) {
if (board[row][col] === player) {
result.push(...getNeighborhood(col + row * size, player, board));
} else {
result.push(col + row * size);
}
}
}
}
module.exports = boardScore;
/*
board = [[0, 0, 0],
[0, '2', 0],
['1', '1', 0]];
console.log(boardScore(board, '1')); // Debe dar 3 - 1 = 2
board = [[0, 0, '1'],
[0, '2', 0],
['1', 0, 0]];
console.log(boardScore(board, '1')); // Debe dar 3 - 1 = 2
/*let board = [[0, '1', '1'],