@johnmorrisdotca/sugoroku 1.0.2 → 1.1.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 (67) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +78 -68
  3. package/dist/board.d.ts +216 -12
  4. package/dist/board.js +205 -13
  5. package/dist/colours.d.ts +80 -8
  6. package/dist/colours.js +57 -7
  7. package/dist/computer.d.ts +139 -9
  8. package/dist/computer.js +118 -11
  9. package/dist/dice.d.ts +53 -4
  10. package/dist/dice.js +42 -3
  11. package/dist/draw-entry.d.ts +3 -3
  12. package/dist/draw-entry.js +2 -2
  13. package/dist/draw.d.ts +43 -3
  14. package/dist/draw.js +63 -13
  15. package/dist/element-define.d.ts +1 -1
  16. package/dist/element-define.js +4 -13
  17. package/dist/element.d.ts +116 -5
  18. package/dist/element.js +378 -102
  19. package/dist/elementFrame.d.ts +21 -0
  20. package/dist/elementFrame.js +110 -0
  21. package/dist/evaluate.d.ts +76 -4
  22. package/dist/evaluate.js +70 -5
  23. package/dist/game.d.ts +408 -23
  24. package/dist/game.js +344 -20
  25. package/dist/geometry.d.ts +50 -3
  26. package/dist/geometry.js +64 -28
  27. package/dist/index.d.ts +12 -11
  28. package/dist/index.js +10 -9
  29. package/dist/match.d.ts +66 -4
  30. package/dist/match.js +69 -6
  31. package/dist/mount.d.ts +77 -6
  32. package/dist/mount.js +105 -357
  33. package/dist/mountView.d.ts +58 -0
  34. package/dist/mountView.js +459 -0
  35. package/dist/moves.d.ts +48 -1
  36. package/dist/moves.js +35 -1
  37. package/dist/notation.d.ts +92 -4
  38. package/dist/notation.js +88 -5
  39. package/dist/play-entry.d.ts +4 -4
  40. package/dist/play-entry.js +1 -1
  41. package/dist/playStyle.d.ts +6 -0
  42. package/dist/playStyle.js +6 -0
  43. package/dist/plays.d.ts +108 -3
  44. package/dist/plays.js +96 -3
  45. package/dist/positionElement.d.ts +107 -0
  46. package/dist/positionElement.js +303 -0
  47. package/dist/positionId.d.ts +29 -1
  48. package/dist/positionId.js +33 -2
  49. package/dist/random.d.ts +33 -3
  50. package/dist/random.js +22 -2
  51. package/dist/record.d.ts +151 -8
  52. package/dist/record.js +121 -36
  53. package/dist/rules.d.ts +130 -10
  54. package/dist/rules.js +133 -14
  55. package/dist/side.d.ts +38 -3
  56. package/dist/side.js +30 -3
  57. package/dist/sound.d.ts +61 -3
  58. package/dist/sound.js +27 -2
  59. package/dist/strings.d.ts +42 -2
  60. package/dist/strings.js +37 -3
  61. package/dist/style.d.ts +6 -0
  62. package/dist/style.js +6 -0
  63. package/dist/variants.d.ts +113 -8
  64. package/dist/variants.js +81 -7
  65. package/dist/version.d.ts +9 -2
  66. package/dist/version.js +9 -2
  67. package/package.json +29 -22
package/dist/mount.js CHANGED
@@ -1,19 +1,28 @@
1
- import { BAR, boardPoint } from "./board.js";
2
1
  import { computerAction, sideToAct } from "./computer.js";
3
2
  import { openingFrom, randomDice, rollFrom, seededDice } from "./dice.js";
4
- import { drawSugoroku } from "./draw.js";
5
- import { boardSize, CHECKER } from "./geometry.js";
6
3
  import { beaverDouble, canBeaver, canDouble, concede, dropDouble, endTurn, legalMoves, offerDouble, playMove, rollDice, rollOpening, takeDouble, turnIsPlayed, undoMove, } from "./game.js";
7
4
  import { finishGame, newMatch, startGame } from "./match.js";
5
+ import { attachSugorokuView } from "./mountView.js";
8
6
  import { formatMove, formatPlay } from "./notation.js";
