-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpawnCaptures.js
More file actions
1271 lines (1146 loc) · 53.8 KB
/
pawnCaptures.js
File metadata and controls
1271 lines (1146 loc) · 53.8 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
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
IMPOSSIBLE = 999;
const DEBUG_PAWN_CAPTURES0 = false;
function debugLog0(str) {
if (DEBUG_PAWN_CAPTURES0) {
console.log(str);
}
}
const DEBUG_PAWN_CAPTURES = false;
function debugLog(str) {
if (DEBUG_PAWN_CAPTURES) {
console.log(str);
}
}
let DEBUG_POSITIONS = [];
let DEBUG_PAWN_CAPTURES2 = false;
function debugLog2(str) {
if (DEBUG_PAWN_CAPTURES2) {
console.log(str);
}
}
let DEBUG_DEPTH = 0;
let DEBUG_PAWN_CAPTURES3 = false;
function debugLog3(str, depth) {
if (DEBUG_PAWN_CAPTURES3 && depth <= DEBUG_DEPTH) {
console.log(str);
}
}
class PawnCaptureSearchState {
constructor(position, assignments, estimatedDistance) {
this.position = position;
this.assignments = assignments;
this.estimatedDistance = estimatedDistance;
}
}
class PawnCaptureConfig {
constructor(promotionSearchThreshold, enableSeparateCaptureTracking) {
this.promotionSearchThreshold = promotionSearchThreshold;
this.enableSeparateCaptureTracking = enableSeparateCaptureTracking;
}
set(pawnCaptureConfig) {
this.promotionSearchThreshold = pawnCaptureConfig.promotionSearchThreshold;
this.enableSeparateCaptureTracking = pawnCaptureConfig.enableSeparateCaptureTracking;
}
}
const pawnCaptureConfig = new PawnCaptureConfig(1000, false);
function getPawnCaptureConfig() {
return pawnCaptureConfig;
}
function getPromotionSearchThreshold() {
return pawnCaptureConfig.promotionSearchThreshold;
}
function setPromotionSearchThreshold(threshold) {
pawnCaptureConfig.promotionSearchThreshold = threshold;
}
function getEnableSeparateCaptureTracking() {
return pawnCaptureConfig.enableSeparateCaptureTracking;
}
function setEnableSeparateCaptureTracking(flag) {
pawnCaptureConfig.enableSeparateCaptureTracking = flag;
}
function getPawns(board) {
const whitePawns = [];
const blackPawns = [];
for (let file = 0; file < 8; file++) {
whitePawns[file] = [];
blackPawns[file] = [];
for (let rank = 0; rank < 8; rank++) {
if (board[file][rank].unit == "P") {
if (board[file][rank].color == "w") {
whitePawns[file].push(rank);
} else {
blackPawns[file].push(rank);
}
}
}
}
return [whitePawns, blackPawns];
}
function copyPawns(pawns) {
let newPawns = [];
for (let side = 0; side < 2; side++) {
newPawns[side] = [];
for (let file = 0; file < 8; file++) {
newPawns[side][file] = pawns[side][file].slice();
}
}
return newPawns;
}
function blankAssignments() {
return [[[-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1]],
[[-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1]]];
}
function copyAssignments(assignments) {
const copy = blankAssignments();
for (let side = 0; side < 2; side++) {
for (let file = 0; file < 8; file++) {
for (let j = 0; j < 2; j++) {
copy[side][file][j] = assignments[side][file][j];
}
}
}
return copy;
}
function insertIntoHeap(state, heap) {
heap.push(state);
let index = heap.length - 1;
let parent = Math.floor((index - 1) / 2);
while (index > 0 && heap[index].estimatedDistance < heap[parent].estimatedDistance) { // sift up
const temp = heap[index];
heap[index] = heap[parent];
heap[parent] = temp;
index = parent;
parent = Math.floor((index - 1) / 2);
}
}
function solveSingleColorHungarian(pawnCounts, used) {
function assignWorkerToJob(workerIndex, jobIndex) {
workerToJobAssignments[workerIndex] = jobIndex;
jobToWorkerAssignments[jobIndex] = workerIndex;
const tightWorkerToJobEdgesIndex = tightWorkerToJobEdges[workerIndex].indexOf(jobIndex);
assert(tightWorkerToJobEdgesIndex != -1, "Did not find job " + jobIndex + " in " +
"tightWorkerToJobEdges[" + workerIndex + "] = " + tightWorkerToJobEdges[workerIndex].toString());
tightWorkerToJobEdges[workerIndex].splice(tightWorkerToJobEdgesIndex, 1);
log("Assigned worker " + workerIndex + " to job " + jobIndex + " " + "abcdefgh".charAt(jobFiles[jobIndex]));
}
function unassignWorkerToJob(workerIndex, jobIndex) {
assert(workerToJobAssignments[workerIndex] == jobIndex && jobToWorkerAssignments[jobIndex] == workerIndex,
"Attempt to unassign worker " + workerIndex + " job " + jobIndex + " not currently assigned");
jobToWorkerAssignments[jobIndex] = -1;
workerToJobAssignments[workerIndex] = -1;
assert(tightWorkerToJobEdges[workerIndex].indexOf(jobIndex) == -1,
"Incorrect found jobIndex " + jobIndex + " in tightWorkerToJobEdges[" + workerIndex + "] = " +
tightWorkerToJobEdges[workerIndex].toString());
tightWorkerToJobEdges[workerIndex].push(jobIndex);
log("Unassigned worker " + workerIndex + " from job " + jobIndex + " " + "abcdefgh".charAt(jobFiles[jobIndex]));
}
function last(arr) {
return arr[arr.length - 1];
}
const DEBUG_HUNGARIAN = false;
function log(str) {
if (DEBUG_HUNGARIAN) {
console.log(str);
}
}
log("Solving: " + pawnCounts.toString() + " used: " + used.toString());
const workerFiles = [];
const jobFiles = [];
for (let file = 0; file < 8; file++) {
if (used[file] == 0) {
workerFiles.push(file);
}
for (let i = 0; i < pawnCounts[file]; i++) {
jobFiles.push(file);
}
}
if (workerFiles.length < jobFiles.length) {
return IMPOSSIBLE;
}
const workerPotential = workerFiles.map(() => 0);
const jobPotential = jobFiles.map(() => 0);
const workerToJobAssignments = workerFiles.map(() => -1);
const jobToWorkerAssignments = jobFiles.map(() => -1);
const tightWorkerToJobEdges = workerFiles.map(() => []);
// initialize tight edges
// there is a tight edge from each pawn to its current file (if the file is available)
let jobIndex = 0;
jobFiles.forEach(jobFile => {
const workerIndex = workerFiles.indexOf(jobFile);
if (workerIndex != -1) {
tightWorkerToJobEdges[workerIndex].push(jobIndex);
}
jobIndex++;
});
while (jobToWorkerAssignments.indexOf(-1) != -1) {
// initialize alternating paths to start at unassigned workers
const reachableWorkers = [];
const reachableJobs = [];
const alternatingPathsQueue = [];
for (let workerIndex = 0; workerIndex < workerFiles.length; workerIndex++) {
if (workerToJobAssignments[workerIndex] == -1) {
alternatingPathsQueue.push([workerIndex]);
reachableWorkers.push(workerIndex);
}
}
// try to find an augmenting path
let augmentingPathFound = false;
for (let alternatingPathsQueueIndex = 0;
!augmentingPathFound && alternatingPathsQueueIndex < alternatingPathsQueue.length;
alternatingPathsQueueIndex++) {
const alternatingPath = alternatingPathsQueue[alternatingPathsQueueIndex];
const workerIndex = last(alternatingPath);
log("expanding alternating path " + alternatingPath.toString());
tightWorkerToJobEdges[workerIndex].forEach(jobIndex => {
if (!augmentingPathFound && reachableJobs.indexOf(jobIndex) == -1) {
const extendedAlternatingPath = alternatingPath.concat([jobIndex]);
reachableJobs.push(jobIndex);
const assignedWorkerIndex = jobToWorkerAssignments[jobIndex];
if (assignedWorkerIndex == -1) { // this job is unmatched, found augmenting path
augmentingPathFound = true;
log("Augmenting path found " + extendedAlternatingPath.toString());
assert(extendedAlternatingPath.length % 2 == 0,
"Unexpected odd number of nodes in path " + extendedAlternatingPath.toString());
// reverse all edges of augmenting path
for (let i = 0; i < extendedAlternatingPath.length; i += 2) {
const newJobIndex = extendedAlternatingPath[i + 1];
const newWorkerIndex = extendedAlternatingPath[i];
if (i < extendedAlternatingPath.length - 2) {
const oldWorkerIndex = extendedAlternatingPath[i + 2];
unassignWorkerToJob(oldWorkerIndex, newJobIndex);
}
assignWorkerToJob(newWorkerIndex, newJobIndex);
}
} else { // if worker has not already been marked reachable, extend alternating path to the matching worker
if (reachableWorkers.indexOf(assignedWorkerIndex) == -1) {
reachableWorkers.push(assignedWorkerIndex);
extendedAlternatingPath.push(assignedWorkerIndex);
alternatingPathsQueue.push(extendedAlternatingPath);
log("Adding alternating path " + extendedAlternatingPath.toString());
}
}
}
});
}
if (!augmentingPathFound) {
// find minimum adjusting potential between reachable workers and unreachable jobs
log("No augmenting path found.");
let minDelta = 999;
reachableWorkers.forEach(workerIndex => {
for (let jobIndex = 0; jobIndex < jobFiles.length; jobIndex++) {
if (reachableJobs.indexOf(jobIndex) == -1) {
const cost = Math.abs(workerFiles[workerIndex] - jobFiles[jobIndex]);
minDelta = Math.min(minDelta, cost - workerPotential[workerIndex] - jobPotential[jobIndex]);
assert(minDelta > 0,
"minDelta has reached <= 0 value " + minDelta + " at workerIndex = " + workerIndex + " jobIndex = " + jobIndex);
}
}
});
// increase potentials for reachable workers, decrease for reachable jobs
reachableWorkers.forEach(workerIndex => {
workerPotential[workerIndex] += minDelta;
log("potential for worker " + workerIndex + " is now " + workerPotential[workerIndex]);
});
reachableJobs.forEach(jobIndex => {
jobPotential[jobIndex] -= minDelta;
log("potential for job " + jobIndex + " is now " + jobPotential[jobIndex]);
});
// find new tight edges
reachableWorkers.forEach(workerIndex => {
for (let jobIndex = 0; jobIndex < jobFiles.length; jobIndex++) {
if (workerPotential[workerIndex] + jobPotential[jobIndex] ==
Math.abs(workerFiles[workerIndex] - jobFiles[jobIndex])) {
if (tightWorkerToJobEdges[workerIndex].indexOf(jobIndex) == -1 &&
jobToWorkerAssignments[jobIndex] != workerIndex) {
log("New tight edge: worker " + workerIndex + " job " + jobIndex);
tightWorkerToJobEdges[workerIndex].push(jobIndex);
}
}
}
});
// find edges that are no longer tight (job end in reachable jobs, worker end not in reachable workers)
reachableJobs.forEach(jobIndex => {
for (let workerIndex = 0; workerIndex < workerFiles.length; workerIndex++) {
if (reachableWorkers.indexOf(workerIndex) == -1) {
const tightWorkerToJobEdgesIndex = tightWorkerToJobEdges[workerIndex].indexOf(jobIndex);
if (tightWorkerToJobEdgesIndex != -1) {
tightWorkerToJobEdges[workerIndex].splice(tightWorkerToJobEdgesIndex, 1);
log("Edge is no longer tight: worker " + workerIndex + " job " + jobIndex);
}
}
}
});
// consistency check 1 - verify that potential inequalities still hold
for (let workerIndex = 0; workerIndex < workerFiles.length; workerIndex++) {
for (let jobIndex = 0; jobIndex < jobFiles.length; jobIndex++) {
const cost = Math.abs(workerFiles[workerIndex] - jobFiles[jobIndex]);
assert(workerPotential[workerIndex] + jobPotential[jobIndex] <= cost,
"Potential inequality violated at workerIndex " + workerIndex +
" job Index " + jobIndex + " " + workerPotential[workerIndex] + " " +
jobPotential[jobIndex] + " " + cost);
}
}
// consistency check 2 - make sure all edges in tightWorkerToJobEdges are really tight
for (let workerIndex = 0; workerIndex < workerFiles.length; workerIndex++) {
tightWorkerToJobEdges[workerIndex].forEach(jobIndex =>
assert(
workerPotential[workerIndex] + jobPotential[jobIndex] ==
Math.abs(workerFiles[workerIndex] - jobFiles[jobIndex]),
"Edge from worker " + workerIndex + " to job " + jobIndex + " is not actually tight " +
"worker potential " + workerPotential[workerIndex] + "job potential " +
jobPotential[jobIndex] + " cost " + Math.abs(workerFiles[workerIndex] - jobFiles[jobIndex])));
}
}
log("-------");
}
let totalCost = 0;
let totalPotential = 0;
for (let jobIndex = 0; jobIndex < jobToWorkerAssignments.length; jobIndex++) {
const workerIndex = jobToWorkerAssignments[jobIndex];
totalCost += Math.abs(jobFiles[jobIndex] - workerFiles[workerIndex]);
totalPotential += jobPotential[jobIndex] + workerPotential[workerIndex];
}
assert(totalCost == totalPotential,
"totalCost " + totalCost + " and totalPotential " + totalPotential + " disagree at end of algorithm" +
" worker potentials " + workerPotential.toString() + " job potentials " + jobPotential.toString());
return totalCost;
}
function solveSingleColor(pawns, side, used) {
/* Solve a single color position, assuming that the board is vertically infinite.
This is either the correct answer on the actual board, or the position is impossible,
but the impossibilities will be detected separately.
*/
const pawnCounts = [];
for (let file = 0; file < 8; file++) {
pawnCounts.push(pawns[side][file].length);
}
return solveSingleColorHungarian(pawnCounts, used);
}
function getTwoColorHeuristic(pawns, which, assignments) {
let whiteDistance = 0;
let blackDistance = 0;
if (which == 0 || which == 2) {
const used = [];
for (let file = 0; file < 8; file++) {
if (assignments[0][file][0] != -1) {
used.push(1);
} else {
used.push(0);
}
}
whiteDistance = solveSingleColor(pawns, 0, used);
}
if (which == 1 || which == 2) {
const used = [];
for (let file = 0; file < 8; file++) {
if (assignments[1][file][0] != -1) {
used.push(1);
} else {
used.push(0);
}
}
blackDistance = solveSingleColor(pawns, 1, used);
}
if (whiteDistance == IMPOSSIBLE || blackDistance == IMPOSSIBLE) {
return IMPOSSIBLE;
}
return whiteDistance + blackDistance;
}
function blockedPromotedPawn(pawns, side, file, rank) {
/*
If there is a blocked promoted pawn on this file for this side, then return the unblocked file that
the pawn could retract to.
If not, return -1.
*/
const lastRank = side == 0 ? 7 : 0;
const secondLastRank = side == 0 ? 6 : 1;
if (rank == lastRank && pawns[1 - side][file].includes(secondLastRank)) {
if ((file == 0 || pawns[1 - side][file - 1].includes(secondLastRank))) {
return file + 1;
} else if ((file == 7 || pawns[1 - side][file + 1].includes(secondLastRank))) {
return file - 1;
}
}
return -1;
}
function existsDirectPath(pawns, side, sourceSquare, targetSquare) {
if (sourceSquare[0] == targetSquare[0] && sourceSquare[1] == targetSquare[1]) return true;
const file = sourceSquare[0];
const rank = sourceSquare[1];
const pawnDir = side == 0 ? -1 : 1;
if (Math.sign(targetSquare[1] - rank) != pawnDir) return false;
if (Math.abs(targetSquare[1] - rank) < Math.abs(targetSquare[0] - file)) return false;
const newRank = rank + pawnDir;
const unblockedFile = blockedPromotedPawn(pawns, side, file, rank);
let searchOrder;
if (unblockedFile != -1) {
searchOrder = [unblockedFile];
} else if (targetSquare[0] < sourceSquare[0]) {
searchOrder = [file - 1, file];
} else if (targetSquare[0] == sourceSquare[0]) {
searchOrder = [file];
} else {
searchOrder = [file + 1, file];
}
return searchOrder.some(newFile =>
newFile >= 0 && newFile <= 7 && pawns[side][newFile].indexOf(newRank) == -1 &&
pawns[1 - side][newFile].indexOf(newRank) == -1 &&
existsDirectPath(pawns, side, [newFile, newRank], targetSquare)
);
}
function restore(object, removed) {
for (const key in removed) {
if (removed.hasOwnProperty(key)) {
object[key] = removed[key];
}
}
}
function previousEven(n) {
return n - (n % 2);
}
function nextEven(n) {
return n + (n % 2);
}
function evaluateHelper(pawns, bestPreviousLevel, whiteCapturesLeft, blackCapturesLeft, invertedAssignments, which,
specialConfigurationSide, cache, depth) {
if (whiteCapturesLeft < 0 || blackCapturesLeft < 0) {
return IMPOSSIBLE;
}
const sortedKeys = Object.keys(invertedAssignments).sort();
const sortedAssignments = {};
sortedKeys.forEach(key => {
sortedAssignments[key] = invertedAssignments[key];
});
const cacheKey = JSON.stringify([sortedAssignments, whiteCapturesLeft, blackCapturesLeft]);
const cacheLookup = cache[cacheKey];
if (cacheLookup && (cacheLookup.isExact || cacheLookup.result >= bestPreviousLevel)) {
return cacheLookup.result;
}
// first, try to simplify
let simplifiedValue = 0;
const newPawns = copyPawns(pawns);
const newInvertedAssignments = invertedAssignments;
const removed = {};
let simplified = true;
while (simplified) {
simplified = false;
for (const sourceSquare in newInvertedAssignments) {
if (newInvertedAssignments.hasOwnProperty(sourceSquare)) {
const side = (newInvertedAssignments[sourceSquare][1] == 1) ? 0 : 1;
const targetSquare = newInvertedAssignments[sourceSquare];
const file = parseInt(sourceSquare.charAt(0));
const rank = parseInt(sourceSquare.charAt(2));
// in a "special configuration" don't simplify the pawn that is on the promotion rank
if (specialConfigurationSide == side && rank == (side == 0 ? 7 : 0)) {
continue;
}
// we can't simplify on this file, if the target file or its adjacent files has an opposing pawn on the
// back rank from a promotion
const opponentBackRank = side == 0 ? 0 : 7;
const targetFile = targetSquare[0];
if (newPawns[1 - side][targetFile].includes(opponentBackRank) ||
(targetFile != 0 && newPawns[1 - side][targetFile - 1].includes(opponentBackRank)) ||
(targetFile != 7 && newPawns[1 - side][targetFile + 1].includes(opponentBackRank))) {
continue;
}
if (existsDirectPath(newPawns, side, [file, rank], targetSquare)) {
debugLog3("Simplifying pawn at " + file + " " + rank + " to " + targetFile, depth);
simplified = true;
removed[sourceSquare] = newInvertedAssignments[sourceSquare];
delete newInvertedAssignments[sourceSquare];
const index = newPawns[side][file].indexOf(rank);
assert(index != -1, rank + " was not found in " + newPawns[side][file] + " on side = "
+ side + " file = " + file);
newPawns[side][file].splice(index, 1);
let distance = 0;
distance += Math.abs(targetFile - file);
const unblockedFile = blockedPromotedPawn(newPawns, side, file, rank);
if (unblockedFile != -1 &&
(targetFile == file || Math.sign(targetFile - file) != Math.sign(unblockedFile - file))) {
distance += 2;
}
if (which == side || which == 2) {
simplifiedValue += distance;
}
if (getEnableSeparateCaptureTracking()) {
if (side == 0) {
whiteCapturesLeft -= distance;
} else {
blackCapturesLeft -= distance;
}
if (whiteCapturesLeft < 0 || blackCapturesLeft < 0) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(IMPOSSIBLE, true);
return IMPOSSIBLE;
}
}
}
}
}
}
let lowerBound = 0;
let best = bestPreviousLevel;
let keyFound = false;
let whiteZeroDistanceSquares = [], blackZeroDistanceSquares = [];
let whiteTotalDistance = 0, blackTotalDistance = 0;
for (const sourceSquare in newInvertedAssignments) {
if (newInvertedAssignments.hasOwnProperty(sourceSquare)) {
keyFound = true;
const side = (newInvertedAssignments[sourceSquare][1] == 1) ? 0 : 1;
const file = parseInt(sourceSquare.charAt(0));
const rank = parseInt(sourceSquare.charAt(2));
const pawnDir = side == 0 ? -1 : 1;
const targetFile = newInvertedAssignments[sourceSquare][0];
const targetRank = newInvertedAssignments[sourceSquare][1];
if (targetFile == file && targetRank == rank) {
if (side == 0) {
whiteZeroDistanceSquares.push([file, rank]);
} else {
blackZeroDistanceSquares.push([file, rank]);
}
continue;
}
if (Math.sign(targetRank - rank) != pawnDir) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(IMPOSSIBLE, true);
return IMPOSSIBLE;
}
if (Math.abs(targetRank - rank) < Math.abs(targetFile - file)) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(IMPOSSIBLE, true);
return IMPOSSIBLE;
}
const lastRank = side == 0 ? 7 : 0;
const secondLastRank = side == 0 ? 6 : 1;
if (rank == lastRank && newPawns[1 - side][file].includes(secondLastRank) &&
(file == 0 || newPawns[1 - side][file - 1].includes(secondLastRank)) &&
(file == 7 || newPawns[1 - side][file + 1].includes(secondLastRank))) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(IMPOSSIBLE, true);
return IMPOSSIBLE;
}
if (specialConfigurationSide == side && rank == (side == 0 ? 7 : 0)) {
continue;
}
let distance = 0;
distance += Math.abs(targetFile - file);
const unblockedFile = blockedPromotedPawn(newPawns, side, file, rank);
if (unblockedFile != -1 &&
(Math.sign(targetFile - file) == -Math.sign(unblockedFile - file))) {
distance += 2;
} else if (rank == lastRank) {
const thirdLastRank = secondLastRank + pawnDir;
for (const adjacentFile of [file - 1, file + 1]) {
if (adjacentFile >= 0 && adjacentFile <= 7 && targetFile == adjacentFile &&
newPawns[1 - side][file].includes(secondLastRank) &&
newPawns[1 - side][adjacentFile].includes(thirdLastRank) &&
newInvertedAssignments[[adjacentFile, thirdLastRank, 0]][0] == adjacentFile
) {
distance += 2;
break;
}
}
}
if (which == side || which == 2) {
lowerBound += distance;
}
if (side == 0) {
whiteTotalDistance += distance;
} else {
blackTotalDistance += distance;
}
if (whiteTotalDistance > whiteCapturesLeft || blackTotalDistance > blackCapturesLeft) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(IMPOSSIBLE, true);
return IMPOSSIBLE;
}
if (targetFile == file) {
if (side == 0) {
whiteZeroDistanceSquares.push([file, rank]);
} else {
blackZeroDistanceSquares.push([file, rank]);
}
}
}
}
let whiteLowerBound = 0, blackLowerBound = 0, eitherLowerBound = 0;
for (const [whiteFile, whiteRank] of whiteZeroDistanceSquares) {
for (const [blackFile, blackRank] of blackZeroDistanceSquares) {
if (whiteFile == blackFile && whiteRank > blackRank) {
if ([5, 6].includes(blackRank)) {
whiteLowerBound += 2;
} else if ([1, 2].includes(whiteRank)) {
blackLowerBound += 2;
} else {
eitherLowerBound += 2;
}
}
}
}
if (!getEnableSeparateCaptureTracking()) {
if (which == 0) {
lowerBound += whiteLowerBound;
} else if (which == 1) {
lowerBound += blackLowerBound;
} else {
lowerBound += whiteLowerBound + blackLowerBound + eitherLowerBound;
}
} else {
if (whiteTotalDistance + whiteLowerBound > whiteCapturesLeft ||
blackTotalDistance + blackLowerBound > blackCapturesLeft ||
whiteLowerBound + blackLowerBound + eitherLowerBound >
previousEven(whiteCapturesLeft - whiteTotalDistance) + previousEven(blackCapturesLeft - blackTotalDistance)) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(IMPOSSIBLE, true);
return IMPOSSIBLE;
}
if (which == 0) {
if (blackTotalDistance + blackLowerBound + eitherLowerBound > blackCapturesLeft) {
const excessBound = blackTotalDistance + blackLowerBound + eitherLowerBound - blackCapturesLeft;
whiteLowerBound += nextEven(excessBound);
}
if (whiteTotalDistance + whiteLowerBound > whiteCapturesLeft) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(IMPOSSIBLE, true);
return IMPOSSIBLE;
}
lowerBound += whiteLowerBound;
} else if (which == 1) {
if (whiteTotalDistance + whiteLowerBound + eitherLowerBound > whiteCapturesLeft) {
const excessBound = whiteTotalDistance + whiteLowerBound + eitherLowerBound - whiteCapturesLeft;
blackLowerBound += nextEven(excessBound);
}
if (blackTotalDistance + blackLowerBound > blackCapturesLeft) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(IMPOSSIBLE, true);
return IMPOSSIBLE;
}
lowerBound += blackLowerBound;
} else {
lowerBound += whiteLowerBound + blackLowerBound + eitherLowerBound;
}
}
debugLog3("Lower bound after simplification is " + (simplifiedValue + lowerBound), depth);
if (simplifiedValue + lowerBound >= bestPreviousLevel) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(simplifiedValue + lowerBound, false);
debugLog3("Early cutoff, lower bound >= bestPreviousLevel " + bestPreviousLevel, depth);
return simplifiedValue + lowerBound;
}
if (!keyFound) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(simplifiedValue, true);
debugLog3("Board is empty, returning value " + simplifiedValue, depth);
return simplifiedValue;
}
const keys = [];
for (const sourceSquare in newInvertedAssignments) {
if (newInvertedAssignments.hasOwnProperty(sourceSquare)) {
keys.push(sourceSquare);
}
}
for (const sourceSquare of keys) {
const side = (newInvertedAssignments[sourceSquare][1] == 1) ? 0 : 1;
const file = parseInt(sourceSquare.charAt(0));
const rank = parseInt(sourceSquare.charAt(2));
const keyIndex = parseInt(sourceSquare.charAt(4));
const pawnDir = side == 0 ? -1 : 1;
const targetFile = newInvertedAssignments[sourceSquare][0];
const originalRank = side == 0 ? 1 : 6;
let searchOrder;
if (targetFile < file) {
searchOrder = [file - 1, file, file + 1];
} else if (targetFile == file) {
searchOrder = [file, file - 1, file + 1];
} else {
searchOrder = [file + 1, file, file - 1];
}
if (rank != originalRank) {
const newRank = rank + pawnDir;
for (const newFile of searchOrder) {
let weight;
if (specialConfigurationSide == side && rank == (side == 0 ? 7 : 0)) {
weight = 0;
} else {
weight = (newFile != file && (which == 2 || which == side)) ? 1 : 0;
}
if (newFile >= 0 && newFile <= 7 && simplifiedValue + weight < best &&
newPawns[side][newFile].indexOf(newRank) == -1 &&
newPawns[1 - side][newFile].indexOf(newRank) == -1) {
const index = newPawns[side][file].indexOf(rank);
newPawns[side][file].splice(index, 1);
newPawns[side][newFile].push(newRank);
let newKeyIndex = 0;
while ([newFile, newRank, newKeyIndex] in newInvertedAssignments) {
newKeyIndex++;
}
newInvertedAssignments[[newFile, newRank, newKeyIndex]] = newInvertedAssignments[[file, rank, keyIndex]];
const originalAssignment = newInvertedAssignments[[file, rank, keyIndex]];
delete newInvertedAssignments[[file, rank, keyIndex]];
debugLog3("Moving pawn from " + file + " " + rank + " to " + newFile + " " + newRank, depth);
const recursiveValue = evaluateHelper(
newPawns, best - simplifiedValue - weight,
getEnableSeparateCaptureTracking() ? whiteCapturesLeft - ((side == 0 && newFile != file) ? 1 : 0) : whiteCapturesLeft,
getEnableSeparateCaptureTracking() ? blackCapturesLeft - ((side == 1 && newFile != file) ? 1 : 0) : blackCapturesLeft,
newInvertedAssignments, which,
specialConfigurationSide, cache, depth + 1);
const recursiveBest = simplifiedValue + weight + recursiveValue;
debugLog3("Evaluation is " + recursiveBest, depth);
if (recursiveBest < best) best = recursiveBest;
debugLog3("Unmoving pawn from " + newFile + " " + newRank + " to " + file + " " + rank, depth);
newPawns[side][newFile].splice(newPawns[side][newFile].length - 1, 1);
newPawns[side][file].push(rank);
newInvertedAssignments[[file, rank, keyIndex]] = originalAssignment;
delete newInvertedAssignments[[newFile, newRank, newKeyIndex]];
if (best == simplifiedValue + lowerBound) {
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(best, true);
debugLog3("Reached lower bound, returning " + best, depth);
return best;
}
}
}
}
}
restore(invertedAssignments, removed);
cache[cacheKey] = new PawnCapturesCacheResult(best, true);
debugLog3("Tried all moves, returning " + best, depth);
return best;
}
function evaluate(assignments, which, specialConfigurationSide, bestResult, whiteCapturesLeft, blackCapturesLeft) {
const startTime = Date.now();
const pawns = [[], []];
const invertedAssignments = {};
for (let file = 0; file < 8; file++) {
pawns[0].push([]);
pawns[1].push([]);
}
for (let side = 0; side < 2; side++) {
for (let file = 0; file < 8; file++) {
if (assignments[side][file][0] != -1) {
pawns[side][assignments[side][file][0]].push(assignments[side][file][1]);
let index = 0;
while ([assignments[side][file][0], assignments[side][file][1], index] in invertedAssignments) {
index++;
}
invertedAssignments[[assignments[side][file][0], assignments[side][file][1], index]] = [
file, side == 0 ? 1 : 6
];
}
}
}
const cache = (specialConfigurationSide != -1 ? {} : (which == 0 ? evaluateHelperCache.whitePawnCapturesCache :
(which == 1 ? evaluateHelperCache.blackPawnCapturesCache : evaluateHelperCache.totalPawnCapturesCache)));
const result = evaluateHelper(pawns, bestResult, whiteCapturesLeft, blackCapturesLeft, invertedAssignments, which,
specialConfigurationSide, cache, 0);
const stopTime = Date.now();
const timeTaken = (stopTime - startTime) / 1000.0;
if (timeTaken > 0.01) {
debugLog2(assignmentsToString(assignments));
debugLog2("evaluate(assignments, " +
[which, specialConfigurationSide, bestResult, whiteCapturesLeft, blackCapturesLeft].join(",")
+ ")", 0);
debugLog2(timeTaken + " seconds");
}
return result;
}
function findPawnToAssign(pawns, which) {
/*
If which == 2 (counting total captures), then search in order:
white's 2nd rank, black's 2nd rank, white's 3rd rank, black's 3rd rank, ...
Otherwise we are counting only one side's captures. Start with the side whose
captures are not being counted, and search their 2nd, 3rd, ... ranks; then do
the same for the side whose captures are being counted.
*/
if (which == 2) {
for (let relativeRank = 1; relativeRank <= 7; relativeRank++) {
for (let side = 0; side <= 1; side++) {
const rank = side == 0 ? relativeRank : 7 - relativeRank;
for (let file = 0; file < 8; file++) {
const index = pawns[side][file].indexOf(rank);
if (index != -1) {
return [side, file, index];
}
}
}
}
} else {
for (let side in [1 - which, which]) {
for (let relativeRank = 1; relativeRank <= 7; relativeRank++) {
const rank = side == 0 ? relativeRank : 7 - relativeRank;
for (let file = 0; file < 8; file++) {
const index = pawns[side][file].indexOf(rank);
if (index != -1) {
return [side, file, index];
}
}
}
}
}
assert(false, "Empty board, shouldn't have gotten here.");
}
function assignmentsToString(assignments) {
let result = "assignments = [";
for (let side = 0; side < 2; side++) {
if (side == 0) {
result += "[";
} else {
result += "],[";
}
for (let file = 0; file < 8; file++) {
result += "[" + assignments[side][file] + "]";
if (file < 7) {
result += ","
}
}
}
result += "]];"
return result;
}
function search(searchState, which, specialConfigurationSide, bestResult, whiteCapturesLeft, blackCapturesLeft, heap) {
debugLog2("Searching: ");
debugLog2("which = " + which);
debugLog2("Estimated distance: " + searchState.estimatedDistance);
const pawns = searchState.position;
const assignments = searchState.assignments;
// first, check for empty board
let emptyBoard = true;
for (let searchFile = 0; searchFile < 8; searchFile++) {
if (pawns[0][searchFile].length > 0 || pawns[1][searchFile].length > 0) {
emptyBoard = false;
break;
}
}
if (emptyBoard) {
return searchState.estimatedDistance;
}
const [side, file, index] = findPawnToAssign(pawns, which);
const oneSidePawns = pawns[side];
if (oneSidePawns[file].length > 0) {
const newPawns = copyPawns(pawns);
const rank = oneSidePawns[file][index];
newPawns[side][file].splice(index, 1);
const maxDistance = (side == 0) ? rank - 1 : 6 - rank;
let leftmostFile = Math.max(file - maxDistance, 0);
let rightmostFile = Math.min(file + maxDistance, 7);
const lastRank = side == 0 ? 7 : 0;
const secondLastRank = (side == 0) ? 1 : 6;
const thirdLastRank = (side == 0) ? 2 : 5;
if (file == 0 && rank == lastRank && newPawns[1 - side][1].includes(secondLastRank)) {
rightmostFile = 5;
} else if (file == 7 && rank == lastRank && newPawns[1 - side][6].includes(secondLastRank)) {
leftmostFile = 2;
} else if (file == 1 && rank == lastRank) {
if (newPawns[1 - side][2].includes(secondLastRank)) {
rightmostFile--;
if (newPawns[1 - side][1].includes(secondLastRank)) {
rightmostFile--;
if (newPawns[1 - side][1].includes(thirdLastRank)) {
rightmostFile--;
}
}
}
} else if (file == 6 && rank == lastRank) {
if (newPawns[1 - side][5].includes(secondLastRank)) {
leftmostFile++;
if (newPawns[1 - side][6].includes(secondLastRank)) {
leftmostFile++;
if (newPawns[1 - side][6].includes(thirdLastRank)) {
leftmostFile++;
}
}
}
}
for (let newFile = leftmostFile; newFile <= rightmostFile; newFile++) {
if (assignments[side][newFile][0] != -1) continue;
debugLog2("Assigning pawn at: " + file + " " + rank + " to: " + newFile);
const newAssignments = copyAssignments(assignments);
newAssignments[side][newFile][0] = file;
newAssignments[side][newFile][1] = rank;
const heuristicEstimate = getTwoColorHeuristic(newPawns, which, newAssignments);
if (heuristicEstimate != IMPOSSIBLE) {
const value = evaluate(newAssignments, which, specialConfigurationSide, bestResult - heuristicEstimate,
whiteCapturesLeft, blackCapturesLeft);
if (value != IMPOSSIBLE) {
const newState = new PawnCaptureSearchState(newPawns, newAssignments, value + heuristicEstimate);
insertIntoHeap(newState, heap);
debugLog2("New estimated distance: " + (value + heuristicEstimate));
} else {
debugLog2("Evaluation is impossible");
}
} else {
debugLog2("Heuristic estimate is impossible");
}
}
}
}
function getNextState(heap) {
const nextState = heap[0];
heap[0] = heap[heap.length - 1];
heap.splice(heap.length - 1, 1); // delete last element
let index = 0;
while (
(2 * index + 1 < heap.length &&
heap[2 * index + 1].estimatedDistance < heap[index].estimatedDistance) ||
(2 * index + 2 < heap.length &&
heap[2 * index + 2].estimatedDistance < heap[index].estimatedDistance)) { // sift down
let newIndex = 2 * index + 1;
if (2 * index + 2 < heap.length &&
heap[2 * index + 2].estimatedDistance < heap[2 * index + 1].estimatedDistance) {
newIndex = 2 * index + 2;
}
const temp = heap[index];
heap[index] = heap[newIndex];
heap[newIndex] = temp;
index = newIndex;
}
return nextState;
}