@openbooknetwork/hesap 0.2.3 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/package.json +2 -2
  2. package/src/client.css +254 -1
  3. package/src/families/counters/add-figures.js +85 -0
  4. package/src/families/counters/add-goals.js +82 -0
  5. package/src/families/counters/add-model.js +82 -0
  6. package/src/families/counters/add.js +442 -0
  7. package/src/families/counters/add.mjs +102 -0
  8. package/src/families/counters/bonds.js +5 -5
  9. package/src/families/counters/client.css +126 -1
  10. package/src/families/counters/client.js +10 -12
  11. package/src/families/counters/count-figures.js +23 -3
  12. package/src/families/counters/count-model.js +5 -0
  13. package/src/families/counters/count.js +31 -9
  14. package/src/families/counters/count.mjs +5 -3
  15. package/src/families/counters/counter.js +25 -0
  16. package/src/families/counters/goals.js +1 -9
  17. package/src/families/counters/i18n/en.yaml +142 -30
  18. package/src/families/counters/i18n/tr.yaml +116 -4
  19. package/src/families/counters/index.mjs +11 -6
  20. package/src/families/counters/match-figures.js +60 -0
  21. package/src/families/counters/match-goals.js +63 -0
  22. package/src/families/counters/match-model.js +93 -0
  23. package/src/families/counters/match.js +399 -0
  24. package/src/families/counters/match.mjs +102 -0
  25. package/src/families/counters/order-figures.js +46 -0
  26. package/src/families/counters/order-model.js +69 -0
  27. package/src/families/counters/order.js +199 -0
  28. package/src/families/counters/order.mjs +62 -0
  29. package/src/families/counters/reading.js +66 -0
  30. package/src/families/counters/scenes.js +18 -0
  31. package/src/families/line/client.css +118 -0
  32. package/src/families/line/client.js +12 -0
  33. package/src/families/line/figures.js +143 -0
  34. package/src/families/line/goals.js +168 -0
  35. package/src/families/line/i18n/en.yaml +61 -0
  36. package/src/families/line/i18n/tr.yaml +61 -0
  37. package/src/families/line/index.mjs +227 -0
  38. package/src/families/line/lens.js +49 -0
  39. package/src/families/line/line.js +624 -0
  40. package/src/families/line/model.js +219 -0
  41. package/src/families.mjs +2 -1
  42. package/src/i18n/en.yaml +211 -31
  43. package/src/i18n/tr.yaml +184 -4
  44. package/src/kit/i18n/en.yaml +8 -1
  45. package/src/kit/i18n/tr.yaml +7 -0
  46. package/src/kit/kit.css +9 -0
  47. package/src/kit/panel.js +9 -4
  48. package/src/kit/random.js +9 -0
  49. package/src/kit/written.js +70 -0
  50. package/src/node.mjs +13 -1
