@johnmorrisdotca/jirai 0.2.0 → 0.3.0

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 (55) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/README.md +172 -79
  3. package/dist/element.d.ts +2 -0
  4. package/dist/element.js +2 -0
  5. package/dist/game.d.ts +2 -1
  6. package/dist/game.js +2 -1
  7. package/dist/generate.d.ts +7 -1
  8. package/dist/generate.js +74 -43
  9. package/dist/grid.d.ts +2 -0
  10. package/dist/grid.js +2 -0
  11. package/dist/index.d.ts +7 -1
  12. package/dist/index.js +4 -1
  13. package/dist/jirai.constants.d.ts +55 -10
  14. package/dist/jirai.constants.js +28 -5
  15. package/dist/jirai.types.d.ts +24 -1
  16. package/dist/levels.d.ts +16 -0
  17. package/dist/levels.js +29 -0
  18. package/dist/measure.d.ts +28 -0
  19. package/dist/measure.js +21 -0
  20. package/dist/orthogonal.d.ts +1 -0
  21. package/dist/react.d.ts +1 -1
  22. package/dist/react.js +1 -1
  23. package/dist/react.types.d.ts +1 -0
  24. package/dist/repair.d.ts +14 -0
  25. package/dist/repair.js +112 -0
  26. package/dist/shape.d.ts +2 -0
  27. package/dist/shape.js +2 -0
  28. package/dist/solve.d.ts +79 -0
  29. package/dist/solve.js +336 -0
  30. package/dist/strings.d.ts +2 -0
  31. package/dist/strings.js +2 -0
  32. package/dist/ui.types.d.ts +5 -0
  33. package/package.json +37 -9
  34. package/src/element.ts +2 -0
  35. package/src/family.test.js +105 -0
  36. package/src/game.ts +2 -1
  37. package/src/generate.ts +60 -33
  38. package/src/grid.ts +2 -0
  39. package/src/index.ts +7 -1
  40. package/src/jirai.constants.ts +28 -5
  41. package/src/jirai.types.ts +23 -2
  42. package/src/levels.ts +31 -0
  43. package/src/measure.ts +44 -0
  44. package/src/orthogonal.ts +1 -0
  45. package/src/react.tsx +1 -1
  46. package/src/react.types.ts +1 -0
  47. package/src/repair.ts +88 -0
  48. package/src/shape.ts +2 -0
  49. package/src/solve.ts +253 -0
  50. package/src/strings.ts +2 -0
  51. package/src/ui.types.ts +5 -0
  52. package/src/version.test.js +9 -0
  53. package/src/deduce.test.ts +0 -47
  54. package/src/game.test.ts +0 -172
  55. package/src/shape.test.ts +0 -56
package/src/generate.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { activeCell, activeCells } from "./shape.ts";
2
- import { deduce } from "./deduce.ts";
3
- import { flood } from "./flood.ts";
4
- import { GENERATION_ATTEMPTS, MARKS, STATUSES } from "./jirai.constants.ts";
1
+ import { activeCells } from "./shape.ts";
2
+ import { GENERATION_ATTEMPTS } from "./jirai.constants.ts";
5
3
  import { neighbours, neighboursOf, validCell, validSettings } from "./grid.ts";
4
+ import { repair } from "./repair.ts";
6
5
  import { seededRandom, shuffled } from "./random.ts";
7
- import type { Board, GenerationOptions, Settings, VisibleGame } from "./jirai.types.ts";
6
+ import { Solver } from "./solve.ts";
7
+ import type { Board, GenerationOptions, Settings } from "./jirai.types.ts";
8
8
 
9
9
  /** A bounded generator must say it failed, never quietly return a guessing board. */