9
- import { diceToPlay } from "./plays.js";
10
7
  import { SUGOROKU_PLAY_STYLE } from "./playStyle.js";
11
8
  import { GameRecorder } from "./record.js";
12
9
  import { presetByKey, settingsFor } from "./rules.js";
13
- import { otherSide, sideIndex } from "./side.js";
10
+ import { otherSide } from "./side.js";
14
11
  import { createSounds, packagedSounds } from "./sound.js";
15
12
  import { sugorokuLanguageOf, sugorokuSay } from "./strings.js";
16
- /** Put the style in the page once: in the document's head, or in the shadow root the host is in. */
13
+ /** Put the style in the page once: in the document's head, or in the shadow root the host is in.
14
+ *
15
+ * @param host - The DOM element receiving the native board or scoped styles.
16
+ * @returns Nothing; the native scoped board styles are installed for the host.
17
+ * @example
18
+ * ```ts no-run
19
+ * import { ensureSugorokuPlayStyle } from "@johnmorrisdotca/sugoroku/play";
20
+ *
21
+ * const host = document.createElement("div");
22
+ * ensureSugorokuPlayStyle(host);
23
+ * console.log(host.tagName);
24
+ * ```
25
+ */
17
26
  export function ensureSugorokuPlayStyle(host) {
18
27
  const root = host.getRootNode();
19
28
  const target = typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot ? root : host.ownerDocument.head;
@@ -31,7 +40,17 @@ function create(document, tag, className, text) {
31
40
  element.textContent = text;
32
41
  return element;
33
42
  }
34
- /** Mount a board into `host`. */
43
+ /** Mount a board into `host`.
44
+ * @param host - The HTMLElement that owns the native interface.
45
+ * @param options - Native settings and callbacks for this mounted interface.
46
+ * @returns The native mounted handle, including controls and destroy() cleanup.
47
+ * @example
48
+ * ```ts
49
+ * import { mountSugoroku } from "@johnmorrisdotca/sugoroku/play";
50
+ * const show = (host: HTMLElement, options: Parameters<typeof mountSugoroku>[1]) => mountSugoroku(host, options);
51
+ * console.log(typeof show); // function
52
+ * ```
53
+ */
35
54
  export function mountSugoroku(host, options = {}) {
36
55
  ensureSugorokuPlayStyle(host);
37
56
  const document = host.ownerDocument;
@@ -51,7 +70,16 @@ export function mountSugoroku(host, options = {}) {
51
70
  let recorder = new GameRecorder(settings, seed);
52
71
  recorder.startGame();
53
72
  // What may change while it is mounted.
54
- let look = { board: options.board, checkers: options.checkers, colours: options.colours, theme: options.theme, home: options.home, view: options.view, numbers: options.numbers, orientation: options.orientation };
73
+ let look = {
74
+ board: options.board,
75
+ checkers: options.checkers,
76
+ colours: options.colours,
77
+ theme: options.theme,
78
+ home: options.home,
79
+ view: options.view,
80
+ numbers: options.numbers,
81
+ orientation: options.orientation,
82
+ };
55
83
  let computer = { white: options.computer?.white ?? null, black: options.computer?.black ?? null };
56
84
  let language = options.language;
57
85
  let names = { ...options.names };
@@ -59,7 +87,7 @@ export function mountSugoroku(host, options = {}) {
59
87
  const hostDice = options.dice === "host";
60
88
  const reducedMotion = view.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
61
89
  const delay = options.computerDelay ?? (reducedMotion ? 0 : 450);
62
- const soundsFor = (setting) => (setting === undefined || setting === false ? null : createSounds(setting === true ? packagedSounds() : setting));
90
+ const soundsFor = (setting) => setting === undefined || setting === false ? null : createSounds(setting === true ? packagedSounds() : setting);
63
91
  let sounds = soundsFor(options.sound);
64
92
  // The page's own parts.
65
93
  host.classList.add("sugoroku-play");
@@ -80,14 +108,11 @@ export function mountSugoroku(host, options = {}) {
80
108
  controls.append(slotA, slotB, slotC);
81
109
  controls.hidden = options.controls === false;
82
110
  host.replaceChildren(score, boardBox, status, controls);
83
- let selected = null;
84
111
  let timer = null;
85
112
  let queue = [];
86
113
  let gone = false;
87
- let portrait = false;
88
114
  let waitingForDice = false;
89
115
  let lastOpening = null;
90
- let message = null;
91
116
  const lang = () => language ?? sugorokuLanguageOf(host);
92
117
  const say = (key, values = {}) => sugorokuSay(lang(), key, values);
93
118
  const isComputer = (side) => computer[side] !== null;
@@ -102,190 +127,20 @@ export function mountSugoroku(host, options = {}) {
102
127
  return say("you");
103
128
  return say(side);
104
129
  };
105
- const eventDetail = (side, extra = {}) => ({ side, game, match, ...extra });
130
+ const eventDetail = (side, extra = {}) => ({
131
+ side,
132
+ game,
133
+ match,
134
+ ...extra,
135
+ });
106
136
  const emit = (name, detail, callback) => {
107
- host.dispatchEvent(new view.CustomEvent(name, { detail, bubbles: true }));
137
+ host.dispatchEvent(new view.CustomEvent(name, { detail: JSON.parse(JSON.stringify(detail)), bubbles: true, composed: true }));
108
138
  callback?.(detail);
109
139
  };
110
140
  const spec = () => game.settings.variant;
111
- const hasCube = () => settings.rules.cube && settings.rules.points !== 1;
112
- /** Whose home board is at the bottom. */
113
- const viewSide = () => {
114
- if (look.view !== undefined && look.view !== "auto")
115
- return look.view;
116
- if (isComputer("white") && human("black"))
117
- return "black";
118
- return "white";
119
- };
120
- // Drawing.
121
- const diceShown = () => {
122
- if (game.phase === "opening") {
123
- return lastOpening === null ? null : { side: "white", values: [lastOpening[0], lastOpening[1]], spent: [false, false] };
124
- }
125
- if (game.dice === null || game.turn === null)
126
- return null;
127
- const values = diceToPlay(spec(), game.dice);
128
- const unused = [...game.need];
129
- const planLeft = [...game.plan];
130
- const spent = values.map((value) => {
131
- const inPlan = planLeft.indexOf(value);
132
- if (inPlan === -1)
133
- return true;
134
- planLeft.splice(inPlan, 1);
135
- const open = unused.indexOf(value);
136
- if (open === -1)
137
- return true;
138
- unused.splice(open, 1);
139
- return false;
140
- });
141
- return { side: game.turn, values, spent };
142
- };
143
- const legalNow = () => (game.phase === "playing" && game.turn !== null && human(game.turn) ? legalMoves(game) : []);
144
- const draw = () => {
145
- const moves = legalNow();
146
- const mover = game.turn;
147
- const sources = [...new Set(moves.map((move) => move.from))];
148
- const targets = selected === null ? [] : [...new Set(moves.filter((move) => move.from === selected).map((move) => move.to))];
149
- return drawSugoroku(game.position, {
150
- variant: spec(),
151
- view: viewSide(),
152
- home: look.home,
153
- orientation: portrait ? "portrait" : "landscape",
154
- numbers: look.numbers,
155
- board: look.board,
156
- checkers: look.checkers,
157
- colours: look.colours,
158
- theme: look.theme,
159
- dice: diceShown(),
160
- cube: hasCube() ? { value: game.cube.value, owner: game.cube.owner } : null,
161
- highlight: mover === null ? null : { side: mover, from: selected, targets, movable: sources },
162
- label: say("board", { variant: say(`variant_${spec().key}`) }),
163
- });
164
- };
165
- // The words.
166
- const pointsText = (count) => say(count === 1 ? "point" : "points", { n: count });
167
- const diceText = (dice) => (dice === null ? "" : diceToPlay(spec(), dice).join(" "));
168
- const statusText = () => {
169
- if (message !== null)
170
- return message;
171
- const side = game.turn;
172
- if (game.phase === "opening")
173
- return waitingForDice ? say("waitingDice") : lastOpening !== null && lastOpening[0] === lastOpening[1] ? say("openingTie", { die: lastOpening[0] }) : say("opening");
174
- if (game.phase === "over") {
175
- const result = game.result;
176
- let line;
177
- if (result.winner === null)
178
- line = say("drawn");
179
- else if (result.how === "drop")
180
- line = say("wonDrop", { side: nameOf(result.winner), points: pointsText(result.points) });
181
- else if (result.how === "concede")
182
- line = say("wonConcede", { side: nameOf(result.winner), points: pointsText(result.points) });
183
- else
184
- line = say("wonBy", { side: nameOf(result.winner), kind: say(result.kind === "single" ? "singleGame" : result.kind), points: pointsText(result.points) });
185
- if (match.over)
186
- line += ` ${match.winner === null ? say("matchDrawn") : say("matchWon", { side: nameOf(match.winner), a: match.score[sideIndex(match.winner)], b: match.score[sideIndex(otherSide(match.winner))] })}`;
187
- return line;
188
- }
189
- if (side === null)
190
- return "";
191
- if (game.phase === "double-offered" || game.phase === "beaver-offered") {
192
- const offerer = game.offeredBy;
193
- const value = game.phase === "double-offered" ? game.cube.value * 2 : game.cube.value * 4;
194
- const lose = pointsText(game.phase === "double-offered" ? game.cube.value : game.cube.value * 2);
195
- if (human(otherSide(offerer)))
196
- return say(game.phase === "double-offered" ? "answerDouble" : "answerBeaver", { side: nameOf(offerer), value, points: lose });
197
- return say("thinking", { side: nameOf(otherSide(offerer)) });
198
- }
199
- if (game.phase === "before-roll") {
200
- if (isComputer(side))
201
- return say("thinking", { side: nameOf(side) });
202
- return isComputer(otherSide(side)) ? say("toRollYou") : say("toRoll", { side: nameOf(side) });
203
- }
204
- if (isComputer(side) && game.moves.length === 0 && game.need.length > 0)
205
- return say("thinking", { side: nameOf(side) });
206
- if (game.plan.length === 0)
207
- return say(human(side) && isComputer(otherSide(side)) ? "noMoveYou" : "noMove", { side: nameOf(side) });
208
- if (turnIsPlayed(game))
209
- return human(side) ? say("played") : say("toPlay", { side: nameOf(side), dice: diceText(game.dice) });
210
- return human(side) && isComputer(otherSide(side)) ? say("toPlayYou", { dice: diceText(game.dice) }) : say("toPlay", { side: nameOf(side), dice: diceText(game.dice) });
211
- };
212
- const scoreText = () => {
213
- const { rules } = settings;
214
- const parts = [say("score", { white: nameOf("white"), a: match.score[0], black: nameOf("black"), b: match.score[1] }), rules.points === 0 ? say("money") : say("matchTo", { points: rules.points })];
215
- if (game.crawford && game.phase !== "over")
216
- parts.push(say("crawford"));
217
- else if (hasCube())
218
- parts.push(game.cube.owner === null ? say("cubeMiddle") : say("cubeHeld", { value: game.cube.value, side: nameOf(game.cube.owner) }));
219
- return parts.join(" · ");
220
- };
221
- const slots = () => {
222
- const off = { text: "", enabled: false, run: () => undefined };
223
- const side = game.turn;
224
- const turnOfHuman = side !== null && human(side);
225
- if (game.phase === "over") {
226
- return [match.over ? { text: say("newMatch"), enabled: true, run: () => api.newMatch(), primary: true } : { text: say("nextGame"), enabled: true, run: () => api.nextGame(), primary: true }, match.over ? off : { text: say("newMatch"), enabled: true, run: () => api.newMatch() }, off];
227
- }
228
- if (game.phase === "opening") {
229
- const nobody = isComputer("white") && isComputer("black");
230
- return [{ text: say("rollOpening"), enabled: !nobody && !waitingForDice, run: () => api.roll(), primary: true, attention: !nobody }, off, off];
231
- }
232
- if (game.phase === "double-offered" || game.phase === "beaver-offered") {
233
- const answerer = otherSide(game.offeredBy);
234
- const mine = human(answerer);
235
- return [
236
- { text: say("take"), enabled: mine, run: () => api.take(), primary: true, attention: mine },
237
- { text: say("drop"), enabled: mine, run: () => api.drop() },
238
- { text: say("beaver"), enabled: mine && canBeaver(game), run: () => api.beaver() },
239
- ];
240
- }
241
- if (game.phase === "before-roll") {
242
- return [
243
- { text: say("roll"), enabled: turnOfHuman && !waitingForDice, run: () => api.roll(), primary: true, attention: turnOfHuman },
244
- { text: say("double"), enabled: turnOfHuman && canDouble(game), run: () => api.double() },
245
- { text: say("undo"), enabled: false, run: () => undefined },
246
- ];
247
- }
248
- const played = turnIsPlayed(game);
249
- return [
250
- { text: say("done"), enabled: turnOfHuman && played, run: () => api.done(), primary: true, attention: turnOfHuman && played },
251
- { text: say("double"), enabled: false, run: () => undefined },
252
- { text: say("undo"), enabled: turnOfHuman && game.moves.length > 0, run: () => api.undo() },
253
- ];
254
- };
255
- let handlers = [() => undefined, () => undefined, () => undefined];
256
- const render = () => {
257
- if (gone)
258
- return;
259
- const width = host.clientWidth || 600;
260
- portrait = look.orientation === "portrait" || (look.orientation !== "landscape" && width < 560);
261
- const size = boardSize({ cube: hasCube(), orientation: portrait ? "portrait" : "landscape" });
262
- boardBox.style.aspectRatio = `${size.width} / ${size.height}`;
263
- boardBox.innerHTML = draw();
264
- host.dataset.phase = game.phase;
265
- host.dataset.turn = game.turn ?? "";
266
- host.dataset.over = String(game.phase === "over");
267
- host.dataset.orientation = portrait ? "portrait" : "landscape";
268
- host.dataset.selected = selected === null ? "" : String(selected);
269
- host.dataset.cube = String(game.cube.value);
270
- host.dataset.need = game.need.join("");
271
- host.dataset.ready = "true";
272
- score.textContent = scoreText();
273
- status.textContent = statusText();
274
- const [a, b, c] = slots();
275
- const buttons = [slotA, slotB, slotC];
276
- [a, b, c].forEach((slot, index) => {
277
- const button = buttons[index];
278
- button.textContent = slot.text;
279
- button.disabled = !slot.enabled;
280
- button.dataset.primary = String(slot.primary === true);
281
- button.dataset.attention = String(slot.attention === true);
282
- button.style.visibility = slot.text === "" ? "hidden" : "visible";
283
- });
284
- handlers = [a.run, b.run, c.run];
285
- };
286
- slotA.addEventListener("click", () => handlers[0]());
287
- slotB.addEventListener("click", () => handlers[1]());
288
- slotC.addEventListener("click", () => handlers[2]());
141
+ let render = () => undefined;
142
+ let resetPointer = () => undefined;
143
+ let disconnectView = () => undefined;
289
144
  const play = (name) => sounds?.play(name);
290
145
  // The game moving on.
291
146
  const startComputer = () => {
@@ -314,11 +169,14 @@ export function mountSugoroku(host, options = {}) {
314
169
  };
315
170
  const setGame = (next) => {
316
171
  game = next;
317
- selected = null;
318
- message = null;
172
+ resetPointer();
319
173
  finishIfOver();
320
174
  render();
321
- if (options.autoEnd === true && game.phase === "playing" && turnIsPlayed(game) && game.turn !== null && human(game.turn)) {
175
+ if (options.autoEnd === true &&
176
+ game.phase === "playing" &&
177
+ turnIsPlayed(game) &&
178
+ game.turn !== null &&
179
+ human(game.turn)) {
322
180
  timer = setTimeout(endNow, delay === 0 ? 0 : 250);
323
181
  return;
324
182
  }
@@ -374,7 +232,9 @@ export function mountSugoroku(host, options = {}) {
374
232
  if (game.phase !== "playing" || game.turn === null)
375
233
  return false;
376
234
  const side = game.turn;
377
- const move = legalMoves(game).filter((one) => one.from === step.from && one.to === step.to).sort((a, b) => a.die - b.die)[0];
235
+ const move = legalMoves(game)
236
+ .filter((one) => one.from === step.from && one.to === step.to)
237
+ .sort((a, b) => a.die - b.die)[0];
378
238
  if (move === undefined)
379
239
  return false;
380
240
  const next = playMove(game, move);
@@ -396,8 +256,20 @@ export function mountSugoroku(host, options = {}) {
396
256
  setGame(next);
397
257
  };
398
258
  const cubeAction = (action, side) => {
399
- const next = action === "double" ? offerDouble(game) : action === "take" ? takeDouble(game) : action === "drop" ? dropDouble(game) : beaverDouble(game);
400
- (action === "double" ? recorder.double : action === "take" ? recorder.take : action === "drop" ? recorder.drop : recorder.beaver).call(recorder, side);
259
+ const next = action === "double"
260
+ ? offerDouble(game)
261
+ : action === "take"
262
+ ? takeDouble(game)
263
+ : action === "drop"
264
+ ? dropDouble(game)
265
+ : beaverDouble(game);
266
+ (action === "double"
267
+ ? recorder.double
268
+ : action === "take"
269
+ ? recorder.take
270
+ : action === "drop"
271
+ ? recorder.drop
272
+ : recorder.beaver).call(recorder, side);
401
273
  play("cube");
402
274
  emit("sugoroku-cube", eventDetail(side, { action, game: next }), options.onCube);
403
275
  setGame(next);
@@ -446,161 +318,6 @@ export function mountSugoroku(host, options = {}) {
446
318
  break;
447
319
  }
448
320
  };
449
- // Touch and mouse.
450
- const whereIs = (target) => {
451
- const mover = game.turn;
452
- if (mover === null || target === null)
453
- return null;
454
- const bar = target.closest("[data-bar]");
455
- if (bar !== null)
456
- return bar.dataset.bar === mover ? BAR : null;
457
- const tray = target.closest("[data-tray]");
458
- if (tray !== null)
459
- return tray.dataset.tray === mover ? 0 : null;
460
- const point = target.closest("[data-board]");
461
- if (point === null || point.dataset.board === undefined)
462
- return null;
463
- return boardPoint(spec(), mover, Number(point.dataset.board));
464
- };
465
- const press = (own) => {
466
- const moves = legalNow();
467
- if (own === null) {
468
- selected = null;
469
- }
470
- else if (selected !== null && moves.some((move) => move.from === selected && move.to === own)) {
471
- makeMove({ from: selected, to: own });
472
- return;
473
- }
474
- else if (moves.some((move) => move.from === own)) {
475
- selected = selected === own ? null : own;
476
- }
477
- else {
478
- selected = null;
479
- }
480
- render();
481
- };
482
- let drag = null;
483
- const underPointer = (x, y) => {
484
- const root = host.getRootNode();
485
- return root.elementFromPoint?.(x, y) ?? null;
486
- };
487
- const sampleColour = (side) => {
488
- const svg = boardBox.querySelector("svg");
489
- const face = svg?.querySelector(`.sg-checker[data-side="${side}"] .sg-face`);
490
- const style = face === null || face === undefined ? null : view.getComputedStyle(face);
491
- return { fill: style?.fill ?? "#fff", edge: style?.stroke ?? "#000" };
492
- };
493
- const onDown = (event) => {
494
- if (event.button !== 0 && event.pointerType === "mouse")
495
- return;
496
- if (game.phase !== "playing" || game.turn === null || !human(game.turn))
497
- return;
498
- const own = whereIs(event.target);
499
- if (own === null)
500
- return;
501
- const moves = legalNow();
502
- if (dragAllowed && moves.some((move) => move.from === own)) {
503
- drag = { pointer: event.pointerId, from: own, x: event.clientX, y: event.clientY, active: false, ghost: null };
504
- }
505
- };
506
- const onMove = (event) => {
507
- if (drag === null || event.pointerId !== drag.pointer)
508
- return;
509
- if (!drag.active) {
510
- if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 8)
511
- return;
512
- drag.active = true;
513
- selected = drag.from;
514
- render();
515
- const svg = boardBox.querySelector("svg");
516
- const rect = svg?.getBoundingClientRect();
517
- const viewWidth = svg?.viewBox.baseVal.width ?? 1;
518
- const scale = rect === undefined ? 1 : rect.width / viewWidth;
519
- const side = game.turn;
520
- const colours = sampleColour(side);
521
- const ghost = create(document, "div", "sgp-ghost");
522
- const diameter = CHECKER * scale;
523
- ghost.style.width = `${diameter}px`;
524
- ghost.style.height = `${diameter}px`;
525
- ghost.style.background = colours.fill;
526
- ghost.style.borderColor = colours.edge;
527
- host.append(ghost);
528
- drag.ghost = ghost;
529
- try {
530
- boardBox.setPointerCapture(event.pointerId);
531
- }
532
- catch {
533
- /* Capture is a nicety. */
534
- }
535
- }
536
- if (drag.ghost !== null) {
537
- const w = drag.ghost.offsetWidth;
538
- drag.ghost.style.transform = `translate(${event.clientX - w / 2}px, ${event.clientY - w / 2}px)`;
539
- }
540
- };
541
- const onUp = (event) => {
542
- if (drag === null || event.pointerId !== drag.pointer) {
543
- return;
544
- }
545
- const finished = drag;
546
- drag = null;
547
- finished.ghost?.remove();
548
- try {
549
- boardBox.releasePointerCapture(event.pointerId);
550
- }
551
- catch {
552
- /* Already released. */
553
- }
554
- if (!finished.active)
555
- return;
556
- const to = whereIs(underPointer(event.clientX, event.clientY));
557
- if (to !== null && makeMove({ from: finished.from, to }))
558
- return;
559
- selected = null;
560
- render();
561
- };
562
- const onCancel = (event) => {
563
- if (drag === null || event.pointerId !== drag.pointer)
564
- return;
565
- drag.ghost?.remove();
566
- const wasActive = drag.active;
567
- drag = null;
568
- if (wasActive) {
569
- selected = null;
570
- render();
571
- }
572
- };
573
- /** A tap or a click: the drag handlers deal with a drag, and a click that follows one is ignored. */
574
- let lastDragEnd = 0;
575
- const onClick = (event) => {
576
- if (Date.now() - lastDragEnd < 60)
577
- return;
578
- if (game.phase !== "playing" || game.turn === null || !human(game.turn))
579
- return;
580
- press(whereIs(event.target));
581
- };
582
- boardBox.addEventListener("pointerdown", onDown);
583
- boardBox.addEventListener("pointermove", onMove);
584
- boardBox.addEventListener("pointerup", (event) => {
585
- const wasDrag = drag?.active === true;
586
- onUp(event);
587
- if (wasDrag)
588
- lastDragEnd = Date.now();
589
- });
590
- boardBox.addEventListener("pointercancel", onCancel);
591
- boardBox.addEventListener("click", onClick);
592
- // Following the page: its width, and its language.
593
- const resize = typeof view.ResizeObserver === "undefined" ? null : new view.ResizeObserver(() => {
594
- const wide = look.orientation === "portrait" || (look.orientation !== "landscape" && (host.clientWidth || 600) < 560);
595
- if (wide !== portrait)
596
- render();
597
- });
598
- resize?.observe(host);
599
- const watch = typeof view.MutationObserver === "undefined" ? null : new view.MutationObserver(() => {
600
- if (language === undefined)
601
- render();
602
- });
603
- watch?.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] });
604
321
  // The handle.
605
322
  const api = {
606
323
  host,
@@ -656,7 +373,10 @@ export function mountSugoroku(host, options = {}) {
656
373
  if (change.preset !== undefined)
657
374
  settings = settingsOf(undefined, undefined, change.preset);
658
375
  else if (change.variant !== undefined || change.rules !== undefined)
659
- settings = settingsOf(change.variant ?? settings.variant.key, { ...(change.variant === undefined ? settings.rules : {}), ...change.rules });
376
+ settings = settingsOf(change.variant ?? settings.variant.key, {
377
+ ...(change.variant === undefined ? settings.rules : {}),
378
+ ...change.rules,
379
+ });
660
380
  match = newMatch(settings);
661
381
  recorder = new GameRecorder(settings, seed);
662
382
  recorder.startGame();
@@ -685,16 +405,44 @@ export function mountSugoroku(host, options = {}) {
685
405
  gone = true;
686
406
  if (timer !== null)
687
407
  clearTimeout(timer);
688
- resize?.disconnect();
689
- watch?.disconnect();
408
+ disconnectView();
690
409
  sounds?.destroy();
691
- drag?.ghost?.remove();
692
410
  host.replaceChildren();
693
411
  host.classList.remove("sugoroku-play");
694
412
  for (const key of ["drag", "phase", "turn", "over", "orientation", "selected", "cube", "need", "ready"])
695
413
  delete host.dataset[key];
696
414
  },
697
415
  };
416
+ const viewHandle = attachSugorokuView({
417
+ host,
418
+ doc: document,
419
+ page: view,
420
+ boardBox,
421
+ score,
422
+ status,
423
+ slotA,
424
+ slotB,
425
+ slotC,
426
+ dragAllowed,
427
+ say,
428
+ nameOf,
429
+ human,
430
+ isComputer,
431
+ spec,
432
+ makeMove,
433
+ game: () => game,
434
+ match: () => match,
435
+ settings: () => settings,
436
+ look: () => look,
437
+ waitingForDice: () => waitingForDice,
438
+ lastOpening: () => lastOpening,
439
+ followsPageLanguage: () => language === undefined,
440
+ stopped: () => gone,
441
+ actions: () => api,
442
+ });
443
+ render = viewHandle.render;
444
+ resetPointer = viewHandle.resetPointer;
445
+ disconnectView = viewHandle.disconnect;
698
446
  render();
699
447
  startComputer();
700
448
  return api;
@@ -0,0 +1,58 @@
1
+ import { type GameState } from "./game.ts";
2
+ import type { Match } from "./match.ts";
3
+ import type { SugorokuLook } from "./mount.ts";
4
+ import type { Settings } from "./rules.ts";
5
+ import { type Side } from "./side.ts";
6
+ /** What the three buttons can ask the mounted game to do. */
7
+ export type SugorokuPlayActions = {
8
+ newMatch: () => void;
9
+ nextGame: () => void;
10
+ roll: () => void;
11
+ take: () => void;
12
+ drop: () => void;
13
+ beaver: () => void;
14
+ double: () => void;
15
+ done: () => void;
16
+ undo: () => void;
17
+ };
18
+ /** The drawing, the words, the buttons and the pointer. The game itself stays in `mountSugoroku`. */
19
+ export type SugorokuViewInput = {
20
+ host: HTMLElement;
21
+ doc: Document;
22
+ page: Window & typeof globalThis;
23
+ boardBox: HTMLElement;
24
+ score: HTMLElement;
25
+ status: HTMLElement;
26
+ slotA: HTMLButtonElement;
27
+ slotB: HTMLButtonElement;
28
+ slotC: HTMLButtonElement;
29
+ dragAllowed: boolean;
30
+ say: (key: string, values?: Record<string, string | number>) => string;
31
+ nameOf: (side: Side) => string;
32
+ human: (side: Side) => boolean;
33
+ isComputer: (side: Side) => boolean;
34
+ spec: () => GameState["settings"]["variant"];
35
+ makeMove: (step: {
36
+ from: number;
37
+ to: number;
38
+ }) => boolean;
39
+ game: () => GameState;
40
+ match: () => Match;
41
+ settings: () => Settings;
42
+ look: () => SugorokuLook;
43
+ waitingForDice: () => boolean;
44
+ lastOpening: () => readonly [number, number] | null;
45
+ followsPageLanguage: () => boolean;
46
+ /** The board has been taken down. */
47
+ stopped: () => boolean;
48
+ actions: () => SugorokuPlayActions;
49
+ };
50
+ export type SugorokuView = {
51
+ render: () => void;
52
+ /** Drop the selected point and any message, as a new position of the game does. */
53
+ resetPointer: () => void;
54
+ /** Listeners, the resize watch and a checker still being dragged. */
55
+ disconnect: () => void;
56
+ };
57
+ /** Draw the board, keep the words and buttons up to date, and play by pointer. */
58
+ export declare function attachSugorokuView(input: SugorokuViewInput): SugorokuView;