@@ -0,0 +1,399 @@
1
+ // The match scene: two rows of objects paired one to one. The reader draws a line between a counter of each row,
2
+ // seats a cup on a saucer, steps a row or stops the music of a game of chairs, and the counters left without a
3
+ // partner take a ring.
4
+ import { ROWS, GOALS_MAX, idOf, roomOf, opening, linesOf, resize, step, lone, won, counts, same, wordsOf, tagKey, measuresOf, wordsLinked, readingOf, verdictOf, differenceOf } from './match-model.js';
5
+ import { writtenLine, words, reading } from '../../kit/written.js';
6
+ import { signTile, verdictMark, isTile, nextSign, signShown, signOf } from './reading.js';
7
+ import { counter, show, put, R, HIT } from './counter.js';
8
+ import { rowsOf, cupsOf, scoreOf, BALL, GAP, CLOSE, WIDE } from './match-figures.js';
9
+ import { MATCH_GOALS } from './match-goals.js';
10
+ import { carry, press } from './move.js';
11
+ import { driver } from './driver.js';
12
+ import { svg as el, svgPoint } from '../../kit/dom.js';
13
+ import { stepper, slider, chip, button, row as line, check } from '../../kit/panel.js';
14
+ import { goalRow } from '../../kit/goal.js';
15
+ import { dice, fresh, another } from '../../kit/random.js';
16
+ import { live } from '../../kit/text.js';
17
+ import { numbers } from '../../kit/format.js';
18
+
19
+ const MAX = 1.7; // A figure grows to at most this scale on a wide stage.
20
+ const PAD = 14; // The figure keeps this far from the stage's edges, in pixels.
21
+ const SAUCER = 15; // The radius a saucer is drawn round.
22
+ const NEAR = 34; // A cup let go this close to a saucer sits on it.
23
+ const rowOf = id => id[0] === 't' ? 'top' : 'bottom', at = id => Number(id.slice(1));
24
+ const NAMES = 26; // The room above and below the rows of a trail page for the names of the rows.
25
+ const tagWide = words => 24 + 8.4 * words.length; // The width of a row's tag round its words.
26
+ const SIGNED = { w: 258, h: 70 }; // The room under the rows for the line of two numbers with a sign.
27
+ const far = (p, q) => Math.hypot(p.x - q.x, p.y - q.y);
28
+
29
+ export default function match({ host, stage, panel, T, lang, moving, motion: fx }) {
30
+ const go = driver(fx);
31
+ const back = el('g'), voids = el('g'), wires = el('g'), rings = el('g'), lower = el('g'), upper = el('g', { class: 'counters-layer' });
32
+ // The tag at the end of each row, in the row's colour.
33
+ const tags = Object.fromEntries(ROWS.map(r => { const pop = el('g', { class: 'a' }, [el('rect', { class: 'counters-rowtag-box', rx: 13 }), el('text', { class: 'counters-rowtag-text' })]); return [r, { pop, g: el('g', { class: `counters-rowtag counters-${r === 'top' ? 'a' : 'b'}`, 'data-ref': `${r}-word`, display: 'none' }, [pop]) }]; }));
34
+ const rubber = el('line', { class: 'counters-rubber', display: 'none' });
35
+ const wordPop = el('g', { class: 'counters-word-pop a' }, [el('rect', { class: 'counters-word-box', rx: 15 }), el('text', { class: 'counters-word-text' })]);
36
+ const word = el('g', { class: 'counters-word', display: 'none' }, [wordPop]);
37
+ // The line under the rows of a page with a sign: the top row's number, the sign, the bottom row's number and the
38
+ // mark that says whether the line is true.
39
+ const tile = signTile(), told = verdictMark(), cards = ROWS.map((r, k) => el('rect', { class: `counters-line-card counters-${k ? 'b' : 'a'}`, x: (k ? 132 : 22) - 23, y: -25, width: 46, height: 50, rx: 8, display: 'none' })), nums = Object.fromEntries(ROWS.map((r, k) => [r, el('text', { class: `counters-line-num counters-${k ? 'b' : 'a'}`, 'data-ref': r, x: k ? 132 : 22 })]));
40
+ const signed = el('g', { display: 'none' }, [...cards, nums.top, el('g', { transform: 'translate(77 0)' }, [tile.el]), nums.bottom, el('g', { transform: 'translate(170 0)' }, [told.el])]);
41
+ press(tile.el, () => { if (!spec || !isTile(spec)) return; s.sign = nextSign(s.sign); if (cs) cs.checked = false; changed(); });
42
+ // The written line of the difference of the rows, which stands where the line of a sign page stands.
43
+ const written = writtenLine();
44
+ const svg = el('svg', { class: 'counters-svg' }, [back, voids, wires, rings, lower, upper, tags.top.g, tags.bottom.g, rubber, word, signed, written.el]);
45
+ stage.appendChild(svg);
46
+ // spec is the page. s holds the counters of each row, the lines the reader drew and how far the Spacing slider
47
+ // stands, from 0 to 1. geo holds the places of the figure, nodes the drawn object of each id, pick the counter a
48
+ // tap chose as the first of a pair, hold the cup the reader carries and ringed the ids that wear a ring.
49
+ let spec = null, s = null, geo = null, area = { w: 0, h: 0 }, nodes = new Map(), pick = null, hold = null, over = null;
50
+ // round is the button of the chairs.
51
+ let chips = [], ringed = new Set(), worded = false, round = null, board = null, goals = [];
52
+ // base is the page as written. On a challenge page spec is base with the rows the goal drew, target is the draw,
53
+ // cs says whether the reader has pressed Check, goal is the challenge's line and solved whether the goal holds.
54
+ let base = null, target = null, cs = null, goal = null, solved = false, steps = [];
55
+
56
+ const int = n => numbers(lang()).int(n);
57
+ const cups = () => spec.look === 'cups', chairs = () => spec.look === 'chairs', scores = () => spec.look === 'scoreboard';
58
+ new ResizeObserver(() => { const r = svg.getBoundingClientRect(); if (spec && (Math.round(r.width) !== area.w || Math.round(r.height) !== area.h)) build(); }).observe(svg);
59
+
60
+ const partner = id => { const k = rowOf(id) === 'top' ? 0 : 1, l = linesOf(spec, s).find(l => l[k] === at(id)); return l ? idOf(ROWS[1 - k], l[1 - k]) : null; };
61
+ const layout = () => scores() ? scoreOf(GOALS_MAX, [T('match-scoreboard-top'), T('match-scoreboard-bottom')]) : cups() ? cupsOf(roomOf(spec, 'top'), roomOf(spec, 'bottom'))
62
+ : rowsOf({ top: roomOf(spec, 'top'), bottom: roomOf(spec, 'bottom'), ...gaps(), tag: tagRoom(), names: spec.trail ? NAMES : 0, line: spec.sign || spec.written ? SIGNED : undefined });
63
+ // The Spacing slider sets the gap of its row up to twice the gap, and a challenge draws one row wide and one close.
64
+ function gaps() {
65
+ if (spec.spread) return { gap: { [spec.spread]: GAP * (1 + s.spread) }, widest: { [spec.spread]: 2 * GAP } };
66
+ if (spec.wide) return { gap: Object.fromEntries(ROWS.map(r => [r, r === spec.wide ? WIDE : CLOSE])) };
67
+ return {};
68
+ }
69
+ // deal sets the rows as the page opens. A challenge draws its rows, and takes its stepper or its sign from its goal.
70
+ function deal() {
71
+ const c = base.challenge;
72
+ spec = base; cs = null; solved = false;
73
+ if (c) { target = another(MATCH_GOALS[c.goal], c, base, dice(fresh()), target); spec = { ...base, ...MATCH_GOALS[c.goal].page(target) }; cs = { checked: false }; }
74
+ s = { ...opening(spec), spread: 0 }; pick = null; worded = false;
75
+ }
76
+ const holds = () => cs ? MATCH_GOALS[base.challenge.goal].holds({ checked: cs.checked, top: s.top, bottom: s.bottom, sign: s.sign }, spec, base.challenge, target) : { done: false };
77
+ const ends = () => solved && MATCH_GOALS[base.challenge.goal].ends;
78
+
79
+ // The tag at a row's end gets the room of its longest words in the page's language, with the greatest number a
80
+ // row can count to.
81
+ function tagRoom() {
82
+ if (cs && MATCH_GOALS[base.challenge.goal].ends) return 6 + tagWide(int(roomOf(spec, 'top')));
83
+ if (spec.word !== true) return 0;
84
+ const n = int(Math.max(roomOf(spec, 'top'), roomOf(spec, 'bottom')));
85
+ return 6 + Math.max(...['same', 'more', 'fewer'].map(w => tagWide(T(`tag-${w}`))), ...(spec.tap ? ['more', 'fewer'].map(w => tagWide(T(`tag-${w}-n`, { n }))) : []));
86
+ }
87
+
88
+ // build draws the figure to fit the stage and puts every object in its place.
89
+ function build() {
90
+ const r = svg.getBoundingClientRect(); area = { w: Math.round(r.width), h: Math.round(r.height) };
91
+ if (!area.w || !area.h) { geo = null; return; } // A phone is showing the text, so the figure is drawn when the stage shows.
92
+ geo = layout();
93
+ const scale = Math.min(MAX, (area.w - 2 * PAD) / geo.w, (area.h - 2 * PAD) / geo.h);
94
+ svg.setAttribute('viewBox', `${geo.w / 2 - area.w / 2 / scale} ${geo.h / 2 - area.h / 2 / scale} ${area.w / scale} ${area.h / scale}`);
95
+ // A trail page names its rows: the top row is the group now, and the bottom row the group before.
96
+ const names = spec.trail ? [['top', 'now', -1], ['bottom', 'before', 1]].map(([r, key, side]) => { const p = geo[r](0), t = el('text', { class: 'counters-row-name', x: p.x - R, y: p.y + side * (R + 17), 'data-ref': r }); t.textContent = T(`row-${key}`); return t; }) : [];
97
+ const drawn = geo.draw(); board = drawn.refs ?? null;
98
+ back.replaceChildren(...drawn.nodes, ...names);
99
+ signed.setAttribute('display', geo.line && spec.sign ? 'inline' : 'none');
100
+ if (geo.line) signed.setAttribute('transform', `translate(${geo.line.x} ${geo.line.y})`);
101
+ if (geo.line && spec.written) written.at(geo.w / 2, geo.line.y); else written.set(null);
102
+ tile.open(isTile(spec), T('sign')); told.show(isTile(spec) && !cs);
103
+ for (const card of cards) card.setAttribute('display', spec.hidden ? 'inline' : 'none');
104
+ for (const n of nodes.values()) n.tween?.pause();
105
+ lower.replaceChildren(); upper.replaceChildren(); voids.replaceChildren(); nodes = new Map(); ringed = new Set();
106
+ for (const r of ROWS) tags[r].pop.lastChild.textContent = '';
107
+ render('jump');
108
+ }
109
+
110
+ // where gives the place of every object on show. A cup with a saucer sits on it.
111
+ function where() {
112
+ const out = new Map();
113
+ for (let i = 0; i < s.bottom; i++) out.set(idOf('bottom', i), geo.bottom(i));
114
+ for (let i = 0; i < s.top; i++) {
115
+ const id = idOf('top', i), to = cups() ? partner(id) : null;
116
+ out.set(id, to ? geo.seat(at(to)) : geo.top(i));
117
+ }
118
+ return out;
119
+ }
120
+
121
+ // render moves every object to its place. After a change the reader made, objects glide, arrive and leave.
122
+ function render(how) {
123
+ if (!geo) return;
124
+ geo = layout(); solved = holds().done;
125
+ const to = where(), anim = how === 'move' && moving();
126
+ for (const [id, n] of nodes) if (!to.has(id)) {
127
+ nodes.delete(id); n.tween?.pause();
128
+ if (anim) go.vanish(n.pop, () => n.g.remove()); else n.g.remove();
129
+ }
130
+ for (const [id, p] of to) {
131
+ let n = nodes.get(id);
132
+ if (!n) {
133
+ n = make(id); nodes.set(id, n); (rowOf(id) === 'top' ? upper : lower).append(n.g); put(n, p);
134
+ if (anim) go.pop(n.pop);
135
+ continue;
136
+ }
137
+ if (n === hold || (n.at.x === p.x && n.at.y === p.y)) continue;
138
+ n.tween?.pause();
139
+ if (anim) n.tween = go.tween(n.at, { x: p.x, y: p.y }, () => show(n)); else put(n, p);
140
+ }
141
+ paint(to, anim); refresh();
142
+ }
143
+
144
+ // make draws a counter, a cup, a saucer, a player or a chair. The reader pairs counters and carries cups. A
145
+ // counter added since a trace page opened carries a plus, and a counter of a tap page has room for its number.
146
+ function make(id) {
147
+ const top = rowOf(id) === 'top';
148
+ if (cups() && !top) return counter('saucer', 'b', SAUCER);
149
+ if (chairs()) return top ? counter('person', 'a', R, at(id)) : counter('chair', 'b');
150
+ if (scores()) return counter('ball', top ? 'a' : 'b', BALL);
151
+ const n = counter(cups() ? 'mug' : 'disc', top ? 'a' : 'b');
152
+ // A counter added since a trace page opened carries a plus in place of the inner ring.
153
+ if (spec.trace && at(id) >= s.base[rowOf(id)]) { n.g.classList.add('counters-added'); n.pop.append(el('path', { class: 'counters-plus', d: 'M -8 0 H 8 M 0 -8 V 8' })); }
154
+ if (spec.tap) {
155
+ n.tagPop = el('g', { class: 'counters-tag-pop' }, [el('rect', { class: 'counters-tag-box', x: -9, y: -9, width: 18, height: 18, rx: 9 }), el('text', { class: 'counters-tag-text' })]);
156
+ n.tag = el('g', { class: 'counters-tag', transform: `translate(${R * 0.8} ${-R * 1.15})`, display: 'none' }, [n.tagPop]);
157
+ n.g.append(n.tag);
158
+ press(n.g, () => numbered(id));
159
+ }
160
+ if (!cups() && spec.pair === 'auto') return n;
161
+ n.g.setAttribute('tabindex', 0); n.g.setAttribute('role', 'button'); n.g.setAttribute('aria-label', T(cups() ? 'cup' : 'kind-disc'));
162
+ n.g.classList.add('counters-moves');
163
+ carry(n.g, cups() ? carried(id, n) : drawn(id, n));
164
+ return n;
165
+ }
166
+
167
+ // A drag from a counter draws a line that follows the finger, and the line stays when it is let go on a counter
168
+ // of the other row that has none. A counter that has a line keeps it until a tap takes it away.
169
+ function drawn(id, n) {
170
+ const aim = q => { const to = aimed(id, q); mark(to); return to; };
171
+ const end = () => { rubber.setAttribute('display', 'none'); mark(null); };
172
+ return {
173
+ point: e => svgPoint(svg, e),
174
+ move(q) {
175
+ if (partner(id)) return;
176
+ const to = aim(q), p = to ? nodes.get(to).at : q;
177
+ for (const [k, v] of Object.entries({ x1: n.at.x, y1: n.at.y, x2: p.x, y2: p.y, display: 'inline' })) rubber.setAttribute(k, v);
178
+ },
179
+ drop(q) { const to = q && !partner(id) ? aim(q) : null; end(); if (to) join(id, to); },
180
+ tap() { end(); tapped(id); },
181
+ };
182
+ }
183
+ // aimed gives the counter of the other row under the point q, when it has no line yet.
184
+ function aimed(id, q) {
185
+ let best = null, d = HIT + 4;
186
+ for (const [to, n] of nodes) if (rowOf(to) !== rowOf(id) && !partner(to) && far(n.at, q) < d) { best = to; d = far(n.at, q); }
187
+ return best;
188
+ }
189
+ // mark shows where a line or a cup would land.
190
+ function mark(id) {
191
+ if (over === id) return;
192
+ nodes.get(over)?.g.classList.remove('counters-over'); nodes.get(id)?.g.classList.add('counters-over'); over = id;
193
+ }
194
+ function join(a, b) {
195
+ const [t, u] = rowOf(a) === 'top' ? [a, b] : [b, a];
196
+ s.lines = [...s.lines.filter(l => l[0] !== at(t) && l[1] !== at(u)), [at(t), at(u)]];
197
+ pick = null; changed();
198
+ }
199
+ const part = id => { s.lines = s.lines.filter(l => l[rowOf(id) === 'top' ? 0 : 1] !== at(id)); pick = null; changed(); };
200
+ // A tap on a paired counter takes its line away. A tap on a counter and then on one of the other row pairs them.
201
+ function tapped(id) {
202
+ if (partner(id)) return part(id);
203
+ if (pick && rowOf(pick) !== rowOf(id)) return join(pick, id);
204
+ pick = pick === id ? null : id; changed();
205
+ }
206
+
207
+ // The reader carries a cup. Let go on an empty saucer it sits there, and anywhere else it goes back to the tray.
208
+ // A tap sends a cup of the tray to the first empty saucer, and a cup on a saucer back to the tray.
209
+ function carried(id, n) {
210
+ let dx = 0, dy = 0;
211
+ const saucer = p => { let best = null, d = NEAR; for (let j = 0; j < s.bottom; j++) { const to = idOf('bottom', j), free = !partner(to) || partner(to) === id; if (free && far(geo.seat(j), p) < d) { best = to; d = far(geo.seat(j), p); } } return best; };
212
+ const free = () => Array.from({ length: s.bottom }, (_, j) => idOf('bottom', j)).find(to => !partner(to));
213
+ return {
214
+ point: e => svgPoint(svg, e), raise: () => upper.append(n.g),
215
+ start(q) { n.tween?.pause(); hold = n; dx = n.at.x - q.x; dy = n.at.y - q.y; },
216
+ move(q) { put(n, { x: q.x + dx, y: q.y + dy }); mark(saucer(n.at)); },
217
+ drop(q) {
218
+ hold = null;
219
+ const to = q ? saucer(n.at) : partner(id);
220
+ mark(null);
221
+ if (to) join(id, to); else part(id);
222
+ },
223
+ tap() { hold = null; const to = partner(id) ? null : free(); if (to) join(id, to); else part(id); },
224
+ };
225
+ }
226
+
227
+ // A tap on a counter left over gives it the next number. A counter that holds its number shakes it once.
228
+ function numbered(id) {
229
+ if (!lone(spec, s)[rowOf(id)].includes(at(id))) return;
230
+ if (s.said.includes(id)) { if (moving()) go.flash(nodes.get(id)?.tagPop); return; }
231
+ s.said = [...s.said, id]; changed();
232
+ }
233
+ // The button of the chairs stops the music, then takes the player left over out with one chair, and starts a new
234
+ // game once one player is left.
235
+ function turn() {
236
+ if (won(spec, s)) s = { ...opening(spec), spread: 0 };
237
+ else if (s.music) s.music = false;
238
+ else s = { ...resize(resize(s, 'top', s.top - 1), 'bottom', s.bottom - 1), music: true };
239
+ changed();
240
+ }
241
+ const turnWords = () => T(won(spec, s) ? 'chairs-again' : s.music ? 'chairs-stop' : 'chairs-next');
242
+
243
+ function changed() { render('move'); }
244
+
245
+ // paint draws the pair lines, rings the counters without a partner and shows the words between the rows.
246
+ function paint(to, anim) {
247
+ wires.replaceChildren(...(cups() ? [] : linesOf(spec, s).map(([t, b]) => {
248
+ const p = to.get(idOf('top', t)), q = to.get(idOf('bottom', b));
249
+ return el('line', { class: 'counters-wire', 'data-ref': 'pairs', x1: p.x, y1: p.y, x2: q.x, y2: q.y });
250
+ })));
251
+ lightPairs();
252
+ const l = lone(spec, s), ids = l.ringed ? ROWS.flatMap(r => l[r].map(i => idOf(r, i))) : [];
253
+ rings.replaceChildren(...ids.map(id => {
254
+ const p = to.get(id), r = cups() ? (rowOf(id) === 'top' ? R + 9 : 1.5 * SAUCER + 6) : chairs() ? R + 8 : R + 3.5;
255
+ const c = el('circle', { class: 'counters-lone a', 'data-ref': 'unpaired', cx: p.x, cy: p.y, r });
256
+ if (anim && !ringed.has(id)) go.pop(c);
257
+ return c;
258
+ }));
259
+ ringed = new Set(ids);
260
+ for (const [id, n] of nodes) n.g.classList.toggle('counters-picked', id === pick);
261
+ if (spec.trace) voids.replaceChildren(...ROWS.flatMap(r => Array.from({ length: Math.max(0, s.base[r] - s[r]) }, (_, k) => {
262
+ const p = geo[r](s[r] + k);
263
+ return el('circle', { class: 'counters-void', 'data-ref': 'taken', cx: p.x, cy: p.y, r: R - 2 });
264
+ })));
265
+ if (spec.tap) for (const [id, n] of nodes) {
266
+ const k = s.said.indexOf(id), words = k < 0 ? '' : int(k + 1), text = n.tagPop.lastChild, open = k < 0 && ids.includes(id);
267
+ for (const [name, v] of [['tabindex', 0], ['role', 'button'], ['aria-label', T('kind-disc')]]) if (open) n.g.setAttribute(name, v); else n.g.removeAttribute(name);
268
+ if (text.textContent === words) continue;
269
+ text.textContent = words; n.tag.setAttribute('display', words ? 'inline' : 'none');
270
+ if (words && anim) go.pop(n.tagPop);
271
+ }
272
+ if (chairs()) {
273
+ const sway = s.music && !won(spec, s) && moving();
274
+ for (const [id, n] of nodes) if (rowOf(id) === 'top') { n.pop.classList.toggle('counters-sway', sway); n.pop.style.animationDelay = `${-0.35 * (at(id) % 3)}s`; }
275
+ if (won(spec, s)) { const p = to.get(idOf('top', 0)), crown = el('path', { class: 'counters-crown a', d: 'M -10 -17 L -10 -28 L -5 -22 L 0 -30 L 5 -22 L 10 -28 L 10 -17 Z' }); rings.append(el('g', { transform: `translate(${p.x} ${p.y})` }, [crown])); if (anim) go.pop(crown); }
276
+ if (round) round.querySelector('span').textContent = turnWords();
277
+ }
278
+ if (spec.sign) {
279
+ // The scoreboard writes its scores and its sign on the board, and the rows write theirs on the line under them.
280
+ const sign = signShown(spec, s), flash = part => { if (anim) go.flash(part); };
281
+ // The cards of a challenge keep the numbers of the rows face down until the goal holds.
282
+ const shown = r => spec.hidden && !solved ? '?' : int(s[r]);
283
+ for (const r of ROWS) { const t = board?.[r] ?? nums[r]; if (t.textContent !== shown(r)) { const first = !t.textContent; t.textContent = shown(r); if (!first) flash(t); } }
284
+ if (board) { if (board.sign.textContent !== sign) { board.sign.textContent = sign; flash(board.sign); } }
285
+ else {
286
+ if (tile.set(sign)) flash(tile.pop);
287
+ if (isTile(spec) && told.set(signOf(s.top, s.bottom) === sign, T(verdictOf(spec, s)))) flash(told.el);
288
+ }
289
+ for (const [k, b] of goals.entries()) b.disabled = s[ROWS[k]] >= GOALS_MAX;
290
+ }
291
+ if (spec.written) {
292
+ // The greater row's number comes first, in its row's colour, and the counters left over are the answer.
293
+ const d = differenceOf(spec, s), cls = r => `counters-${r === 'top' ? 'a' : 'b'}`;
294
+ if (written.set({ ...d.line, refs: { a: d.greater, b: d.less, c: 'unpaired' }, cls: { a: cls(d.greater), b: cls(d.less) } }, int) && anim) go.flash(written.el);
295
+ }
296
+ // A challenge that writes the numbers of its rows once it is reached uses the tags for them.
297
+ const ws = ends() ? Object.fromEntries(ROWS.map(r => [r, null])) : spec.word === true ? wordsOf(spec, s) : null;
298
+ for (const r of ROWS) {
299
+ const t = tags[r], text = t.pop.lastChild;
300
+ t.g.setAttribute('display', ws ? 'inline' : 'none');
301
+ if (!ws) continue;
302
+ // The tag stands after the last counter of its row, or after the last empty place.
303
+ const words = ws[r] ? T(tagKey(ws[r]), { n: int(ws[r].n ?? 0) }) : int(s[r]), w = tagWide(words), n = Math.max(s[r], spec.trace ? s.base[r] : 0), p = geo[r](Math.max(0, n - 1));
304
+ for (const [k, v] of Object.entries({ x: -w / 2, y: -13, width: w, height: 26 })) t.pop.firstChild.setAttribute(k, v);
305
+ t.g.setAttribute('transform', `translate(${p.x + (n ? R : -R) + 12 + w / 2} ${p.y})`);
306
+ if (text.textContent !== words) { const first = !text.textContent; text.textContent = words; if (anim && !first) go.flash(t.pop); }
307
+ }
308
+ const on = spec.word === 'same' && same(spec, s);
309
+ word.setAttribute('display', on ? 'inline' : 'none');
310
+ if (on) {
311
+ const text = T('word-same'), w = 30 + 9.4 * text.length, xs = [...to.values()].map(p => p.x);
312
+ wordPop.lastChild.textContent = text;
313
+ for (const [k, v] of Object.entries({ x: -w / 2, y: -15, width: w, height: 30 })) wordPop.firstChild.setAttribute(k, v);
314
+ word.setAttribute('transform', `translate(${(Math.min(...xs) + Math.max(...xs)) / 2} ${geo.mid})`);
315
+ if (anim && !worded) go.pop(wordPop);
316
+ }
317
+ worded = on;
318
+ }
319
+
320
+ // refresh writes every value that follows the rows, in the readouts and the text: the counts and the words of the
321
+ // tags.
322
+ function refresh() {
323
+ const st = counts(spec, s), ids = measuresOf(spec), ws = wordsLinked(spec).length ? wordsOf(spec, s) : null;
324
+ const said = { reading: () => spec.written ? reading(differenceOf(spec, s).line, int, T) : T(readingOf(spec, s), { a: int(s.top), b: int(s.bottom) }),
325
+ written: () => words(differenceOf(spec, s).line, int), verdict: () => T(verdictOf(spec, s)) }, value = id => said[id]?.() ?? int(st[id]);
326
+ for (const k of chips) if (k.set(value(k.id)) && moving()) go.flash(k.el);
327
+ judge();
328
+ live(host, { value: id => ids.includes(id) ? value(id) : wordsLinked(spec).includes(id) ? T(tagKey(ws[id.split('-')[0]]), { n: int(ws[id.split('-')[0]].n ?? 0) }) : null });
329
+ }
330
+
331
+ // judge writes a challenge's line and whether its goal holds. The counters swell the first time it does.
332
+ function judge() {
333
+ if (!goal) return;
334
+ const name = base.challenge.goal, r = holds();
335
+ goal.say(T(`goal-${name}`));
336
+ for (const st of steps) st.show(r.done);
337
+ if (goal.show(r.done, r.note ? T(`note-${name}-${r.note}`) : undefined) && moving()) go.cheer([...nodes.values()].map(n => n.pop));
338
+ }
339
+
340
+ // The panel holds a stepper for each row that has one, the Spacing slider, the button of the chairs and the
341
+ // readouts.
342
+ function drawPanel() {
343
+ // A challenge keeps the number of its stepper out of sight until the goal holds.
344
+ const ctls = ROWS.filter(r => spec[`${r}Ctl`]).map(r => stepper({ shown: !cs || solved, id: r, label: T(`ctl-${r}`), min: spec[`${r}Ctl`].lo, max: spec[`${r}Ctl`].hi, value: s[r], write: int,
345
+ change: v => { s = step(spec, s, r, v); pick = null; if (cs) cs.checked = false; changed(); } }));
346
+ steps = [...ctls];
347
+ if (spec.spread) ctls.push(slider({ id: 'spread', label: T('ctl-spread'), min: 0, max: 100, value: s.spread * 100, output: false,
348
+ write: v => `×${numbers(lang()).fmt(1 + v / 100)}`, input: v => { s.spread = v / 100; render('jump'); } }));
349
+ round = chairs() ? button({ label: turnWords(), act: 'round', primary: true, press: turn }) : null;
350
+ if (round) ctls.push(round);
351
+ // The scoreboard has a button for a goal of each team and one for a new match.
352
+ goals = scores() ? ROWS.map(r => button({ label: T(`score-${r}`), act: `score-${r}`, press: () => { if (s[r] < GOALS_MAX) { s = resize(s, r, s[r] + 1); changed(); } } })) : [];
353
+ if (scores()) ctls.push(...goals, button({ label: T('new-match'), act: 'new-match', press: () => { s = { ...opening(spec), spread: 0 }; changed(); } }));
354
+ // The line of words takes a line of the panel to itself, so the panel keeps its height as the words change.
355
+ chips = spec.readout.map(id => chip({ id, label: T(`match-${spec.trail ? 'trail' : spec.look}-${id}`) ?? T(`match-${id}`) ?? T(id), cls: ['reading', 'written'].includes(id) ? 'counters-chip-wide' : '' }));
356
+ for (const k of chips) if (!['reading', 'written'].includes(k.id)) k.width(k.id === 'verdict' ? 5 : 2);
357
+ // A challenge has its line with Another one and a hint, and a Check button beside its controls.
358
+ goal = null;
359
+ if (cs) {
360
+ const name = base.challenge.goal;
361
+ goal = goalRow({ T, motion: moving() ? fx : null, hint: on => on ? T(`hint-${name}`) : null, another: () => { deal(); drawPanel(); build(); if (!geo) refresh(); } });
362
+ ctls.push(check({ T, press: () => { if (!cs.checked) { cs.checked = true; render('move'); if (!geo) refresh(); } } }));
363
+ }
364
+ panel.replaceChildren(...[goal?.el, ctls.length ? line('ctls', ctls) : null, chips.length ? line('out', chips) : null].filter(Boolean));
365
+ }
366
+
367
+ // pairsLit says the reader points at the link pairs, which lights each pair line and the counters at its ends.
368
+ let pairsLit = false;
369
+ function lightPairs() {
370
+ const paired = new Set(linesOf(spec, s).flatMap(([t, b]) => [idOf('top', t), idOf('bottom', b)]));
371
+ for (const [id, n] of nodes) n.g.classList.toggle('counters-paired-lit', pairsLit && paired.has(id));
372
+ for (const w of wires.children) w.classList.toggle('counters-hot', pairsLit);
373
+ }
374
+ function point(id, on) {
375
+ if (!spec) return;
376
+ written.light(id, on, ['written', 'reading']);
377
+ if (id === 'pairs') { pairsLit = on; lightPairs(); }
378
+ for (const part of svg.querySelectorAll(`[data-ref="${id}"]`)) part.classList.toggle('counters-hot', on);
379
+ for (const part of panel.querySelectorAll('[data-ref]')) part.classList.toggle('hot', on && part.dataset.ref === id);
380
+ }
381
+ function stop() { for (const n of nodes.values()) n.tween?.pause(); hold = null; over = null; rubber.setAttribute('display', 'none'); }
382
+
383
+ return {
384
+ show(page) {
385
+ stop(); pairsLit = false; base = page; target = null; deal();
386
+ drawPanel(); build();
387
+ if (!geo) refresh();
388
+ },
389
+ hide() {
390
+ stop(); spec = null; base = null; cs = null; goal = null; geo = null; nodes = new Map();
391
+ for (const g of [back, voids, wires, rings, lower, upper]) g.replaceChildren();
392
+ for (const g of [word, tags.top.g, tags.bottom.g, signed]) g.setAttribute('display', 'none');
393
+ for (const r of ROWS) nums[r].textContent = '';
394
+ written.set(null);
395
+ },
396
+ point,
397
+ lang() { if (!spec) return; const was = goal; drawPanel(); goal?.keep(was); build(); if (!geo) refresh(); },
398
+ };
399
+ }
@@ -0,0 +1,102 @@
1
+ // The Node half of the match scene: two rows of objects paired one to one. It checks a page's fields and says what
2
+ // each link shows when the page opens.
3
+ import { schema } from '@openbooknetwork/kitap';
4
+ import { MATCH_LOOKS, ROWS, ROW_MAX, SPREAD_MAX, PLAYERS, GOALS_MAX, roomOf, opening, counts, wordsOf, tagKey, measuresOf, wordsLinked, readingOf, verdictOf, differenceOf } from './match-model.js';
5
+ import { words, reading } from '../../kit/written.js';
6
+ import { SIGN_FIELD } from './reading.js';
7
+ import { MATCH_GOALS, matchStart } from './match-goals.js';
8
+ import { numbers } from '../../kit/format.js';
9
+ import { list, value, string, challenge, drawn } from '../../node.mjs';
10
+
11
+ const { z, check } = schema;
12
+ const Int = z.number().int();
13
+ const Range = z.tuple([Int, Int]);
14
+ const Stepper = z.object({ stepper: Range, start: Int.optional() }).strict();
15
+ const Row = z.union([Int, Stepper]);
16
+ const Fields = z.object({
17
+ look: z.enum(MATCH_LOOKS).default('rows'), // Two rows of counters, cups above saucers, players above chairs, or two scores.
18
+ top: Row.optional(), // The objects of the top row as the page opens, as a number or on a stepper.
19
+ bottom: Row.optional(), // The objects of the bottom row.
20
+ pair: z.enum(['drag', 'auto']).optional(), // The reader draws each pair, or the scene pairs the rows in order.
21
+ spread: z.enum(ROWS).optional(), // A Spacing slider sets the gap between the counters of this row.
22
+ // same shows the words "The same" between rows whose every counter has a partner. true gives each row a tag at
23
+ // its end that reads more, fewer or the same.
24
+ word: z.union([z.literal('same'), z.literal(true)]).optional(),
25
+ tap: z.literal('tag').optional(), // A tap on a counter left over gives it the next number.
26
+ trace: z.boolean().default(false), // A counter added since the page opened carries a plus, and one taken leaves a place.
27
+ trail: z.boolean().default(false), // The bottom row holds the top row as it was one step ago.
28
+ // A line of the two numbers with a sign between them: a tile that opens on this sign, or a sign that follows.
29
+ sign: z.enum(SIGN_FIELD).optional(),
30
+ // The written line of the difference of the rows under them, such as 11 − 7 = 4.
31
+ written: z.literal('difference').optional(),
32
+ // A challenge names a goal of match-goals.js and the ranges it draws its rows from.
33
+ challenge: z.object({ goal: z.string(), top: Range.optional(), bottom: Range.optional(), rows: Range.optional(), apart: Range.optional() }).strict().optional(),
34
+ readout: z.array(z.string()).default([]),
35
+ }).strict();
36
+
37
+ function read(fields, { at }, ctx) {
38
+ const pg = check(Fields, fields, at), fail = words => ctx.fail(at, words);
39
+ const top = value(pg.top), bottom = value(pg.bottom);
40
+ const spec = { ...pg, scene: 'match', pair: pg.pair ?? 'drag', top: top.n, topCtl: top.ctl, bottom: bottom.n, bottomCtl: bottom.ctl };
41
+ if (pg.challenge) { readChallenge(pg, spec, at, ctx); return { data: spec, has: () => false, offers: 'nothing, a challenge page draws its numbers as it opens' }; }
42
+ for (const [v, name] of [[top, 'top'], [bottom, 'bottom']]) {
43
+ if (v.n == null) { fail(`${name} is missing, write the objects of the ${name} row, such as 5, or { stepper: [1, 10], start: 5 }`); continue; }
44
+ const lo = v.ctl?.lo ?? v.n, hi = v.ctl?.hi ?? v.n;
45
+ if (lo > hi || v.n < lo || v.n > hi) fail(`${name} has the range [${lo}, ${hi}] and starts at ${v.n}, write [low, high] and a start between them`);
46
+ else if (lo < 0 || hi > ROW_MAX) fail(`${name} reaches ${v.ctl ? `[${lo}, ${hi}]` : v.n}, a row holds from 0 to ${ROW_MAX} objects`);
47
+ }
48
+ if (pg.sign && !['rows', 'scoreboard'].includes(pg.look)) fail('sign stands between the numbers of two rows or two scores, write look: rows or look: scoreboard');
49
+ if (pg.written && (pg.look !== 'rows' || pg.sign || pg.trail)) fail('written writes the difference of two rows of counters, write look: rows and leave sign and trail out');
50
+ if (pg.look === 'scoreboard') {
51
+ for (const f of ['pair', 'word', 'tap', 'trace', 'trail', 'spread']) if (pg[f]) fail(`${f} belongs to look: rows, the buttons add the goals of the scoreboard`);
52
+ if (top.ctl || bottom.ctl || [top.n, bottom.n].some(n => n > GOALS_MAX)) fail(`top and bottom are the scores of the home team and the away team, write each as a number from 0 to ${GOALS_MAX}`);
53
+ if (pg.sign !== 'follow') fail('the scoreboard keeps the sign between its scores, write sign: follow');
54
+ }
55
+ if (pg.look === 'cups' && pg.pair) fail('pair belongs to look: rows, a drag seats a cup on a saucer in the cups look');
56
+ if (pg.look === 'chairs') {
57
+ for (const f of ['pair', 'word', 'tap', 'trace', 'trail', 'spread']) if (pg[f]) fail(`${f} belongs to look: rows, the buttons run the rounds of the chairs`);
58
+ if (top.ctl || bottom.ctl || top.n < PLAYERS[0] || top.n > PLAYERS[1] || bottom.n !== top.n - 1) fail(`top and bottom are the players and the chairs, write top as a number from ${PLAYERS[0]} to ${PLAYERS[1]} and bottom as one less`);
59
+ }
60
+ if (pg.spread) {
61
+ if (pg.look !== 'rows' || spec.pair !== 'auto') fail('spread moves the counters of a row under lines the scene draws, write look: rows and pair: auto');
62
+ if (roomOf(spec, pg.spread) > SPREAD_MAX) fail(`spread doubles the length of the ${pg.spread} row, which reaches ${roomOf(spec, pg.spread)} counters, give it ${SPREAD_MAX} at most`);
63
+ }
64
+ if (!['chairs', 'scoreboard'].includes(pg.look)) {
65
+ if (pg.word === true && (pg.look !== 'rows' || spec.pair !== 'auto')) fail('word: true names the row with counters left over by lines the scene draws, write look: rows and pair: auto');
66
+ if (pg.trail) {
67
+ if (pg.look !== 'rows' || spec.pair !== 'auto' || !top.ctl || bottom.ctl || Math.abs(top.n - bottom.n) !== 1) fail('trail keeps the top row of one step ago in the bottom row, write look: rows, pair: auto, top on a stepper and bottom as a number one less or one more than its start');
68
+ for (const f of ['trace', 'spread']) if (pg[f]) fail(`${f} and trail both follow the steps of a row, keep one`);
69
+ }
70
+ for (const f of ['tap', 'trace']) if (pg[f] && (pg.look !== 'rows' || spec.pair !== 'auto')) fail(`${f} works on counters left over by lines the scene draws, write look: rows and pair: auto`);
71
+ }
72
+ const ids = measuresOf(spec), linked = [...ids, ...wordsLinked(spec)];
73
+ for (const id of pg.readout) if (!ids.includes(id)) fail(`readout names "${id}", this page reads out ${list(ids)}`);
74
+ return { data: spec, has: id => linked.includes(id), offers: `one of ${list(linked)}` };
75
+ }
76
+
77
+ // A challenge page names its goal and the ranges the goal draws from, and leaves every other field out. The goal
78
+ // draws the rows, and gives the page its stepper or its sign tile.
79
+ function readChallenge(pg, spec, at, ctx) {
80
+ const c = pg.challenge, goal = challenge(c, MATCH_GOALS, { scene: 'match', at, ctx });
81
+ if (!goal) return;
82
+ for (const [f, v] of Object.entries(pg)) if (!['challenge', 'look'].includes(f) && v !== undefined && v !== false && !(f === 'readout' && !v.length)) ctx.fail(at, `${f} is set by challenge.goal ${c.goal}, leave it out`);
83
+ if (pg.look !== 'rows') ctx.fail(at, `look is set by challenge.goal ${c.goal}, which draws two rows of counters, leave it out`);
84
+ const problem = goal.problem(c);
85
+ if (problem) return ctx.fail(at, `challenge.${problem}`);
86
+ drawn(goal, c, spec, { at, ctx, starts: matchStart });
87
+ }
88
+
89
+ // A link shows a count or the word of a row's tag as the page opens.
90
+ function start(spec, lang, id) {
91
+ const s = opening(spec);
92
+ if (wordsLinked(spec).includes(id)) { const w = wordsOf(spec, s)[id.split('-')[0]]; return string(lang, `counters_${tagKey(w)}`, { n: numbers(lang).int(w.n) }); }
93
+ if (!measuresOf(spec).includes(id)) return null;
94
+ const int = numbers(lang).int;
95
+ if (id === 'written') return words(differenceOf(spec, s).line, int);
96
+ if (id === 'reading' && spec.written) return reading(differenceOf(spec, s).line, int, (key, vars) => string(lang, `hesap_${key}`, vars));
97
+ if (id === 'reading') return string(lang, `counters_${readingOf(spec, s)}`, { a: int(s.top), b: int(s.bottom) });
98
+ if (id === 'verdict') return string(lang, `counters_${verdictOf(spec, s)}`);
99
+ return int(counts(spec, s)[id]);
100
+ }
101
+
102
+ export default { read, start };
@@ -0,0 +1,46 @@
1
+ // The parts of an order figure: a counter drawn small, a block of rows of ten with its number, and a number card.
2
+ import { svg as el } from '../../kit/dom.js';
3
+ import { txt } from './figures.js';
4
+ import { tenPlace } from './count-figures.js';
5
+
6
+ // dot is a counter of radius r that takes no touch, in the family's colour a or b.
7
+ export const dot = (colour, r, p) => el('g', { class: `counters-counter counters-${colour}`, transform: `translate(${p.x} ${p.y})` },
8
+ [el('circle', { class: 'counters-body', r }), el('circle', { class: 'counters-ring', r: r * 0.6 })]);
9
+
10
+ const GAP = 22, FIVE = 4, DOT = 9, PAD = 8; // A block's counters, the gap after the fifth and the edge round them.
11
+ const NUM = 46; // The room above a block for its number.
12
+ export const BLOCK = { w: 10 * GAP + FIVE + 2 * PAD, h: NUM + 10 * GAP + 2 * PAD, num: NUM / 2 - 2 };
13
+
14
+ // block draws a number's room for 100 counters in rows of ten at x, 0, with the number above it. set lays n
15
+ // counters out, with the full rows solid and the last row lighter. frame surrounds the full rows, the last row or
16
+ // the whole block, cover hides the rows.
17
+ export function block(row, colour, x) {
18
+ const num = txt(`counters-block-num counters-${colour}`, x + BLOCK.w / 2, BLOCK.num), top = NUM + PAD;
19
+ num.setAttribute('data-ref', row);
20
+ const dots = Array.from({ length: 100 }, (_, i) => { const p = tenPlace(i, GAP, FIVE); return dot(colour, DOT, { x: x + PAD + p.x, y: top + p.y }); });
21
+ const held = el('g', {}, dots), edge = el('rect', { class: 'counters-decide', rx: 8, display: 'none' });
22
+ const lid = el('g', { class: 'counters-cover', display: 'none' }, [el('rect', { x, y: NUM, width: BLOCK.w, height: BLOCK.h - NUM, rx: 10 }), txt('counters-cover-mark', x + BLOCK.w / 2, NUM + (BLOCK.h - NUM) / 2, '?')]);
23
+ return {
24
+ nodes: [el('rect', { class: 'counters-tray', x, y: NUM, width: BLOCK.w, height: BLOCK.h - NUM, rx: 10 }), held, edge, lid, num],
25
+ set(n, words) {
26
+ num.textContent = words;
27
+ dots.forEach((d, i) => { d.setAttribute('display', i < n ? 'inline' : 'none'); d.classList.toggle('counters-light', i >= Math.floor(n / 10) * 10); });
28
+ },
29
+ // kind is rows, last or all, or null for no frame. An empty run of rows keeps a thin frame at its place.
30
+ frame(kind, n) {
31
+ edge.setAttribute('display', kind ? 'inline' : 'none');
32
+ if (!kind) return;
33
+ const full = Math.floor(n / 10), from = kind === 'last' ? full : 0, rows = kind === 'last' ? 1 : kind === 'rows' ? full : 10, m = kind === 'all' ? PAD : 3;
34
+ for (const [k, v] of Object.entries({ x: x + PAD - m, y: top + from * GAP - m, width: BLOCK.w - 2 * PAD + 2 * m, height: rows * GAP + 2 * m })) edge.setAttribute(k, v);
35
+ },
36
+ cover(on) { lid.setAttribute('display', on ? 'inline' : 'none'); held.setAttribute('display', on ? 'none' : 'inline'); },
37
+ };
38
+ }
39
+
40
+ export const CARD = { w: 84, h: 108 };
41
+ // card draws a number card round 0, 0: the number, and under it the number in small rows of ten.
42
+ export function card(n, words) {
43
+ const g = 5.6, left = -5 * g - 0.8, top = -CARD.h / 2 + 40, full = Math.floor(n / 10) * 10;
44
+ const minis = Array.from({ length: n }, (_, i) => { const p = tenPlace(i, g, 1.6); return el('circle', { class: `counters-mini${i >= full ? ' counters-light' : ''}`, cx: left + p.x, cy: top + p.y, r: 2.2 }); });
45
+ return [el('rect', { class: 'counters-card-box', x: -CARD.w / 2, y: -CARD.h / 2, width: CARD.w, height: CARD.h, rx: 9 }), txt('counters-card-num', 0, -CARD.h / 2 + 21, words), ...minis];
46
+ }
@@ -0,0 +1,69 @@
1
+ // What an order page holds and what it reads out: two numbers on one count or as two blocks of rows of ten, or three
2
+ // number cards. The build and the browser both use this file, so a page's text and its live values agree.
3
+ import { relation, isTile, signShown, readingKey, verdictKey } from './reading.js';
4
+
5
+ // A page draws its two numbers as markers on one count of 100, or as two blocks of rows of ten.
6
+ export const SHOWS = ['count', 'blocks'];
7
+ export const ROWS = ['top', 'bottom'];
8
+ export const TOP = 100; // The greatest number a page shows.
9
+ export const CARDS = 3; // The cards a page puts in order.
10
+
11
+ // A page puts cards in order when it names their numbers or asks for a draw.
12
+ export const isCards = spec => !!(spec.cards || spec.draw);
13
+
14
+ // opening gives the numbers as the page opens. cards holds the numbers of the cards on show, which New numbers
15
+ // draws again. A page that asks for a draw and names no cards opens without them, and the browser draws them. sign is the sign on the tile of a page that has one. open says whether the rows of the blocks are in sight, and place
16
+ // holds the place of each card, counted from 0, or null for a card in the tray.
17
+ export const opening = spec => ({ top: spec.top, bottom: spec.bottom, open: !spec.cover, sign: isTile(spec) ? spec.sign : null,
18
+ cards: spec.cards ?? [], place: isCards(spec) ? Array(CARDS).fill(null) : [] });
19
+
20
+ // A number in rows of ten has full rows and a last row: 3 and 4 for 34, 4 and 0 for 40.
21
+ export const tens = n => ({ rows: Math.floor(n / 10), last: n % 10 });
22
+
23
+ // counts gives every number a page can show.
24
+ export function counts(spec, s) {
25
+ const t = tens(s.top), b = tens(s.bottom);
26
+ return { top: s.top, bottom: s.bottom, 'top-rows': t.rows, 'top-last': t.last, 'bottom-rows': b.rows, 'bottom-last': b.last };
27
+ }
28
+
29
+ // decides names the rows that decide which number is greater: the full rows when their numbers differ, the last
30
+ // rows when the full rows are the same, and all of both blocks when the numbers are the same.
31
+ export const decides = s => s.top === s.bottom ? 'all' : tens(s.top).rows !== tens(s.bottom).rows ? 'rows' : 'last';
32
+
33
+ // between says how the cards of two neighbouring places stand, or null while one of the places is empty.
34
+ export function between(spec, s, k) {
35
+ const [a, b] = [k, k + 1].map(p => s.cards[s.place.indexOf(p)]);
36
+ return a === undefined || b === undefined ? null : relation(a, b);
37
+ }
38
+ // The cards stand in order when each is less than the one after it.
39
+ export const ordered = (spec, s) => Array.from({ length: CARDS - 1 }, (_, k) => between(spec, s, k)).every(r => r === 'less');
40
+
41
+ // The measures a page can read out and link in its text. A covered page keeps what gives the answer away to itself.
42
+ export function measuresOf(spec) {
43
+ if (isCards(spec)) return [];
44
+ if (spec.cover) return ['top', 'bottom'];
45
+ return ['top', 'bottom', ...(spec.reading || spec.sign ? ['reading'] : []), ...(isTile(spec) ? ['verdict'] : []), ...(spec.show === 'blocks' ? ['top-rows', 'top-last', 'bottom-rows', 'bottom-last'] : [])];
46
+ }
47
+ // The strings of the line of words and of the mark, as the page stands.
48
+ export const readingOf = (spec, s) => readingKey(s.top, s.bottom, signShown(spec, s));
49
+ export const verdictOf = (spec, s) => verdictKey(s.top, s.bottom, signShown(spec, s));
50
+
51
+ // On one count the first number's pin stands above its counter and the second's below. With the first number one
52
+ // row under the second, both pins meet between the two counters, so pinShift moves the first left and the second
53
+ // right there. It gives each pin's shift as -1, 0 or 1.
54
+ export const pinShift = s => s.top - s.bottom === 10 ? { top: -1, bottom: 1 } : { top: 0, bottom: 0 };
55
+
56
+ // drawCards draws three numbers from 10 to 99 for the cards. Two have the same full rows and different last rows,
57
+ // so the last row decides between them, and the third has other full rows. In one draw of three the third is one
58
+ // of the two with its digits swapped, as 63 beside 36, where that gives such a number. The cards come in an order
59
+ // that is not yet the right one, and differ from the cards in last.
60
+ export function drawCards(dice, last = []) {
61
+ const digits = Array.from({ length: 10 }, (_, i) => i), swap = n => (n % 10) * 10 + Math.floor(n / 10);
62
+ for (;;) {
63
+ const rows = dice.int(1, 9), pair = dice.some(digits, 2).map(d => rows * 10 + d);
64
+ const turned = dice.shuffle(pair).map(swap).filter(n => n >= 10 && tens(n).rows !== rows);
65
+ const third = dice.int(1, 3) === 1 && turned.length ? turned[0] : dice.pick(digits.slice(1).filter(r => r !== rows)) * 10 + dice.pick(digits);
66
+ const cards = dice.shuffle([...pair, third]), sorted = a => [...a].sort((x, y) => x - y).join();
67
+ if (cards.join() !== sorted(cards) && sorted(cards) !== sorted(last)) return cards;
68
+ }
69
+ }