10
10
  export class GenerationError extends Error {
@@ -13,45 +13,72 @@ export class GenerationError extends Error {
13
13
 
14
14
  /** Verify a board from one opening, using only clues that have been uncovered. */
15
15
  export function isSolvable(board: Board, enumerate = true): boolean {
16
- const adjacent = neighboursOf(board.settings);
17
- const open = board.clues.map(() => false);
18
- const known = new Set<number>();
19
- flood(board.clues, adjacent, open, [board.first]);
20
- while (open.filter(Boolean).length < activeCells(board.settings).length - board.settings.mines) {
21
- const visible: VisibleGame = {
22
- settings: board.settings, clues: board.clues.map((n, cell) => activeCell(board.settings, cell) ? open[cell] ? n : null : -2),
23
- marks: open.map((yes) => yes ? MARKS.open : MARKS.covered), status: STATUSES.playing,
24
- };
25
- const result = deduce(visible, known, enumerate);
26
- if (result.contradiction) return false;
27
- let changed = false;
28
- for (const cell of result.mines) {
29
- if (!board.mines[cell]) return false;
30
- if (!known.has(cell)) { known.add(cell); changed = true; }
31
- }
32
- if (result.safe.some((cell) => board.mines[cell])) return false;
33
- if (result.safe.some((cell) => !open[cell])) { flood(board.clues, adjacent, open, result.safe); changed = true; }
34
- if (!changed) return false;
35
- }
36
- return true;
16
+ const solver = new Solver(board.settings);
17
+ return solver.run(Int8Array.from(board.clues), board.first, enumerate).solved;
37
18
  }
38
19
 
39
- /** Deal after the first reveal. A seed fixes the whole candidate stream and the accepted board. */
20
+ /** Layouts the repair stage may try, per cell of the field. */
21
+ const REPAIRS_PER_CELL = 12;
22
+
23
+ /**
24
+ * Deal after the first reveal. A seed fixes the whole candidate stream and the accepted board.
25
+ *
26
+ * A no-guess deal first draws random layouts, as 0.1 and 0.2 did, so every board those versions dealt is still dealt.
27
+ * If none of them can be finished by deduction it takes the closest and repairs it: single mines are moved near the
28
+ * place the solver stopped until the solver finishes the whole field. The result is proved the same way either route.
29
+ */
40
30
  export function makeBoard(settings: Settings, first: number, options: GenerationOptions = {}): Board {
41
31
  if (!validSettings(settings) || !validCell(settings, first)) throw new GenerationError("settings", "Invalid board settings or opening cell.");
42
32
  const protectedCells = new Set([first, ...(settings.opening === "clear" ? neighbours(settings, first) : [])]);
43
- const available = Array.from({ length: settings.width * settings.height }, (_, cell) => cell).filter((cell) => validCell(settings, cell) && !protectedCells.has(cell));
33
+ const available = activeCells(settings).filter((cell) => !protectedCells.has(cell));
44
34
  if (available.length < settings.mines) throw new GenerationError("opening", "Too many mines for a safe opening at this cell.");
35
+ if (settings.noGuess && neighbours(settings, first).length === 0 && available.length > settings.mines)
36
+ throw new GenerationError("opening", "The opening cell touches no other cell, so no clue can follow from it. Open another cell.");
45
37
  const attempts = options.attempts ?? GENERATION_ATTEMPTS;
46
38
  if (!Number.isInteger(attempts) || attempts < 1 || attempts > 10_000) throw new GenerationError("settings", "Attempts must be between 1 and 10000.");
39
+ const repairs = options.repairs ?? (options.repair === false ? 0 : REPAIRS_PER_CELL * settings.width * settings.height);
40
+ if (!Number.isInteger(repairs) || repairs < 0 || repairs > 1_000_000) throw new GenerationError("settings", "Repairs must be between 0 and 1000000.");
41
+ const enumerate = options.enumerate ?? true;
47
42
  const random = seededRandom(settings.seed);
48
43
  const adjacent = neighboursOf(settings);
44
+ const solver = new Solver(settings, adjacent);
45
+ const cells = settings.width * settings.height;
46
+ const layout = new Uint8Array(cells), clues = new Int8Array(cells);
47
+ let best: Uint8Array | null = null, fewest = Infinity;
48
+ const board = (attempt: number): Board => ({
49
+ settings: { ...settings }, mines: Array.from(layout, Boolean), clues: Array.from(clues), first, attempt,
50
+ });
49
51
  for (let attempt = 0; attempt < (settings.noGuess ? attempts : 1); attempt += 1) {
50
- const places = new Set(shuffled(available, random).slice(0, settings.mines));
51
- const mines = available.length ? Array.from({ length: settings.width * settings.height }, (_, cell) => places.has(cell)) : [];
52
- const clues = mines.map((mine, cell) => !activeCell(settings, cell) ? -2 : mine ? -1 : adjacent[cell]!.filter((n) => mines[n]).length);
53
- const board: Board = { settings: { ...settings }, mines, clues, first, attempt };
54
- if (!settings.noGuess || isSolvable(board, options.enumerate ?? true)) return board;
52
+ layout.fill(0);
53
+ for (const cell of shuffled(available, random).slice(0, settings.mines)) layout[cell] = 1;
54
+ solver.clueFor(layout, clues);
55
+ if (!settings.noGuess) return board(attempt);
56
+ const report = solver.run(clues, first, enumerate);
57
+ if (report.solved) return board(attempt);
58
+ if (report.remaining < fewest) { fewest = report.remaining; best = layout.slice(); }
59
+ }
60
+ if (best !== null && repairs > 0) {
61
+ // A cell no chain of neighbours reaches from the opening can never be told by a clue. Make each a mine and leave it
62
+ // be: nobody has to find a mine to win, and nobody could find that one. Fewer mines than such cells: do not try.
63
+ const reached = new Set([first]);
64
+ for (const cell of reached) for (const n of adjacent[cell]!) reached.add(n);
65
+ const stranded = available.filter((cell) => !reached.has(cell));
66
+ if (stranded.length <= settings.mines) {
67
+ const reachable = available.filter((cell) => reached.has(cell));
68
+ const place = (): void => {
69
+ layout.fill(0);
70
+ for (const cell of stranded) layout[cell] = 1;
71
+ for (const cell of shuffled(reachable, random).slice(0, settings.mines - stranded.length)) layout[cell] = 1;
72
+ solver.clueFor(layout, clues);
73
+ };
74
+ // Begin from the closest of the random layouts, with the stranded cells made mines at the cost of other mines.
75
+ layout.set(best);
76
+ const movable = reachable.filter((cell) => layout[cell]);
77
+ for (const cell of shuffled(stranded.filter((c) => !layout[c]), random)) { const from = movable.pop(); layout[from!] = 0; layout[cell] = 1; }
78
+ solver.clueFor(layout, clues);
79
+ const outcome = repair(solver, layout, clues, first, new Set([...protectedCells, ...stranded]), random, repairs, enumerate, place);
80
+ if (outcome.solved) return board(attempts + outcome.tries);
81
+ }
55
82
  }
56
83
  throw new GenerationError("exhausted", "No verified board found within the work budget. Try another seed, fewer mines, or a different opening.");
57
84
  }
package/src/grid.ts CHANGED
@@ -17,6 +17,7 @@ export function validSettings(value: unknown): value is Settings {
17
17
  && (s.opening === "safe" || s.opening === "clear")
18
18
  && Number.isInteger(s.seed) && s.seed >= 0 && s.seed <= 0xffffffff;
19
19
  }
20
+ /** Reports whether a row-major cell is inside the board's active shape. */
20
21
  export function validCell(settings: Settings, cell: number): boolean {
21
22
  return Number.isInteger(cell) && cell >= 0 && cell < settings.width * settings.height && activeCell(settings, cell);
22
23
  }
@@ -37,6 +38,7 @@ export function neighbours(settings: Settings, cell: number): number[] {
37
38
  }
38
39
  return [...out].sort((a, b) => a - b);
39
40
  }
41
+ /** Precomputes the neighbour list for each row-major cell. */
40
42
  export function neighboursOf(settings: Settings): number[][] {
41
43
  return Array.from({ length: settings.width * settings.height }, (_, cell) => neighbours(settings, cell));
42
44
  }
package/src/index.ts CHANGED
@@ -7,8 +7,14 @@ export * from "./game.ts";
7
7
  export * from "./deduce.ts";
8
8
  export * from "./keep.ts";
9
9
  export { seededRandom } from "./random.ts";
10
- export const VERSION = "0.2.0";
10
+ /** Package version, kept in step with the release metadata. */
11
+ export const VERSION = "0.3.0";
11
12
 
12
13
  export { SHAPES, activeCell, activeCells } from "./shape.ts";
13
14
 
14
15
  export * from "./orthogonal.ts";
16
+ export { measureBoard } from "./measure.ts";
17
+ export type { Measure } from "./measure.ts";
18
+ export type { ProofKind, ProofTally } from "./solve.ts";
19
+ export { levelNamed, levelSettings } from "./levels.ts";
20
+ export type { LevelSize } from "./levels.ts";
@@ -1,26 +1,49 @@
1
1
  import type { Grid, Settings } from "./jirai.types.ts";
2
2
 
3
+ /** Names for the supported square, four-neighbour, hex, and wrap grids. */
3
4
  export const GRIDS = { square: "square", orthogonal: "orthogonal", hex: "hex", wrap: "wrap" } as const;
5
+ /** Names for the game lifecycle states. */
4
6
  export const STATUSES = { ready: "ready", playing: "playing", won: "won", lost: "lost" } as const;
7
+ /** Names for the cell mark cycle. */
5
8
  export const MARKS = { covered: "covered", flag: "flag", question: "question", open: "open" } as const;
9
+ /** Names for the moves accepted by the engine. */
6
10
  export const MOVES = { reveal: "reveal", mark: "mark", chord: "chord" } as const;
7
- /** Hex coordinates are axial: a row is displaced half a cell to the right. */
11
+ /** Neighbour offsets and edge behaviour for each topology. Hex coordinates are axial: each row is displaced half a cell to the right. */
8
12
  export const GRID_SPECS: Record<Grid, { offsets: readonly (readonly [number, number])[]; wrap: boolean }> = {
9
13
  square: { offsets: [[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]], wrap: false },
10
14
  orthogonal: { offsets: [[0,-1],[-1,0],[1,0],[0,1]], wrap: false },
11
15
  hex: { offsets: [[-1,0],[1,0],[0,-1],[1,-1],[-1,1],[0,1]], wrap: false },
12
16
  wrap: { offsets: [[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]], wrap: true },
13
17
  };
18
+ /** The four difficulty levels, easiest first. Each is a larger and denser field than the one before. */
19
+ export const LEVELS = ["easy", "medium", "hard", "extra-hard"] as const;
20
+ /** The 0.1 and 0.2 names for the first three levels. They are still accepted wherever a level is. */
21
+ export const LEVEL_ALIASES = { beginner: "easy", intermediate: "medium", expert: "hard" } as const;
22
+ /** Size and mine count of each level on a rectangular board. Shaped boards keep the size and the density. */
23
+ export const LEVEL_SIZES: Record<(typeof LEVELS)[number], { width: number; height: number; mines: number }> = {
24
+ easy: { width: 9, height: 9, mines: 10 },
25
+ medium: { width: 16, height: 16, mines: 40 },
26
+ hard: { width: 30, height: 16, mines: 99 },
27
+ "extra-hard": { width: 40, height: 24, mines: 240 },
28
+ };
29
+ /** Common minefield dimensions and mine counts. The levels, their older names, and two shapes of field. */
14
30
  export const PRESETS = {
15
- beginner: { width: 9, height: 9, mines: 10 },
16
- intermediate: { width: 16, height: 16, mines: 40 },
17
- expert: { width: 30, height: 16, mines: 99 },
31
+ ...LEVEL_SIZES,
32
+ beginner: LEVEL_SIZES.easy,
33
+ intermediate: LEVEL_SIZES.medium,
34
+ expert: LEVEL_SIZES.hard,
18
35
  wide: { width: 21, height: 9, mines: 24 },
19
36
  tall: { width: 9, height: 21, mines: 24 },
20
37
  } as const;
21
- export const DEFAULT_SETTINGS: Settings = { ...PRESETS.beginner, grid: GRIDS.square, noGuess: true, opening: "clear", seed: 1 };
38
+ /** Default easy game, with a verified no-guess board and clear opening. */
39
+ export const DEFAULT_SETTINGS: Settings = { ...LEVEL_SIZES.easy, grid: GRIDS.square, noGuess: true, opening: "clear", seed: 1 };
40
+ /** Largest width or height accepted by settings validation. */
22
41
  export const MAX_SIDE = 60;
42
+ /** Largest total cell count accepted by settings validation. */
23
43
  export const MAX_CELLS = 2400;
44
+ /** Default number of random layouts tried before a no-guess deal falls back to repairing the closest one. */
24
45
  export const GENERATION_ATTEMPTS = 128;
46
+ /** Largest frontier enumerated for exact deductions. */
25
47
  export const ENUMERATION_CELLS = 18;
48
+ /** Maximum partial assignments checked in one exact deduction search. */
26
49
  export const ENUMERATION_NODES = 100_000;
@@ -1,7 +1,14 @@
1
- /** A cell's number is its row-major place on the board, starting at zero. */
1
+ /** Neighbour topology used to count the clues around each cell. */
2
2
  export type Grid = "square" | "orthogonal" | "hex" | "wrap";
3
+ /** A difficulty level: easy, medium, hard or extra-hard. */
4
+ export type Level = "easy" | "medium" | "hard" | "extra-hard";
5
+ /** The 0.1 and 0.2 names for easy, medium and hard, still accepted wherever a level is. */
6
+ export type LevelAlias = "beginner" | "intermediate" | "expert";
7
+ /** Current game state, including whether a mine has been hit. */
3
8
  export type Status = "ready" | "playing" | "won" | "lost";
9
+ /** Player-facing state of one cell; the answer is never a mark. */
4
10
  export type Mark = "covered" | "flag" | "question" | "open";
11
+ /** Board dimensions and rules used to deal and validate a game. */
5
12
  export type Settings = {
6
13
  /** Shape omits cells; rectangle is the compatible default. Wrap requires rectangle. */
7
14
  shape?: "rectangle" | "heart" | "star" | "hexagon";
@@ -15,12 +22,15 @@ export type Settings = {
15
22
  opening: "safe" | "clear";
16
23
  seed: number;
17
24
  };
25
+ /** A reveal, mark-cycle, or numbered-cell chord applied to a game. */
18
26
  export type Move = { kind: "reveal" | "mark" | "chord"; cell: number };
27
+ /** A dealt board including its answer; keep it off public clients. */
19
28
  export type Board = {
20
29
  settings: Settings;
21
30
  mines: readonly boolean[];
22
31
  clues: readonly number[];
23
32
  first: number;
33
+ /** Which candidate this deal was: below the `attempts` limit it is a random layout, at or above it a repaired one. */
24
34
  attempt: number;
25
35
  };
26
36
  /** Rules data includes the answer; never send it to a competitive client. Use visibleGame for hints and drawing. */
@@ -34,6 +44,7 @@ export type Game = {
34
44
  /** A proved hint has been shown during this run. */
35
45
  helped: boolean;
36
46
  };
47
+ /** Answer-free state suitable for deductions, hints, and public display. */
37
48
  export type VisibleGame = {
38
49
  settings: Settings;
39
50
  /** Null is hidden, including flags. Only opened cells give a clue. */
@@ -41,7 +52,9 @@ export type VisibleGame = {
41
52
  marks: readonly Mark[];
42
53
  status: Status;
43
54
  };
55
+ /** An exact count over unknown cells, with the clues that supplied it. */
44
56
  export type Constraint = { cells: readonly number[]; mines: number; sources: readonly number[] };
57
+ /** Certain safe cells and mines proved from visible clues. */
45
58
  export type Deduction = {
46
59
  safe: readonly number[];
47
60
  mines: readonly number[];
@@ -50,7 +63,15 @@ export type Deduction = {
50
63
  /** A conflicting clue, or a board with no consistent mine placement. */
51
64
  contradiction: boolean;
52
65
  };
53
- export type GenerationOptions = { attempts?: number; enumerate?: boolean };
66
+ /**
67
+ * Work limits for seeded board generation and its no-guess check. `attempts` is the number of random layouts tried
68
+ * first; `repairs` is how many single-mine moves the repair stage may try on the closest of them (0, or `repair:
69
+ * false`, keeps the 0.2 behaviour of giving up after the attempts); `enumerate` switches the exact small-frontier check.
70
+ */
71
+ export type GenerationOptions = { attempts?: number; repairs?: number; repair?: boolean; enumerate?: boolean };
72
+ /** Supported interface copy locales. */
54
73
  export type Language = "en" | "ja";
74
+ /** Board colours for drawing and mounted play. */
55
75
  export type Material = "ivory" | "wood" | "slate";
76
+ /** Symbols used to mark mines. */
56
77
  export type Pieces = "flags" | "stones" | "flowers";
package/src/levels.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { LEVEL_ALIASES, LEVEL_SIZES, LEVELS } from "./jirai.constants.ts";
2
+ import { activeCells } from "./shape.ts";
3
+ import type { Grid, Level, LevelAlias, Settings } from "./jirai.types.ts";
4
+
5
+ /** Board size and mine count a level asks for. */
6
+ export type LevelSize = Pick<Settings, "width" | "height" | "mines">;
7
+
8
+ /**
9
+ * The level a name means, or null. Accepts `easy`, `medium`, `hard` and `extra-hard` (also written `extra hard`,
10
+ * `extra_hard` or `extraHard`, in any case), and the older `beginner`, `intermediate` and `expert`.
11
+ */
12
+ export function levelNamed(name: unknown): Level | null {
13
+ if (typeof name !== "string") return null;
14
+ const key = name.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/^extrahard$/, "extra-hard");
15
+ if (Object.hasOwn(LEVEL_ALIASES, key)) return LEVEL_ALIASES[key as LevelAlias];
16
+ return (LEVELS as readonly string[]).includes(key) ? key as Level : null;
17
+ }
18
+
19
+ /**
20
+ * The size and mine count of a level. A rectangle gets the level's own numbers; a shaped board keeps the level's
21
+ * width and height and its density of mines over the cells that are left. Throws `RangeError` for a name that is no level.
22
+ */
23
+ export function levelSettings(level: Level | LevelAlias, board: { grid?: Grid; shape?: Settings["shape"] } = {}): LevelSize {
24
+ const named = levelNamed(level);
25
+ if (named === null) throw new RangeError(`Unknown level: ${String(level)}`);
26
+ const size = LEVEL_SIZES[named];
27
+ if ((board.shape ?? "rectangle") === "rectangle") return { ...size };
28
+ const probe = { ...size, grid: board.grid ?? "square", shape: board.shape, noGuess: true, opening: "clear", seed: 1 } as const;
29
+ const cells = activeCells(probe).length;
30
+ return { width: size.width, height: size.height, mines: Math.max(1, Math.min(cells - 10, Math.round(size.mines / (size.width * size.height) * cells))) };
31
+ }
package/src/measure.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { Solver } from "./solve.ts";
2
+ import type { ProofTally } from "./solve.ts";
3
+ import type { Board } from "./jirai.types.ts";
4
+
5
+ /** How demanding a dealt board is to solve by deduction, measured by solving it. */
6
+ export type Measure = {
7
+ /** Mines per playable cell. */
8
+ density: number;
9
+ /** Playable cells. */
10
+ cells: number;
11
+ /** Share of the safe cells the first reveal opens before any reasoning. */
12
+ opening: number;
13
+ /** Cells proved by each kind of reasoning: one clue, two clues together, the mine counter, or every arrangement of a small frontier. */
14
+ proofs: ProofTally;
15
+ /** Share of the playable cells proved by anything beyond one clue's count: the part of the board that needs multi-step reasoning. */
16
+ multiStep: number;
17
+ /** The longest chain of deductions, each resting on the one before. */
18
+ depth: number;
19
+ /** One number for ranking boards: higher is harder. Not a calibrated rating, but monotone in each part above. */
20
+ score: number;
21
+ /** The board can be finished by deduction alone. */
22
+ solvable: boolean;
23
+ };
24
+
25
+ /**
26
+ * Solve a dealt board from its opening and report what it took. The score is
27
+ * `100 × density + 100 × multiStep + depth ÷ 4`, so it rises with the crowding of the mines, with the share of the
28
+ * field that needs more than a single clue, and with how long the longest chain of reasoning runs. It is a way to
29
+ * put boards in order, not a rating of how long a person will take.
30
+ */
31
+ export function measureBoard(board: Board): Measure {
32
+ const solver = new Solver(board.settings);
33
+ const report = solver.run(Int8Array.from(board.clues), board.first, true);
34
+ const cells = solver.safeTotal + solver.mineTotal;
35
+ const density = solver.mineTotal / cells;
36
+ const { count, overlap, total, enumeration } = report.proved;
37
+ const multiStep = (overlap + total + enumeration) / cells;
38
+ const opening = solver.safeTotal === 0 ? 0 : report.free / solver.safeTotal;
39
+ const score = 100 * density + 100 * multiStep + report.depth / 4;
40
+ return {
41
+ density, cells, opening, proofs: { count, overlap, total, enumeration }, multiStep, depth: report.depth,
42
+ score: Math.round(score * 10) / 10, solvable: report.solved,
43
+ };
44
+ }
package/src/orthogonal.ts CHANGED
@@ -7,6 +7,7 @@ import type { Board, GenerationOptions, Game, Settings } from "./jirai.types.ts"
7
7
 
8
8
  /** Identifies the four-neighbour rules and progress-code format. */
9
9
  export const ORTHOGONAL_VARIANT = "orthogonal" as const;
10
+ /** Settings accepted by the four-neighbour-specific helpers. */
10
11
  export type OrthogonalSettings = Omit<Settings, "grid">;
11
12
 
12
13
  /** Starts a game under four-neighbour rules. */
package/src/react.tsx CHANGED
@@ -2,7 +2,7 @@ import { useEffect, useRef } from "react";
2
2
  import { mountJirai } from "./mount.ts";
3
3
  import type { JiraiProps } from "./react.types.ts";
4
4
 
5
- /** The plain-DOM game as a React component. Options are read on mount; give it a new key to load a new board. */
5
+ /** Renders the DOM player inside a React-owned host. Options are read on mount; use a new key to load a new board. */
6
6
  export function JiraiBoard({ settings, progress, material, pieces, language, controls, onChange, onFinish, onError, ...element }: JiraiProps) {
7
7
  const host = useRef<HTMLDivElement>(null);
8
8
  const latest = useRef({ onChange, onFinish, onError });
@@ -1,3 +1,4 @@
1
1
  import type { HTMLAttributes } from "react";
2
2
  import type { MountOptions } from "./ui.types.ts";
3
+ /** Mount options plus standard div attributes for the React wrapper. */
3
4
  export type JiraiProps = MountOptions & Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "onError">;
package/src/repair.ts ADDED
@@ -0,0 +1,88 @@
1
+ import type { Solver } from "./solve.ts";
2
+
3
+ /** What a repair run did: whether it reached a board the solver finishes, how many layouts it tried, and how many safe cells it left covered. */
4
+ export type RepairOutcome = { solved: boolean; tries: number; remaining: number };
5
+
6
+ /** How readily a move that leaves more safe cells covered is kept, to climb out of a dead end. Small: nearly all such moves are refused. */
7
+ const WARMTH = 0.3;
8
+ /** Tries without getting closer after which the search begins again from a new layout, at least. */
9
+ const PATIENCE = 1500;
10
+ /** How far from the stuck cell a mine may be moved from and to. */
11
+ const REACH = 2;
12
+
13
+ function pick<T>(items: readonly T[], random: () => number): T | undefined {
14
+ return items.length === 0 ? undefined : items[Math.floor(random() * items.length)];
15
+ }
16
+
17
+ /** Move a mine from `from` to `to`, keeping every clue in step. Calling it again with the arguments swapped undoes it. */
18
+ function move(solver: Solver, mines: Uint8Array, clues: Int8Array, from: number, to: number): void {
19
+ mines[from] = 0; mines[to] = 1;
20
+ for (const cell of [from, to]) {
21
+ const delta = cell === to ? 1 : -1;
22
+ for (const n of solver.adjacent[cell]!) if (!mines[n]) clues[n]! += delta;
23
+ }
24
+ clues[to] = -1;
25
+ let count = 0;
26
+ for (const n of solver.adjacent[from]!) if (mines[n]) count += 1;
27
+ clues[from] = count;
28
+ }
29
+
30
+ /**
31
+ * Make an unsolvable layout solvable by moving single mines next to the place the solver got stuck, never touching a
32
+ * pinned cell, and keeping a move when it leaves the solver no worse off (and now and then when it does, so that a
33
+ * dead end can be left). The search is counted in layouts tried, never in time, so a seed always gives the same board.
34
+ * `mines` and `clues` are changed in place and hold the answer when the outcome is solved.
35
+ */
36
+ export function repair(solver: Solver, mines: Uint8Array, clues: Int8Array, first: number, pinned: ReadonlySet<number>, random: () => number, budget: number, enumerate: boolean, restart: () => void): RepairOutcome {
37
+ const around = (cell: number, radius: number): number[] => {
38
+ const seen = new Set([cell]);
39
+ let ring = [cell];
40
+ for (let step = 0; step < radius; step += 1) {
41
+ const next: number[] = [];
42
+ for (const c of ring) for (const n of solver.adjacent[c]!) if (!seen.has(n)) { seen.add(n); next.push(n); }
43
+ ring = next;
44
+ }
45
+ return [...seen].filter((c) => !pinned.has(c));
46
+ };
47
+ let report = solver.run(clues, first, enumerate);
48
+ let tries = 0, closest = report.remaining, idle = 0;
49
+ const patience = Math.max(PATIENCE, 2 * solver.cells);
50
+ while (!report.solved && tries < budget) {
51
+ tries += 1;
52
+ const frontier: number[] = [], covered: number[] = [], cutOff: number[] = [];
53
+ for (let cell = 0; cell < solver.cells; cell += 1) {
54
+ if (solver.state[cell] !== 0) continue;
55
+ covered.push(cell);
56
+ if (solver.adjacent[cell]!.some((n) => solver.state[n] === 1)) frontier.push(cell);
57
+ else if (!mines[cell] && !pinned.has(cell)) cutOff.push(cell);
58
+ }
59
+ let from: number | undefined, to: number | undefined;
60
+ const lost = cutOff.length > 0 && random() < 0.5 ? pick(cutOff, random) : undefined;
61
+ if (lost !== undefined) {
62
+ // A safe cell no opened clue touches is walled in by mines. Either wall one in more, or take a wall mine away.
63
+ const walls = solver.adjacent[lost]!.filter((n) => mines[n] && !pinned.has(n));
64
+ if (walls.length > 0 && random() < 0.5) { from = pick(walls, random); to = pick(around(from!, REACH).filter((c) => !mines[c]), random); }
65
+ else { to = lost; from = pick(around(lost, REACH + 1).filter((c) => mines[c]), random); }
66
+ } else {
67
+ const focus = pick(frontier.length > 0 ? frontier : covered, random);
68
+ if (focus === undefined) break;
69
+ let near = around(focus, REACH);
70
+ from = pick(near.filter((c) => mines[c]), random);
71
+ if (from === undefined) { near = around(focus, REACH + 2); from = pick(near.filter((c) => mines[c]), random); }
72
+ to = pick(near.filter((c) => !mines[c]), random);
73
+ }
74
+ if (from === undefined || to === undefined) continue;
75
+ move(solver, mines, clues, from, to);
76
+ const next = solver.run(clues, first, enumerate);
77
+ const worse = next.remaining - report.remaining;
78
+ if (worse < 0 || (worse === 0 && next.unresolved <= report.unresolved) || (worse > 0 && random() < Math.exp(-worse / WARMTH))) report = next;
79
+ else move(solver, mines, clues, to, from);
80
+ if (report.remaining < closest) { closest = report.remaining; idle = 0; }
81
+ else if (++idle > patience) {
82
+ // Stuck for a long while in one corner of the search: begin again from a new layout.
83
+ restart();
84
+ report = solver.run(clues, first, enumerate); closest = report.remaining; idle = 0;
85
+ }
86
+ }
87
+ return { solved: report.solved, tries, remaining: report.remaining };
88
+ }
package/src/shape.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Settings } from "./jirai.types.ts";
2
+ /** Board silhouettes supported by settings. */
2
3
  export const SHAPES = ["rectangle", "heart", "star", "hexagon"] as const;
3
4
  /** Row-major addresses stay stable; omitted cells have no clue and no neighbours. */
4
5
  export function activeCell(settings: Settings, cell: number): boolean {
@@ -27,6 +28,7 @@ export function activeCell(settings: Settings, cell: number): boolean {
27
28
  default: return true;
28
29
  }
29
30
  }
31
+ /** Returns all active cells in stable row-major order. */
30
32
  export function activeCells(settings: Settings): number[] {
31
33
  return Array.from({ length: settings.width * settings.height }, (_, cell) => cell).filter(cell => activeCell(settings, cell));
32
34
  }