forked from lichess-org/lila
-
Notifications
You must be signed in to change notification settings - Fork 0
/
moveCtrl.ts
587 lines (525 loc) · 19.6 KB
/
moveCtrl.ts
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
import { Api as CgApi } from 'chessground/api';
import * as xhr from 'common/xhr';
import * as prop from 'common/storage';
import * as cs from 'chess';
import { src as src, dest as dest } from 'chess';
import { PromotionCtrl, promote } from 'chess/promotion';
import { RootCtrl, VoiceMove, VoiceCtrl, Entry, Match } from '../main';
import { coloredArrows, numberedArrows, brushes } from './arrows';
import { settingNodes } from './view';
import {
type SparseMap,
type Transform,
spread,
spreadMap,
getSpread,
remove,
pushMap,
movesTo,
findTransforms,
} from '../util';
// Based on the original implementation by Sam 'Spammy' Ezeh. see the README.md in ui/voice/@build
export default (window as any).LichessVoiceMove = function (
root: RootCtrl,
ui: VoiceCtrl,
initialFen: string
): VoiceMove {
const DEBUG = { emptyMatches: false, buildMoves: false, buildSquares: false, collapse: true };
const cg: CgApi = root.chessground;
const byVal: SparseMap<Entry> = new Map(); // map values to lexicon entries
const byTok: Map<string, Entry> = new Map(); // map token chars to lexicon entries
const byWord: Map<string, Entry> = new Map(); // map input words to lexicon entries
const moves: SparseMap<Uci> = new Map(); // map valid xvals to all full legal movesmmmmmmmmmh
const squares: SparseMap<Uci> = new Map(); // map of xvals to selectable or reachable square(s)
const sans: SparseMap<string> = new Map(); // map xvals to ucis of valid sans
const confirm: Map<string, (v: boolean) => void> = new Map(); // boolean confirmation callbacks
const clarityPref = prop.storedIntProp('voice.clarity', 0);
const colorsPref = prop.storedBooleanPropWithEffect('voice.useColors', true, _ => initTimerRec());
const timerPref = prop.storedIntPropWithEffect('voice.timer', 3, _ => initTimerRec());
let entries: Entry[] = [];
let partials = { commands: [], colors: [], numbers: [] };
let board: cs.Board;
let ucis: Uci[]; // every legal move in uci
let choices: Map<string, Uci> | undefined; // map choice (blue, red, 1, 2, etc) to action
let choiceTimeout: number | undefined; // timeout for ambiguity choices
const commands: { [_: string]: () => void } = {
no: () => (ui.showHelp() ? ui.showHelp(false) : clearMoveProgress()),
help: () => ui.showHelp(true),
'mic-off': () => lichess.mic.stop(),
flip: () => root.flipNow(),
rematch: () => root.rematch?.(true),
draw: () => root.offerDraw?.(true, false),
resign: () => root.resign?.(true, false),
next: () => root.next?.(),
takeback: () => root.takebackYes?.(),
upvote: () => root.vote?.(true),
downvote: () => root.vote?.(false),
solve: () => root.solve?.(),
};
for (const [color, brush] of brushes) cg.state.drawable.brushes[`v-${color}`] = brush;
update(initialFen);
initGrammar();
return {
ui,
initGrammar,
prefNodes,
allPhrases,
update,
promotionHook,
opponentRequest,
};
function prefNodes() {
return settingNodes(colorsPref, clarityPref, timerPref, root.redraw);
}
async function initGrammar(): Promise<void> {
const g = await xhr.jsonSimple(lichess.assetUrl(`compiled/grammar/move-${ui.lang()}.json`));
byWord.clear();
byTok.clear();
byVal.clear();
for (const e of g.entries) {
byWord.set(e.in, e);
byTok.set(e.tok, e);
if (e.val === undefined) e.val = e.tok;
pushMap(byVal, e.val, e);
}
entries = g.entries;
partials = g.partials;
initDefaultRec();
initTimerRec();
}
function initDefaultRec() {
const excludeTag = root?.vote ? 'round' : 'puzzle'; // reduce unneeded vocabulary
const words = tagWords().filter(x => byWord.get(x)?.tags?.includes(excludeTag) !== true);
lichess.mic.initRecognizer(words, { listener: listen });
}
function initTimerRec() {
if (timer() === 0) return;
const words = [...partials.commands, ...(colorsPref() ? partials.colors : partials.numbers)].map(w => valWord(w));
lichess.mic.initRecognizer(words, { recId: 'timer', partial: true, listener: listenTimer });
}
function maxArrows() {
return Math.min(8, colorsPref() ? partials.colors.length : partials.numbers.length);
}
function update(fen: string) {
board = cs.readFen(fen);
cg.setShapes([]);
if (!cg.state.movable.dests) return;
ucis = cs.destsToUcis(cg.state.movable.dests);
buildMoves();
buildSquares();
}
function listen(text: string, msgType: Voice.MsgType) {
if (msgType === 'stop' && !ui.pushTalk()) clearMoveProgress();
else if (msgType === 'full') {
try {
if (DEBUG.collapse) console.groupCollapsed(`listen '${text}'`);
else console.info(`listen '${text}'`);
if (handleCommand(text) || handleAmbiguity(text) || handleMove(text)) {
confirm.forEach((cb, _) => cb(false));
confirm.clear();
}
} finally {
if (DEBUG.collapse) console.groupEnd();
}
}
root.redraw();
}
function listenTimer(word: string) {
if (!choices || !choiceTimeout) return;
const val = wordVal(word);
const move = choices.get(val);
if (val !== 'no' && !move) return;
clearMoveProgress();
if (move) submit(move);
lichess.mic.setRecognizer('default');
cg.redrawAll();
}
function makeArrows() {
if (!choices) return;
const arrowTime = choiceTimeout ? timer() : undefined;
cg.setShapes(
colorsPref()
? coloredArrows([...choices], arrowTime)
: numberedArrows([...choices], arrowTime, cg.state.orientation === 'white')
);
}
function handleCommand(msgText: string): boolean {
const c = matchOneTags(msgText, ['command', 'choice'])?.[0];
if (!c) return false;
for (const [action, callback] of confirm) {
if (c === 'yes' || c === 'no' || c === action) {
confirm.delete(action);
callback(c !== 'no');
return true;
}
}
if (!(c in commands)) return false;
commands[c]();
return true;
}
function handleAmbiguity(phrase: string): boolean {
if (!choices || phrase.includes(' ')) return false;
const chosen = matchOne(
phrase,
[...choices].map(([w, uci]) => [wordVal(w), [uci]])
);
if (!chosen) {
clearMoveProgress();
console.info('handleAmbiguity', `no match for '${phrase}' among`, choices);
return false;
}
console.info('handleAmbiguity', `matched '${phrase}' to '${chosen[0]}' at cost=${chosen[1]} among`, choices);
submit(chosen[0]);
return true;
}
function handleMove(phrase: string): boolean {
if (selection() && chooseMoves(matchMany(phrase, spreadMap(squares)))) return true;
return chooseMoves(matchMany(phrase, [...spreadMap(moves), ...spreadMap(squares)]));
}
// see the README.md in ui/voice/@build to decrypt these variable names.
function matchMany(phrase: string, xvalsOut: [string, string[]][], partite = false): [string, Match][] {
const htoks = wordsToks(phrase);
const xtoksOut: SparseMap<string> = new Map(); // temp map for token expansion
for (const [xvals, outs] of xvalsOut) {
for (const xtoks of valsToks(xvals)) {
for (const out of outs) pushMap(xtoksOut, xtoks, out);
}
}
const matches = new Map<string, Match>();
for (const [xtoks, outs] of spreadMap(xtoksOut)) {
const cost = costToMatch(htoks, xtoks, partite);
const sanUcis = new Set(getSpread(sans, toksVals(xtoks)));
if (cost > 1) continue;
for (const out of outs) {
if (!matches.has(out) || matches.get(out)!.cost > cost) {
matches.set(out, { isSan: sanUcis.has(out), cost });
}
}
}
const sorted = [...matches].sort(([, lhs], [, rhs]) => lhs.cost - rhs.cost);
if (sorted.length > 0 || DEBUG.emptyMatches)
console.info('matchMany', `from: `, xtoksOut, '\nto: ', new Map(sorted));
return sorted;
}
function matchOne(heard: string, xvalsOut: [string, string[]][]): [string, Match] | undefined {
return matchMany(heard, xvalsOut, true)[0];
}
function matchOneTags(heard: string, tags: string[], vals: string[] = []): [string, Match] | undefined {
return matchOne(heard, [...vals.map(v => [v, [v]]), ...byTags(tags).map(e => [e.val!, [e.val!]])] as [
string,
string[]
][]);
}
function costToMatch(h: string, x: string, partite: boolean) {
if (h === x) return 0;
const xforms = findTransforms(h, x)
.map(t => t.reduce((acc, t) => acc + transformCost(t, partite), 0))
.sort((lhs, rhs) => lhs - rhs);
return xforms?.[0] ?? Infinity;
}
function transformCost(transform: Transform, partite: boolean) {
if (transform.from === transform.to) return 0;
const from = byTok.get(transform.from);
const sub = from?.subs?.find(x => x.to === transform.to);
if (partite) {
// mappings within a tag partition are not allowed when partite is true
const to = byTok.get(transform.to);
// should be optimized, maybe consolidate tags when parsing the lexicon
if (from?.tags?.every(x => to?.tags?.includes(x)) && from.tags.length === to!.tags.length) return Infinity;
}
return sub?.cost ?? Infinity;
}
function chooseMoves(m: [string, Match][]) {
if (m.length === 0) return false;
if (m.length === 1 && m[0][0].length === 2) {
console.info('chooseMoves', `select '${m[0][0]}'`);
submit(m[0][0]);
return true;
}
if (timer()) return ambiguate(m);
if (
(m.length === 1 && m[0][1].cost < 0.4) ||
(m.length > 1 && m[1][1].cost - m[0][1].cost > [0.7, 0.5, 0.3][clarityPref()])
) {
console.info('chooseMoves', `chose '${m[0][0]}' cost=${m[0][1].cost}`);
submit(m[0][0]);
return true;
}
return ambiguate(m);
}
function ambiguate(options: [string, Match][]) {
if (options.length === 0) return false;
// dedup by uci squares & keep first to preserve cost order
options = options
.filter(
([uci, _], keepIfFirst) => options.findIndex(first => first[0].slice(0, 4) === uci.slice(0, 4)) === keepIfFirst
)
.slice(0, maxArrows());
// if multiple choices with identical cost head the list, prefer a single SAN move
const sameLowCost = options.filter(([_, m]) => m.cost === options[0][1].cost);
const sanMoves = sameLowCost.filter(([_, m]) => m.isSan);
if (sanMoves.length === 1 && sameLowCost.length > 1) {
// move san uci to front and make it cheaper
const sanIndex = sameLowCost.findIndex(([uci, _]) => uci === sanMoves[0][0]);
[options[0], options[sanIndex]] = [options[sanIndex], options[0]];
options[0][1].cost -= 0.01;
}
if (timer()) {
const clarityThreshold = [1.0, 0.5, 0.001][clarityPref()];
const lowestCost = options[0][1].cost;
// trim choices to clarity window
options = options.filter(([, m]) => m.cost - lowestCost <= clarityThreshold);
}
choices = new Map<string, Uci>();
const preferred = options.length === 1 || options[0][1].cost < options[1][1].cost;
if (preferred) choices.set('yes', options[0][0]);
if (colorsPref()) {
const colorNames = [...brushes.keys()];
options.forEach(([uci], i) => choices!.set(colorNames[i], uci));
} else options.forEach(([uci], i) => choices!.set(`${i + 1}`, uci));
console.info('ambiguate', choices);
choiceTimeout = 0;
if (preferred && timer()) {
choiceTimeout = setTimeout(() => {
submit(options[0][0]);
choiceTimeout = undefined;
lichess.mic.setRecognizer('default');
}, timer() * 1000 + 100);
lichess.mic.setRecognizer('timer');
}
makeArrows();
cg.redrawAll();
return true;
}
function opponentRequest(request: string, callback?: (granted: boolean) => void) {
if (callback) confirm.set(request, callback);
else confirm.delete(request);
}
function submit(uci: Uci) {
clearMoveProgress();
if (uci.length < 3) {
const dests = ucis.filter(x => x.startsWith(uci));
if (dests.length <= maxArrows()) return ambiguate(dests.map(uci => [uci, { cost: 0 }]));
if (uci !== selection()) selection(src(uci));
cg.redrawAll();
return true;
}
const role = cs.promo(uci) as cs.Role;
cg.cancelMove();
if (role) {
promote(cg, dest(uci), role);
root.sendMove(src(uci), dest(uci), role, { premove: false });
} else {
cg.selectSquare(src(uci), true);
cg.selectSquare(dest(uci), false);
}
return true;
}
function promotionHook() {
return (ctrl: PromotionCtrl, roles: cs.Role[] | false) =>
roles
? lichess.mic.addListener(
(text: string) => {
const val = matchOneTags(text, ['role'], ['no'])?.[0];
lichess.mic.stopPropagation();
if (val && roles.includes(cs.charRole(val))) ctrl.finish(cs.charRole(val));
else if (val === 'no') ctrl.cancel();
},
{ listenerId: 'promotion' }
)
: lichess.mic.removeListener('promotion');
}
// given each uci, build every possible move phrase for it, and keep clues
function buildMoves() {
const addToks = (xtoks: string, sanUci?: Uci) => {
const xvals = xtoks.split('').join(',');
xvalset.add(xvals);
if (sanUci) pushMap(sans, xvals, sanUci);
};
moves.clear();
sans.clear();
const xvalset: Set<string> = new Set(); // allowable exact phrases for uci
for (const uci of ucis) {
const usrc = src(uci),
udest = dest(uci),
nsrc = cs.square(usrc),
ndest = cs.square(udest),
dp = board.pieces[ndest],
srole = board.pieces[nsrc].toUpperCase();
if (srole == 'K') {
if (isOurs(dp)) {
pushMap(moves, 'castle', uci);
moves.set(ndest < nsrc ? 'O-O-O' : 'O-O', new Set([uci]));
} else if (Math.abs(nsrc & 7) - Math.abs(ndest & 7) > 1) continue; // require the rook square explicitly
}
xvalset.clear();
xvalset.add(uci);
if (dp && !isOurs(dp)) {
const drole = dp.toUpperCase(); // takes
addToks(`${srole}${drole}`);
addToks(`${srole}x${drole}`);
pushMap(moves, `${srole},x`, uci); // keep out of xvalset to avoid conflicts with promotion
addToks(`x${drole}`);
addToks(`${uci[0]}x`);
addToks(`${uci[0]}x${drole}`);
addToks(`x`);
}
if (srole === 'P') {
addToks(udest, uci); // includes en passant
if (uci[0] === uci[2]) {
addToks(`P${udest}`);
} else if (dp) {
addToks(`${usrc}x${udest}`);
addToks(`Px${udest}`);
addToks(`${uci[0]}x${udest}`, uci);
}
if (uci[3] === '1' || uci[3] === '8') {
for (const moveVals of xvalset) {
for (const role of 'QRBN') {
for (const xvals of [`${moveVals},=,${role}`, `${moveVals},${role}`]) {
pushMap(moves, xvals, `${uci}${role}`);
}
}
}
}
} else {
const others: number[] = movesTo(ndest, srole, board);
let rank = '',
file = '';
for (const other of others) {
if (other === nsrc || board.pieces[other] !== board.pieces[nsrc]) continue;
if (nsrc >> 3 === other >> 3) file = uci[0];
if ((nsrc & 7) === (other & 7)) rank = uci[1];
else file = uci[0];
}
for (const piece of [`${srole}${file}${rank}`, `${srole}`]) {
if (dp) addToks(`${piece}x${udest}`, uci);
addToks(`${piece}${udest}`, uci);
}
}
for (const xvals of xvalset) pushMap(moves, xvals, uci);
}
if (DEBUG.buildMoves) console.info('buildMoves', moves);
}
function buildSquares() {
squares.clear();
for (const uci of ucis) {
const sel = selection();
if (sel && !uci.startsWith(sel)) continue;
const usrc = src(uci),
udest = dest(uci),
nsrc = cs.square(usrc),
ndest = cs.square(udest),
dp = board.pieces[ndest],
srole = board.pieces[nsrc].toUpperCase() as 'P' | 'N' | 'B' | 'R' | 'Q' | 'K';
pushMap(squares, `${usrc[0]},${usrc[1]}`, usrc);
pushMap(squares, `${udest[0]},${udest[1]}`, uci);
//if (srole !== 'P') {
pushMap(squares, srole, uci);
pushMap(squares, srole, usrc);
//}
if (dp && !isOurs(dp)) pushMap(squares, dp.toUpperCase(), uci);
}
// deconflict role partials for move & select
for (const [xouts, set] of squares) {
if (!'PNBRQK'.includes(xouts)) continue;
const moves = spread(set).filter(x => x.length > 2);
if (moves.length > maxArrows()) moves.forEach(x => remove(squares, xouts, x));
else if (moves.length > 0) [...set].filter(x => x.length === 2).forEach(x => remove(squares, xouts, x));
}
if (DEBUG.buildSquares) console.info('buildSquares', squares);
}
function isOurs(p: string | undefined) {
return p === '' || p === undefined
? undefined
: cg.state.turnColor === 'white'
? p.toUpperCase() === p
: p.toLowerCase() === p;
}
function clearMoveProgress() {
const mustRedraw = moveInProgress();
clearTimeout(choiceTimeout);
choiceTimeout = undefined;
choices = undefined;
cg.setShapes([]);
selection(false);
if (mustRedraw) cg.redrawAll();
}
function selection(sq?: Key | false) {
if (sq !== undefined) {
cg.selectSquare(sq || null);
buildSquares();
}
return cg.state.selected;
}
function timer(): number {
return [0, 1.5, 2, 2.5, 3, 5][timerPref()];
}
function moveInProgress() {
return selection !== undefined || choices !== undefined;
}
function tokWord(tok: string) {
return byTok.get(tok)?.in;
}
function toksVals(toks: string) {
return [...toks].map(tok => byTok.get(tok)?.val).join(',');
}
function tagWords(tags?: string[], intersect = false) {
return byTags(tags, intersect).map(e => e.in);
}
function byTags(tags?: string[], intersect = false): Entry[] {
return tags === undefined
? entries
: intersect
? entries.filter(e => e.tags.every(tag => tags.includes(tag)))
: entries.filter(e => e.tags.some(tag => tags.includes(tag)));
}
function wordTok(word: string) {
return byWord.get(word)?.tok ?? '';
}
function wordVal(word: string) {
return byWord.get(word)?.val ?? word;
}
function wordsToks(phrase: string) {
return phrase
.split(' ')
.map(word => wordTok(word))
.join('');
}
function valToks(val: string) {
return getSpread(byVal, val).map(e => e.tok);
}
function valsToks(vals: string): string[] {
const fork = (toks: string[], val: string[]): string[] => {
if (val.length === 0) return toks;
const nextToks: string[] = [];
for (const nextTok of valToks(val[0])) {
for (const tok of toks) nextToks.push(tok + nextTok);
}
return fork(nextToks, val.slice(1));
};
return fork([''], vals.split(','));
}
function valsWords(vals: string): string[] {
return valsToks(vals).map(toks => [...toks].map(tok => tokWord(tok)).join(' '));
}
function valWord(val: string, tag?: string) {
// if no tag, returns only the first matching input word for val, there may be others
const v = byVal.has(val) ? byVal.get(val) : byTok.get(val);
if (v instanceof Set) {
return tag ? [...v].find(e => e.tags.includes(tag))?.in : v.values().next().value.in;
}
return v ? v.in : val;
}
function allPhrases() {
const res: [string, string][] = [];
for (const [xval, uci] of [...moves, ...squares]) {
const toVal = typeof uci === 'string' ? uci : '[...]';
res.push(...(valsWords(xval).map(p => [p, toVal]) as [string, string][]));
}
for (const e of byTags(['command', 'choice'])) {
res.push(...(valsWords(e.val!).map(p => [p, e.val!]) as [string, string][]));
}
return [...new Map(res)]; // vals expansion can create duplicates
}
};