lila/ui/round/src/util.ts

90 lines
2.1 KiB
TypeScript
Raw Normal View History

2017-04-25 08:10:14 -06:00
import { h } from 'snabbdom'
2017-07-09 04:15:42 -06:00
import { Hooks } from 'snabbdom/hooks'
2017-07-09 04:23:43 -06:00
import { Attrs } from 'snabbdom/modules/attributes'
2017-07-08 15:09:41 -06:00
import * as cg from 'chessground/types'
import { Redraw } from './interfaces';
2017-04-25 08:10:14 -06:00
2017-04-25 05:16:04 -06:00
const pieceScores = {
pawn: 1,
knight: 3,
bishop: 3,
rook: 5,
queen: 9,
king: 0
};
2017-07-09 04:23:43 -06:00
export function dataIcon(icon: string): Attrs {
2017-05-23 02:34:28 -06:00
return {
'data-icon': icon
};
}
2017-04-25 08:10:14 -06:00
export function uci2move(uci: string): cg.Key[] | undefined {
2017-04-25 05:16:04 -06:00
if (!uci) return undefined;
2017-04-25 08:10:14 -06:00
if (uci[1] === '@') return [uci.slice(2, 4) as cg.Key];
return [uci.slice(0, 2), uci.slice(2, 4)] as cg.Key[];
2017-07-09 04:23:43 -06:00
}
2017-07-09 04:15:42 -06:00
export function bind(eventName: string, f: (e: Event) => void, redraw: Redraw | undefined = undefined): Hooks {
2017-04-25 08:10:14 -06:00
return {
2017-07-09 04:15:42 -06:00
insert(vnode) {
2017-04-25 08:10:14 -06:00
(vnode.elm as HTMLElement).addEventListener(eventName, e => {
const res = f(e);
2017-04-25 08:10:14 -06:00
if (redraw) redraw();
return res;
2017-04-25 08:10:14 -06:00
});
}
};
}
2017-07-09 04:23:43 -06:00
2017-04-25 05:16:04 -06:00
export function parsePossibleMoves(possibleMoves) {
if (!possibleMoves) return {};
2017-07-08 15:09:41 -06:00
for (let k in possibleMoves) {
2017-04-25 05:16:04 -06:00
if (typeof possibleMoves[k] === 'object') break;
possibleMoves[k] = possibleMoves[k].match(/.{2}/g);
}
return possibleMoves;
2017-07-09 04:23:43 -06:00
}
2017-04-25 05:16:04 -06:00
// {white: {pawn: 3 queen: 1}, black: {bishop: 2}}
2017-07-08 15:09:41 -06:00
export function getMaterialDiff(pieces: cg.Pieces): cg.MaterialDiff {
let counts = {
2017-04-25 05:16:04 -06:00
king: 0,
queen: 0,
rook: 0,
bishop: 0,
knight: 0,
pawn: 0
2017-07-08 15:09:41 -06:00
}, p, role, c, k;
for (k in pieces) {
2017-04-25 05:16:04 -06:00
p = pieces[k];
counts[p.role] += (p.color === 'white' ? 1 : -1);
}
2017-07-08 15:09:41 -06:00
const diff = {
2017-04-25 05:16:04 -06:00
white: {},
black: {}
};
for (role in counts) {
c = counts[role];
if (c > 0) diff.white[role] = c;
else if (c < 0) diff.black[role] = -c;
}
return diff;
2017-07-09 04:23:43 -06:00
}
2017-07-08 15:09:41 -06:00
export function getScore(pieces: cg.Pieces): number {
let score = 0, k;
for (k in pieces) {
2017-04-25 05:16:04 -06:00
score += pieceScores[pieces[k].role] * (pieces[k].color === 'white' ? 1 : -1);
}
return score;
2017-07-09 04:23:43 -06:00
}
2017-04-25 08:10:14 -06:00
export function spinner() {
return h('div.spinner', [
h('svg', { attrs: { viewBox: '0 0 40 40' } }, [
h('circle', {
attrs: { cx: 20, cy: 20, r: 18, fill: 'none' }
})])]);
}