-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsumego.js
3516 lines (3516 loc) · 149 KB
/
tsumego.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
var tsumego;
(function (tsumego) {
var stat;
(function (stat) {
stat.logv = [];
stat.summarizxe = () => stat.logv.map(f => f());
})(stat = tsumego.stat || (tsumego.stat = {}));
})(tsumego || (tsumego = {}));
var tsumego;
(function (tsumego) {
let color;
(function (color) {
color[color["black"] = 1] = "black";
color[color["white"] = -1] = "white";
})(color = tsumego.color || (tsumego.color = {}));
})(tsumego || (tsumego = {}));
var tsumego;
(function (tsumego) {
class SortedArray {
/**
* The items will be sorted in such a way that
* compare(flags[i], flags[i + 1]) <= 0 for every i:
* To sort items in a specific order:
*
* ascending: (a, b) => a - b
* descending: (a, b) => b - a
*
* To sort first by one field in the ascneding order
* and then by another field in the descending order:
*
* (a, b) =>
* a[0] - b[0] ||
* a[1] - b[1];
*
* This is exactly how Array::sort works.
*/
constructor() {
}
reset() {
this.flags = [];
this.items = [];
return this.items;
}
/**
* Inserts a new item in a "stable" way, i.e.
* if items are taken from one array which is
* sorted according to some criteria #A and inserted
* into this array, not only the items will be
* sorted here by the new criteria #B, but also items
* for which #B doesn't define a specific order
* (returns zero in other words), will be correctly
* ordered according to #A. More strictly, for any i < j:
*
* 1. B(sa[i], sa[j]) <= 0
* 2. if B(sa[i], sa[j]) = 0 then A(sa[i], sa[j]) <= 0
*
* This property allows to compose a few sorted arrays.
*/
insert(item, flag) {
const { items, flags } = this;
let i = items.length;
// it sounds crazy, but passing around this single number
// inside a one element array is way faster than passing
// this number alone: 10s vs 14s (!)
while (i > 0 && flags[i - 1][0] < flag[0])
i--;
// using .push when i == n and .unshift when i == 0
// won't make the solver run faster
items.splice(i, 0, item);
flags.splice(i, 0, flag);
return i;
}
}
tsumego.SortedArray = SortedArray;
})(tsumego || (tsumego = {}));
/// <reference path="sorted.ts" />
var tsumego;
(function (tsumego) {
tsumego.min = (a, b) => a < b ? a : b;
tsumego.max = (a, b) => a > b ? a : b;
tsumego.abs = (a) => a < 0 ? -a : a;
tsumego.sign = (x) => x < 0 ? -1 : x > 0 ? +1 : 0;
tsumego.nesw = [[-1, 0], [+1, 0], [0, -1], [0, +1]];
function* region(root, belongs, neighbors = tsumego.stone.neighbors) {
const body = [];
const edge = [root];
while (edge.length > 0) {
const xy = edge.pop();
yield xy;
body.push(xy);
for (const nxy of neighbors(xy))
if (belongs(nxy, xy) && body.indexOf(nxy) < 0 && edge.indexOf(nxy) < 0)
edge.push(nxy);
}
}
tsumego.region = region;
tsumego.b4 = (b0, b1, b2, b3) => b0 | b1 << 8 | b2 << 16 | b3 << 24;
tsumego.b0 = (b) => b & 255;
tsumego.b1 = (b) => b >> 8 & 255;
tsumego.b2 = (b) => b >> 16 & 255;
tsumego.b3 = (b) => b >> 24 & 255;
tsumego.b_ = (b) => [tsumego.b0(b), tsumego.b1(b), tsumego.b2(b), tsumego.b3(b)];
function sequence(length, item) {
const items = [];
for (let i = 0; i < length; i++)
items[i] = item instanceof Function ? item(i) : item;
return items;
}
tsumego.sequence = sequence;
tsumego.hex = (x) => (0x100000000 + x).toString(16).slice(-8);
tsumego.rcl = (x, n) => x << n | x >>> (32 - n);
function memoized(fn, hashArgs) {
const cache = {};
return fn && function (x) {
const h = hashArgs(x);
return h in cache ? cache[h] : cache[h] = fn(x);
};
}
tsumego.memoized = memoized;
/** e.g. @enumerable(false) */
function enumerable(isEnumerable) {
return (p, m, d) => void (d.enumerable = isEnumerable);
}
tsumego.enumerable = enumerable;
function assert(condition) {
if (!condition)
debugger;
}
tsumego.assert = assert;
tsumego.n32b = (d) => ({
parse(x) {
const r = {};
for (let name in d) {
const { offset, length, signed = false } = d[name];
const value = x << 32 - offset - length >> 32 - length;
r[name] = signed ? value : value & (1 << length) - 1;
}
return r;
}
});
})(tsumego || (tsumego = {}));
var tsumego;
(function (tsumego) {
const kCoord = 0x20000000;
const kColor = 0x40000000;
const kWhite = 0x80000000;
/**
* 0 1 2 3
* 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | x | y | r | | k |h|c|w|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* x - the x coord (valid only if h = 1)
* y - the y coord (valid only if h = 1)
* h - whether the stone has coordinates
* c - whether the stone has a color
* w - whether the stone is white (valid if c = 1)
* r - depth at which repetition occurs
* k - who is the ko master: +1, 0, -1
*/
let stone;
(function (stone) {
})(stone = tsumego.stone || (tsumego.stone = {}));
(function (stone) {
function make(x, y, color) {
return x | y << 4 | kCoord | (color && kColor) | color & kWhite;
}
stone.make = make;
})(stone = tsumego.stone || (tsumego.stone = {}));
(function (stone) {
stone.nocoords = (color) => kColor | color & kWhite;
stone.color = (m) => (m & kColor) && (m & kWhite ? -1 : +1);
stone.setcolor = (m, c) => m & ~kColor & ~kWhite | (c && kColor) | c & kWhite;
stone.hascoords = (m) => !!(m & kCoord);
stone.x = (m) => m & 15;
stone.y = (m) => m >> 4 & 15;
stone.coords = (m) => [stone.x(m), stone.y(m)];
stone.same = (a, b) => !((a ^ b) & 255);
stone.dist = (a, b) => Math.abs(stone.x(a) - stone.x(b)) + Math.abs(stone.y(a) - stone.y(b));
stone.move = (s, dx, dy) => stone.x(s) + dx & 15 | (stone.y(s) + dy & 15) << 4 | s & ~255;
stone.neighbors = (m) => {
const [x, y] = stone.coords(m);
const c = stone.color(m);
return [
x <= 0x0 ? 0 : stone.make(x - 1, y, c),
x >= 0xF ? 0 : stone.make(x + 1, y, c),
y <= 0x0 ? 0 : stone.make(x, y - 1, c),
y >= 0xF ? 0 : stone.make(x, y + 1, c)
];
};
stone.diagonals = (m) => {
const [x, y] = stone.coords(m);
const c = stone.color(m);
return [
x <= 0x0 || y <= 0x0 ? 0 : stone.make(x - 1, y - 1, c),
x >= 0xF || y <= 0x0 ? 0 : stone.make(x + 1, y - 1, c),
x <= 0x0 || y >= 0xF ? 0 : stone.make(x - 1, y + 1, c),
x >= 0xF || y >= 0xF ? 0 : stone.make(x + 1, y + 1, c)
];
};
class Set {
constructor(items) {
this.stones = [];
if (items)
for (const s of items)
this.stones.push(s);
}
toString() {
return this.stones.sort((a, b) => a - b).map(stone.toString).join('');
}
has(s) {
for (const x of this.stones)
if (stone.same(x, s))
return true;
return false;
}
add(...stones) {
for (const s of stones)
if (!this.has(s))
this.stones.push(s);
}
remove(p) {
for (let i = this.stones.length - 1; i >= 0; i--) {
const q = this.stones[i];
if (typeof p === 'function' ? p(q) : stone.same(p, q))
this.stones.splice(i, 1);
}
}
map(mapping) {
const mapped = new Set;
for (const s of this) {
const q = mapping(s);
if (!q)
return null;
mapped.add(q);
}
return mapped;
}
/** Adds the item if it wasn't there or removes it otherwise. */
xor(s) {
if (this.has(s))
this.remove(s);
else
this.add(s);
}
empty() {
this.stones = [];
}
get rect() {
let r = 0;
for (const s of this)
r = tsumego.block.join(r, tsumego.block.just(s));
return r;
}
get size() {
return this.stones.length;
}
*[Symbol.iterator]() {
for (const s of this.stones)
yield s;
}
}
stone.Set = Set;
})(stone = tsumego.stone || (tsumego.stone = {}));
tsumego.infdepth = 255; // only 8 bits available for storing the depth
/**
* If b(1), b(2), ... is the sequence of positions leading
* to the current position and the sub tree (sub graph, actually)
* of positions that proves the solution contains any of
* b(i), then repd.get(solution) = i.
*/
let repd;
(function (repd_1) {
repd_1.get = move => move >> 8 & 255;
repd_1.set = (move, repd) => move & ~0xFF00 | repd << 8;
})(repd = tsumego.repd || (tsumego.repd = {}));
(function (stone) {
let km;
(function (km_1) {
km_1.get = (s) => s << 3 >> 30; // the signed shift
km_1.set = (s, km) => s & ~0x18000000 | (km & 3) << 27;
})(km = stone.km || (stone.km = {}));
})(stone = tsumego.stone || (tsumego.stone = {}));
(function (stone) {
let label;
(function (label_1) {
/** W -> -1, B -> +1 */
function color(label) {
if (label == 'B')
return +1;
if (label == 'W')
return -1;
return 0;
}
label_1.color = color;
/** -1 -> W, +1 -> B */
function string(color) {
if (color > 0)
return 'B';
if (color < 0)
return 'W';
}
label_1.string = string;
})(label = stone.label || (stone.label = {}));
})(stone = tsumego.stone || (tsumego.stone = {}));
(function (stone) {
const n2s = (n) => String.fromCharCode(n + 0x61); // 0 -> `a`, 3 -> `d`
const s2n = (s) => s.charCodeAt(0) - 0x61; // `d` -> 43 `a` -> 0
/** e.g. W[ab], [ab], W[] */
function toString(m) {
const c = stone.color(m);
const [x, y] = stone.coords(m);
const s = !stone.hascoords(m) ? '' : n2s(x) + n2s(y);
const t = stone.label.string(c) || '';
const _nr = repd.get(m);
return t + '[' + s + ']'
+ (_nr ? ' depth=' + _nr : '');
}
stone.toString = toString;
function fromString(s) {
if (s == 'B' || s == 'B[]')
return stone.nocoords(+1);
if (s == 'W' || s == 'W[]')
return stone.nocoords(-1);
if (!/^[BW]\[[a-z]{2}\]|[a-z]{2}$/.test(s))
return 0;
const c = { B: +1, W: -1 }[s[0]] || 0;
if (c)
s = s.slice(2);
const x = s2n(s[0]);
const y = s2n(s[1]);
return stone.make(x, y, c);
}
stone.fromString = fromString;
let list;
(function (list) {
list.toString = (x) => '[' + x.map(stone.toString).join(',') + ']';
})(list = stone.list || (stone.list = {}));
})(stone = tsumego.stone || (tsumego.stone = {}));
(function (stone) {
let cc;
(function (cc) {
/** 0x25 -> "E2" */
function toString(s, boardSize) {
const x = stone.x(s);
const y = stone.y(s);
const xs = String.fromCharCode('A'.charCodeAt(0) + (x < 8 ? x : x + 1)); // skip the I letter
const ys = (boardSize - y) + '';
return xs + ys;
}
cc.toString = toString;
})(cc = stone.cc || (stone.cc = {}));
})(stone = tsumego.stone || (tsumego.stone = {}));
})(tsumego || (tsumego = {}));
var tsumego;
(function (tsumego) {
// en.wikipedia.org/wiki/Mersenne_Twister
// oeis.org/A221557
var s, m;
/** Returns a random 32 bit number. MT 19937. */
function rand() {
if (s >= 624) {
for (let i = 0; i < 624; i++) {
let y = m[i] & 0x80000000 | m[(i + 1) % 624] & 0x7fffffff;
m[i] = m[(i + 397) % 624] ^ y >> 1;
if (y & 1)
m[i] = m[i] ^ 0x9908b0df;
}
s = 0;
}
let y = m[s++];
y ^= y >>> 11;
y ^= y << 7 & 2636928640;
y ^= y << 15 & 4022730752;
y ^= y >>> 18;
return y;
}
tsumego.rand = rand;
(function (rand) {
/**
* By default it's initialized to Date.now(), but
* can be changed to something else before using
* the solver.
*/
function seed(value) {
s = 624;
m = [value];
for (let i = 1; i < 624; i++)
m[i] = (m[i - 1] ^ m[i - 1] >> 30) + i | 0;
}
rand.seed = seed;
seed(0);
})(rand = tsumego.rand || (tsumego.rand = {}));
/** Returns a random number in the 0..1 range. */
tsumego.random = () => Math.abs(rand() / 0x80000000);
})(tsumego || (tsumego = {}));
var tsumego;
(function (tsumego) {
var profile;
(function (profile) {
profile.enabled = true;
profile.now = typeof performance === 'undefined' ?
() => Date.now() :
() => performance.now();
const timers = {};
const counters = {};
const distributions = {};
function reset() {
for (let name in timers)
timers[name] = 0;
profile.started = profile.now();
}
profile.reset = reset;
function log() {
if (profile.started >= 0) {
const total = profile.now() - profile.started;
console.log(`Total: ${(total / 1000).toFixed(2)}s`);
for (let name in timers)
console.log(`${name}: ${(timers[name] / total) * 100 | 0}%`);
}
if (Object.keys(counters).length > 0) {
console.log('counters:');
for (let name in counters)
console.log(` ${name}: ${counters[name]}`);
}
if (Object.keys(distributions).length > 0) {
console.log('distributions:');
for (let name in distributions) {
const d = distributions[name];
const n = d.length;
let lb, rb, min, max, sum = 0;
for (let i = 0; i < n; i++) {
if (d[i] === undefined)
continue;
rb = i;
if (lb === undefined)
lb = i;
if (min === undefined || d[i] < min)
min = d[i];
if (max === undefined || d[i] > max)
max = d[i];
sum += d[i];
}
console.log(` ${name}:`);
for (let i = lb; i <= rb; i++)
if (d[i] !== undefined)
console.log(` ${i}: ${d[i]} = ${d[i] / sum * 100 | 0}%`);
}
}
}
profile.log = log;
function _time(name, fn) {
if (!profile.enabled)
return fn;
timers[name] = 0;
return function (...args) {
const started = profile.now();
try {
return fn.apply(this, args);
}
finally {
timers[name] += profile.now() - started;
}
};
}
profile._time = _time;
/** Measures time taken by all invocations of the method. */
function time(prototype, method, d) {
d.value = _time(prototype.constructor.name + '::' + method, d.value);
}
profile.time = time;
class Counter {
constructor(name) {
this.name = name;
counters[name] = 0;
}
inc(n = 1) {
counters[this.name] += n;
}
}
profile.Counter = Counter;
class Distribution {
constructor(name) {
this.d = distributions[name] = [];
}
inc(value, n = 1) {
this.d[value] = (this.d[value] | 0) + n;
}
}
profile.Distribution = Distribution;
})(profile = tsumego.profile || (tsumego.profile = {}));
})(tsumego || (tsumego = {}));
/**
* LL(*) recursive descent parser.
*
* en.wikipedia.org/wiki/Recursive_descent_parser
*/
var tsumego;
(function (tsumego) {
var LL;
(function (LL) {
class Pattern {
constructor(_exec) {
this._exec = _exec;
}
exec(str, pos) {
const r = this._exec(str, pos || 0);
if (typeof pos === 'number')
return r;
if (r && r[1] == str.length)
return r[0];
return null;
}
map(fn) {
return new Pattern((str, pos) => {
const r = this.exec(str, pos);
return r ? [fn(r[0]), r[1]] : null;
});
}
take(i) {
return this.map(r => r[i]);
}
slice(from, to) {
return this.map((r) => r.slice(from, to));
}
/** [["A", 1], ["B", 2]] -> { A: 1, B: 2 } */
fold(keyName, valName, merge = (a, b) => b) {
return this.map((r) => {
const m = {};
for (const p of r) {
const k = p[keyName];
const v = p[valName];
m[k] = merge(m[k], v);
}
return m;
});
}
rep(min = 0) {
return new Pattern((str, pos) => {
const res = [];
let r;
while (r = this.exec(str, pos)) {
res.push(r[0]);
pos = r[1];
}
return res.length >= min ? [res, pos] : null;
});
}
}
LL.Pattern = Pattern;
LL.rgx = (r) => new Pattern((str, pos) => {
const m = r.exec(str.slice(pos));
return m && m.index == 0 ? [m[0], pos + m[0].length] : null;
});
LL.txt = (s) => new Pattern((str, pos) => {
return str.slice(pos, pos + s.length) == s ? [s, pos + s.length] : null;
});
function seq(...ps) {
return new Pattern((str, pos) => {
const res = [];
for (const p of ps) {
const r = p.exec(str, pos);
if (!r)
return null;
res.push(r[0]);
pos = r[1];
}
return [res, pos];
});
}
LL.seq = seq;
})(LL = tsumego.LL || (tsumego.LL = {}));
})(tsumego || (tsumego = {}));
/// <reference path="llrdp.ts" />
/**
* SGF parser.
*
* www.red-bean.com/sgf
*/
var tsumego;
(function (tsumego) {
var SGF;
(function (SGF) {
const { txt, rgx, seq } = tsumego.LL;
var Pattern = tsumego.LL.Pattern;
/**
* EBNF rules:
*
* val = "[" ... "]"
* tag = 1*("A".."Z") 0*val
* step = ";" 0*tag
* sgf = "(" 0*stp 0*sgf ")"
*/
const pattern = (() => {
var val = rgx(/\s*\[[^\]]*?\]/).map(s => s.trim().slice(+1, -1));
var tag = seq(rgx(/\s*\w+/).map(s => s.trim()), val.rep());
var step = seq(rgx(/\s*;/), tag.rep()).take(1).fold(0, 1, (a, b) => (a || []).concat(b));
var sgf_fwd = new Pattern((s, i) => sgf.exec(s, i));
var sgf = seq(rgx(/\s*\(\s*/), step.rep(), sgf_fwd.rep(), rgx(/\s*\)\s*/)).map(r => new Node(r[1], r[2]));
return sgf;
})();
class Node {
constructor(steps, vars) {
this.steps = steps;
this.vars = vars;
}
get(tag) {
return this.steps[0][tag];
}
}
SGF.Node = Node;
// decorators break the source-map-support tool
Object.defineProperty(Node.prototype, 'get', {
enumerable: false
});
SGF.parse = (source) => pattern.exec(source);
})(SGF = tsumego.SGF || (tsumego.SGF = {}));
})(tsumego || (tsumego = {}));
var tsumego;
(function (tsumego) {
class Stack {
constructor() {
this.items = [];
this.length = 0;
}
push(item) {
this.items[this.length++] = item;
}
pop() {
return this.length > 0 ? this.items[--this.length] : null;
}
*[Symbol.iterator]() {
for (let i = 0; i < this.length; i++)
yield this.items[i];
}
}
tsumego.Stack = Stack;
})(tsumego || (tsumego = {}));
/// <reference path="utils.ts" />
/// <reference path="stone.ts" />
/// <reference path="rand.ts" />
/// <reference path="prof.ts" />
/// <reference path="sgf.ts" />
/// <reference path="stack.ts" />
var tsumego;
(function (tsumego) {
tsumego._n_play = 0;
tsumego._n_redo = 0;
/**
* A block descriptor is represented by a 32 bit signed integer:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | xmin | xmax | ymin | ymax | libs | size |c|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* The first 2 bytes describe the rectangular boundaries of the block.
* This implies that blocks must fit in 16x16 board.
*
* Next byte contains the number of liberties. Most of the blocks
* hardly have 20 libs, so 8 bits should be more than enough.
*
* The first 7 bits of the last byte contain the number of stones
* in the block, which gives up to 128 stones. Most of the blocks have
* less than 15 stones.
*
* The last bit is the sign bit of the number and it tells the color
* of the block: 0 = black, 1 = white. This implies that black blocks
* are positive and white blocks are negative.
*
* Since a block a removed when it loses its last liberty, blocks with
* libs = 0 or size = 0 do not represent any real entity on the board.
*/
let block;
(function (block) {
})(block = tsumego.block || (tsumego.block = {}));
(function (block) {
function make(xmin, xmax, ymin, ymax, libs, size, color) {
return xmin | xmax << 4 | ymin << 8 | ymax << 12 | libs << 16 | size << 24 | color & 0x80000000;
}
block.make = make;
block.xmin = (b) => b & 15;
block.xmax = (b) => b >> 4 & 15;
block.ymin = (b) => b >> 8 & 15;
block.ymax = (b) => b >> 12 & 15;
block.dims = (b) => [block.xmin(b), block.xmax(b), block.ymin(b), block.ymax(b)];
block.libs = (b) => b >> 16 & 255;
block.size = (b) => b >> 24 & 127;
/** block.join(0, r) returns r */
block.join = (b1, b2) => !b1 ? b2 : block.make(tsumego.min(block.xmin(b1), block.xmin(b2)), tsumego.max(block.xmax(b1), block.xmax(b2)), tsumego.min(block.ymin(b1), block.ymin(b2)), tsumego.max(block.ymax(b1), block.ymax(b2)), 0, 0, 0);
/** returns a 1 x 1 block */
block.just = (s) => {
const x = tsumego.stone.x(s);
const y = tsumego.stone.y(s);
return block.make(x, x, y, y, 0, 0, s);
};
/** A pseudo block descriptor with 1 liberty. */
block.lib1 = block.make(0, 0, 0, 0, 1, 0, 0);
/** Useful when debugging. */
block.toString = (b) => !b ? null : (b > 0 ? '+' : '-') +
'[' + block.xmin(b) + ', ' + block.xmax(b) + ']x' +
'[' + block.ymin(b) + ', ' + block.ymax(b) + '] ' +
'libs=' + block.libs(b) + ' ' + 'size=' + block.size(b);
})(block = tsumego.block || (tsumego.block = {}));
/**
* A square board with size up to 16x16.
*
* The board's internal representation supports
* very fast play(x, y, color) and undo() operations.
*/
class Board {
constructor(size, setup) {
this.hash_b = 0; // low 32 bits of the 64 bit hash
this.hash_w = 0; // hi 32 bits of the 64 bit hash
/**
* blocks[id] = a block descriptor with this block.id
*
* When block #1 is merged with block #2, its size is
* reset to 0 and its libs is set to #2's id: this trick
* allows to not modify the board table too often.
*
* This means that to get the block libs and other data
* it's necessary to walk up the chain of merged blocks.
* This operation is called "lifting" of the block id.
*
* When a block is captured, blocks[id] is reset to 0,
* but the corresponding elements in the board table
* aren't changed.
*
* Elements in this array are never removed. During the
* lifetime of a block, its descriptor is changed and when
* the block is captured, its descriptor is nulled, but is
* never removed from the array.
*/
this.blocks = [0];
this._redo_hist = 0; // tells when the cache is valid
this._area = tsumego.sequence(256, () => 0);
/**
* A random 32 bit number for each intersection in the 16x16 board.
* The hash of the board is then computed as H(B) = XOR Q(i, j) where
*
* Q(i, j) = hashtb[i, j] if B(i, j) is a B stone
* Q(i, j) = hashtw[i, j] if B(i, j) is a W stone
*
* This is also known as Zobrist hashing.
*/
this.hasht_b = tsumego.sequence(256, tsumego.rand);
this.hasht_w = tsumego.sequence(256, tsumego.rand);
if (typeof size === 'string' || typeof size === 'object')
this.initFromSGF(size, setup);
else if (typeof size === 'number') {
this.init(size);
if (setup instanceof Array)
this.initFromTXT(setup);
}
}
/**
* The 32 bit hash of the board. It's efficiently
* recomputed after each move.
*/
get hash() {
return this.hash_b & 0x0000FFFF | this.hash_w & 0xFFFF0000;
}
get sgf() {
return this.toStringSGF();
}
set sgf(value) {
this.initFromSGF(value);
}
get text() {
return this.toStringTXT();
}
set text(value) {
this.initFromTXT(value.split(/\r?\n/));
}
init(size) {
if (size > 16)
throw Error(`Board ${size}x${size} is too big. Up to 16x16 boards are supported.`);
this.size = size;
this.table = tsumego.sequence(256, () => 0);
this.drop();
}
initFromTXT(rows) {
rows.map((row, y) => {
row.replace(/\s/g, '').split('').map((chr, x) => {
let c = chr == 'X' ? +1 : chr == 'O' ? -1 : 0;
if (c && !this.play(tsumego.stone.make(x, y, c)))
throw new Error('Invalid setup.');
});
});
this.drop();
}
initFromSGF(source, nvar) {
const sgf = typeof source === 'string' ? tsumego.SGF.parse(source) : source;
if (!sgf)
throw new SyntaxError('Invalid SGF: ' + source);
const setup = sgf.steps[0]; // ;FF[4]SZ[19]...
const size = +setup['SZ'];
if (!size)
throw SyntaxError('SZ[n] tag must specify the size of the board.');
this.init(size);
const place = (stones, tag) => {
if (!stones)
return;
for (const xy of stones) {
const s = tag + '[' + xy + ']';
if (!this.play(tsumego.stone.fromString(s)))
throw new Error(s + ' cannot be added.');
}
};
function placevar(node) {
place(node.steps[0]['AW'], 'W');
place(node.steps[0]['AB'], 'B');
}
placevar(sgf);
if (nvar)
placevar(sgf.vars[nvar - 1]);
this.drop();
}
/** Drops the history of moves. */
drop() {
this.history = {
added: new tsumego.Stack(),
hashes: new tsumego.Stack(),
changed: new tsumego.Stack(),
};
for (let i = 0; i < 256; i++)
this.table[i] = this.lift(this.table[i]);
this._redo_data = null;
this._redo_hist = 0;
}
/**
* Clones the board and without the history of moves.
* It essentially creates a shallow copy of the board.
*/
fork() {
const b = new Board(0);
b.size = this.size;
b.hash_b = this.hash_b;
b.hash_w = this.hash_w;
b.blocks = this.blocks.slice(0);
for (let i = 0; i < 256; i++)
b.table[i] = this.table[i];
b.drop();
return b;
}
get(x, y) {
if (y === void 0) {
if (!tsumego.stone.hascoords(x))
return 0;
[x, y] = tsumego.stone.coords(x);
}
return this.blocks[this.getBlockId(x, y)];
}
lift(id) {
let bd;
while (id && !block.size(bd = this.blocks[id]))
id = block.libs(bd);
return id;
}
/**
* Returns block id or zero.
* The block data can be read from blocks[id].
*/
getBlockId(x, y) {
if (!this._inBounds(x, y))
return 0;
return this.lift(this.table[y << 4 | x]);
}
/**
* Returns the four neighbors of the stone
* in the [L, R, T, B] format.
*/
getNbBlockIds(x, y) {
return [
this.getBlockId(x - 1, y),
this.getBlockId(x + 1, y),
this.getBlockId(x, y - 1),
this.getBlockId(x, y + 1)
];
}
/**
* Adjusts libs of the four neighboring blocks
* of the given color by the given quantity.
*/
adjust(x, y, color, quantity) {
const neighbors = this.getNbBlockIds(x, y);
next: for (let i = 0; i < 4; i++) {
const id = neighbors[i];
const bd = this.blocks[id];
if (bd * color <= 0)
continue;
for (let j = 0; j < i; j++)
if (neighbors[j] == id)
continue next;
this.change(id, bd + quantity * block.lib1);
}
}
/**
* emoves ablock from the board and adjusts
* the number of liberties of affected blocks.
*/
remove(id) {
const bd = this.blocks[id];
const [xmin, xmax, ymin, ymax] = block.dims(bd);
for (let y = ymin; y <= ymax; y++) {
for (let x = xmin; x <= xmax; x++) {
if (this.getBlockId(x, y) == id) {
if (bd > 0)
this.hash_b ^= this.hasht_b[y << 4 | x];
else
this.hash_w ^= this.hasht_w[y << 4 | x];
this.adjust(x, y, -bd, +1);
}
}
}
this.change(id, 0);
}
/**
* Changes the block descriptor and makes
* an appropriate record in the history.
*/
change(id, bd) {
// adding a new block corresponds to a change from
// blocks[blocks.length - 1] -> b
this.history.changed.push(id);
this.history.changed.push(id < this.blocks.length ? this.blocks[id] : 0);
this.blocks[id] = bd;
}
inBounds(x, y) {
if (y === void 0) {
if (!tsumego.stone.hascoords(x))
return false;
[x, y] = tsumego.stone.coords(x);
}
return this._inBounds(x, y);
}
_inBounds(x, y) {
const n = this.size;
return x >= 0 && x < n && y >= 0 && y < n;
}
/**
* Returns the number of captured stones + 1.
* If the move cannot be played, returns 0.
* The move can be undone by undo().
*
* This method only sets table[y * size + x] to
* to an appropriate block id and changes block
* descriptors in the array of blocks. It doesn't
* allocate temporary objects and thus is pretty fast.
*/
play(move) {
if (this._redo_data && this._redo_hist == this.history.added.length) {
const nres = this.redo(move);
if (nres)
return nres;
}
else {
this._redo_data = null;
}
const color = tsumego.stone.color(move);
const x = tsumego.stone.x(move);
const y = tsumego.stone.y(move);
if (!color || !tsumego.stone.hascoords(move) || !this._inBounds(x, y) || this.getBlockId(x, y))
return 0;
tsumego._n_play++;
const size = this.size;
const hash_b = this.hash_b;
const hash_w = this.hash_w;
const n_changed = this.history.changed.length / 2; // id1, bd1, id2, bd2, ...
const ids = this.getNbBlockIds(x, y);
const nbs = [0, 0, 0, 0];
const lib = [0, 0, 0, 0];
for (let i = 0; i < 4; i++) {
nbs[i] = this.blocks[ids[i]];
lib[i] = block.libs(nbs[i]);
}
// remove captured blocks
let result = 0;
fstr: for (let i = 0; i < 4; i++) {
for (let j = 0; j < i; j++)
// check if that block is already removed
if (ids[j] == ids[i])
continue fstr;
if (lib[i] == 1 && color * nbs[i] < 0) {
this.remove(ids[i]);
result += block.size(nbs[i]);
// the removed block may have occupied
// several liberties of the stone
for (let j = 0; j < 4; j++)
if (ids[j] == ids[i])
lib[j] = nbs[j] = 0;
}
}
// if nothing has been captured...
if (result == 0) {
const isll =
/* L */ (nbs[0] * color < 0 || lib[0] == 1 || x == 0) &&