@pretty-chitty/core 1.2.17 → 2.0.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 (170) hide show
  1. package/dist/components/ClientTrustMatchViewer.d.ts +14 -1
  2. package/dist/components/ClientTrustMatchViewer.d.ts.map +1 -1
  3. package/dist/components/ClientTrustMatchViewer.js +25 -2
  4. package/dist/components/ClientTrustMatchViewer.js.map +1 -1
  5. package/dist/components/DemoWrapper.d.ts.map +1 -1
  6. package/dist/components/DemoWrapper.js +4 -11
  7. package/dist/components/DemoWrapper.js.map +1 -1
  8. package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
  9. package/dist/components/Gallery/BuiltItem.js +3 -0
  10. package/dist/components/Gallery/BuiltItem.js.map +1 -1
  11. package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
  12. package/dist/components/Gallery/GalleryController.js +3 -1
  13. package/dist/components/Gallery/GalleryController.js.map +1 -1
  14. package/dist/components/PanelSpark.js +1 -1
  15. package/dist/components/PlayerImage.d.ts.map +1 -1
  16. package/dist/components/PlayerImage.js +21 -1
  17. package/dist/components/PlayerImage.js.map +1 -1
  18. package/dist/components/Playground.d.ts.map +1 -1
  19. package/dist/components/Playground.js +37 -11
  20. package/dist/components/Playground.js.map +1 -1
  21. package/dist/components/TokenizedMessage.d.ts +2 -6
  22. package/dist/components/TokenizedMessage.d.ts.map +1 -1
  23. package/dist/components/TokenizedMessage.js +1 -35
  24. package/dist/components/TokenizedMessage.js.map +1 -1
  25. package/dist/components/TopBarPlayers.d.ts.map +1 -1
  26. package/dist/components/TopBarPlayers.js +1 -1
  27. package/dist/components/TopBarPlayers.js.map +1 -1
  28. package/dist/game/Chit.js +2 -2
  29. package/dist/game/Chit.js.map +1 -1
  30. package/dist/game/ConnectionTransport.d.ts +3 -0
  31. package/dist/game/ConnectionTransport.d.ts.map +1 -1
  32. package/dist/game/ConnectionTransport.js +13 -4
  33. package/dist/game/ConnectionTransport.js.map +1 -1
  34. package/dist/game/Game.d.ts +8 -1
  35. package/dist/game/Game.d.ts.map +1 -1
  36. package/dist/game/Match.d.ts +66 -0
  37. package/dist/game/Match.d.ts.map +1 -1
  38. package/dist/game/Match.js +151 -3
  39. package/dist/game/Match.js.map +1 -1
  40. package/dist/game/MatchStorage.d.ts +8 -1
  41. package/dist/game/MatchStorage.d.ts.map +1 -1
  42. package/dist/game/MatchStorage.js +11 -3
  43. package/dist/game/MatchStorage.js.map +1 -1
  44. package/dist/game/Pick.d.ts +14 -0
  45. package/dist/game/Pick.d.ts.map +1 -1
  46. package/dist/game/Pick.js +15 -0
  47. package/dist/game/Pick.js.map +1 -1
  48. package/dist/game/PlayerChit.d.ts +4 -0
  49. package/dist/game/PlayerChit.d.ts.map +1 -1
  50. package/dist/game/PlayerChit.js +8 -2
  51. package/dist/game/PlayerChit.js.map +1 -1
  52. package/dist/game/PlayerInfo.d.ts +8 -0
  53. package/dist/game/PlayerInfo.d.ts.map +1 -1
  54. package/dist/game/PlayerInfo.js +6 -3
  55. package/dist/game/PlayerInfo.js.map +1 -1
  56. package/dist/game/PlayerPromptStatusChit.d.ts.map +1 -1
  57. package/dist/game/PlayerPromptStatusChit.js +3 -1
  58. package/dist/game/PlayerPromptStatusChit.js.map +1 -1
  59. package/dist/game/Turn.d.ts +11 -2
  60. package/dist/game/Turn.d.ts.map +1 -1
  61. package/dist/game/Turn.js +118 -68
  62. package/dist/game/Turn.js.map +1 -1
  63. package/dist/game/TurnState.d.ts +8 -0
  64. package/dist/game/TurnState.d.ts.map +1 -1
  65. package/dist/game/TurnState.js +7 -0
  66. package/dist/game/TurnState.js.map +1 -1
  67. package/dist/game/ai/AiClientPrompts.d.ts +160 -0
  68. package/dist/game/ai/AiClientPrompts.d.ts.map +1 -0
  69. package/dist/game/ai/AiClientPrompts.js +525 -0
  70. package/dist/game/ai/AiClientPrompts.js.map +1 -0
  71. package/dist/game/ai/AiLiveView.d.ts +2 -0
  72. package/dist/game/ai/AiLiveView.d.ts.map +1 -0
  73. package/dist/game/ai/AiLiveView.js +48 -0
  74. package/dist/game/ai/AiLiveView.js.map +1 -0
  75. package/dist/game/ai/AiPlayerView.d.ts +2 -0
  76. package/dist/game/ai/AiPlayerView.d.ts.map +1 -0
  77. package/dist/game/ai/AiPlayerView.js +89 -0
  78. package/dist/game/ai/AiPlayerView.js.map +1 -0
  79. package/dist/game/ai/connectAiPlayer.d.ts +43 -0
  80. package/dist/game/ai/connectAiPlayer.d.ts.map +1 -0
  81. package/dist/game/ai/connectAiPlayer.js +58 -0
  82. package/dist/game/ai/connectAiPlayer.js.map +1 -0
  83. package/dist/game/ai/defineAi.d.ts +119 -0
  84. package/dist/game/ai/defineAi.d.ts.map +1 -0
  85. package/dist/game/ai/defineAi.js +122 -0
  86. package/dist/game/ai/defineAi.js.map +1 -0
  87. package/dist/game/ai/simulateMatches.d.ts +62 -0
  88. package/dist/game/ai/simulateMatches.d.ts.map +1 -0
  89. package/dist/game/ai/simulateMatches.js +108 -0
  90. package/dist/game/ai/simulateMatches.js.map +1 -0
  91. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts +3 -0
  92. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts.map +1 -1
  93. package/dist/game/badAiTransport/BadAIClientPrompts.js +3 -0
  94. package/dist/game/badAiTransport/BadAIClientPrompts.js.map +1 -1
  95. package/dist/hooks/useTokenMap.d.ts +2 -4
  96. package/dist/hooks/useTokenMap.d.ts.map +1 -1
  97. package/dist/hooks/useTokenMap.js +2 -5
  98. package/dist/hooks/useTokenMap.js.map +1 -1
  99. package/dist/hooks/useWebGlRenderer.d.ts +1 -0
  100. package/dist/hooks/useWebGlRenderer.d.ts.map +1 -1
  101. package/dist/hooks/useWebGlRenderer.js +33 -21
  102. package/dist/hooks/useWebGlRenderer.js.map +1 -1
  103. package/dist/index.d.ts +21 -1
  104. package/dist/index.d.ts.map +1 -1
  105. package/dist/index.js +8 -1
  106. package/dist/index.js.map +1 -1
  107. package/dist/utilities/CanvasStack/CanvasOperations.d.ts +15 -1
  108. package/dist/utilities/CanvasStack/CanvasOperations.d.ts.map +1 -1
  109. package/dist/utilities/CanvasStack/CanvasOperations.js +65 -6
  110. package/dist/utilities/CanvasStack/CanvasOperations.js.map +1 -1
  111. package/dist/utilities/CanvasStack/CanvasStack.d.ts +18 -1
  112. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  113. package/dist/utilities/CanvasStack/CanvasStack.js +119 -6
  114. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  115. package/dist/utilities/CanvasStack/PlayerCanvas.d.ts +2 -1
  116. package/dist/utilities/CanvasStack/PlayerCanvas.d.ts.map +1 -1
  117. package/dist/utilities/CanvasStack/PlayerCanvas.js +3 -2
  118. package/dist/utilities/CanvasStack/PlayerCanvas.js.map +1 -1
  119. package/dist/utilities/CanvasStack/ReactCanvas.d.ts +2 -1
  120. package/dist/utilities/CanvasStack/ReactCanvas.d.ts.map +1 -1
  121. package/dist/utilities/CanvasStack/ReactCanvas.js +2 -2
  122. package/dist/utilities/CanvasStack/ReactCanvas.js.map +1 -1
  123. package/dist/utilities/ParameterizedCanvas.d.ts +1 -0
  124. package/dist/utilities/ParameterizedCanvas.d.ts.map +1 -1
  125. package/dist/utilities/ParameterizedCanvas.js +4 -1
  126. package/dist/utilities/ParameterizedCanvas.js.map +1 -1
  127. package/dist/utilities/TokenizedText.d.ts +49 -0
  128. package/dist/utilities/TokenizedText.d.ts.map +1 -0
  129. package/dist/utilities/TokenizedText.js +47 -0
  130. package/dist/utilities/TokenizedText.js.map +1 -0
  131. package/package.json +1 -1
  132. package/src/library/components/ClientTrustMatchViewer.tsx +32 -2
  133. package/src/library/components/DemoWrapper.tsx +4 -12
  134. package/src/library/components/Gallery/BuiltItem.ts +4 -0
  135. package/src/library/components/Gallery/GalleryController.ts +3 -1
  136. package/src/library/components/PanelSpark.tsx +1 -1
  137. package/src/library/components/PlayerImage.tsx +26 -2
  138. package/src/library/components/Playground.tsx +77 -12
  139. package/src/library/components/TokenizedMessage.tsx +2 -63
  140. package/src/library/components/TopBarPlayers.tsx +6 -1
  141. package/src/library/game/Chit.ts +2 -2
  142. package/src/library/game/ConnectionTransport.ts +12 -3
  143. package/src/library/game/Game.ts +9 -1
  144. package/src/library/game/Match.ts +162 -3
  145. package/src/library/game/MatchStorage.ts +14 -4
  146. package/src/library/game/Pick.ts +20 -0
  147. package/src/library/game/PlayerChit.ts +10 -3
  148. package/src/library/game/PlayerInfo.ts +13 -3
  149. package/src/library/game/PlayerPromptStatusChit.ts +3 -1
  150. package/src/library/game/Turn.ts +131 -76
  151. package/src/library/game/TurnState.ts +8 -0
  152. package/src/library/game/ai/AI_GUIDE.md +434 -0
  153. package/src/library/game/ai/AiClientPrompts.ts +681 -0
  154. package/src/library/game/ai/AiLiveView.ts +63 -0
  155. package/src/library/game/ai/AiPlayerView.ts +112 -0
  156. package/src/library/game/ai/ai.test.ts +475 -0
  157. package/src/library/game/ai/connectAiPlayer.ts +88 -0
  158. package/src/library/game/ai/defineAi.ts +230 -0
  159. package/src/library/game/ai/simulateMatches.ts +172 -0
  160. package/src/library/game/badAiTransport/BadAIClientPrompts.ts +3 -0
  161. package/src/library/hooks/useTokenMap.ts +2 -6
  162. package/src/library/hooks/useWebGlRenderer.tsx +44 -24
  163. package/src/library/index.ts +34 -2
  164. package/src/library/utilities/CanvasStack/CanvasOperations.tsx +87 -17
  165. package/src/library/utilities/CanvasStack/CanvasStack.ts +119 -5
  166. package/src/library/utilities/CanvasStack/PlayerCanvas.tsx +5 -2
  167. package/src/library/utilities/CanvasStack/ReactCanvas.tsx +2 -2
  168. package/src/library/utilities/ParameterizedCanvas.ts +5 -1
  169. package/src/library/utilities/TokenizedText.test.ts +32 -0
  170. package/src/library/utilities/TokenizedText.ts +97 -0
@@ -0,0 +1,88 @@
1
+ import { Connection } from "../Connection";
2
+ import { LocalConnectionTransport } from "../ConnectionTransport";
3
+ import type { Match } from "../Match";
4
+ import { PlayerChit } from "../PlayerChit";
5
+ import { RootChit } from "../RootChit";
6
+ import { ClientStatus } from "../clientTransport/ClientStatus";
7
+ import { AiClientPrompts, AiPlayerOptions } from "./AiClientPrompts";
8
+ import { AiPlayerView } from "./AiPlayerView";
9
+ import { AiLiveView } from "./AiLiveView";
10
+
11
+ export type ConnectAiPlayerOptions = AiPlayerOptions & {
12
+ /** Max simulated transport latency in ms. Default 0 (the bot is in-process) */
13
+ latencyMs?: number;
14
+ /**
15
+ * How the bot reads the board. "live" (the default, unless the game's AI sets `serializedView`)
16
+ * reads the match's own objects in place: fast, but rules can see hidden information.
17
+ * "serialized" rebuilds exactly what the server sends this seat: fair, but every prompt costs a
18
+ * full redacted snapshot.
19
+ */
20
+ view?: "live" | "serialized";
21
+ };
22
+
23
+ export type AiPlayerHandle = {
24
+ playerId: string;
25
+ prompts: AiClientPrompts<any, any, any>;
26
+ status: ClientStatus<any, any>;
27
+ dispose: () => void;
28
+ };
29
+
30
+ /**
31
+ * Seats an AI player in a match. The bot connects like any other client, so it only ever sees
32
+ * what the server sends to `playerId`. Uses `match.game.ai` rules if the game defines them.
33
+ *
34
+ * This is the low-level primitive: it seats exactly one bot with exactly these options, which is
35
+ * what harnesses want (forced moves, per-seat params, a different AI per seat). Hosts that just
36
+ * want every seat flagged `ai` on its `PlayerInfo` played by the engine call
37
+ * {@link Match.seatAiPlayers} instead; it calls this for each such seat and skips seats already
38
+ * taken by a bot connected here.
39
+ *
40
+ * The bot's plan memory is kept in the match's saved state (see `AiMemoryStore`), so a bot
41
+ * re-seated after a reload continues its plan. It also follows `match.ai.enabled`.
42
+ *
43
+ * ```ts
44
+ * connectAiPlayer(match, "p2", { params: { weights }, onDecision: log });
45
+ * ```
46
+ *
47
+ * @group AI
48
+ */
49
+ export function connectAiPlayer<P extends PlayerChit, R extends RootChit<P>>(
50
+ match: Match<P, R>,
51
+ playerId: string,
52
+ options: ConnectAiPlayerOptions = {},
53
+ ): AiPlayerHandle {
54
+ const latency = options.latencyMs ?? 0;
55
+ const serverSide = new LocalConnectionTransport(latency);
56
+ const clientSide = new LocalConnectionTransport(latency);
57
+ const connection = new Connection(clientSide);
58
+
59
+ const mode = options.view ?? (match.game.ai?.serializedView ? "serialized" : "live");
60
+ const view = mode === "live" ? new AiLiveView(match) : new AiPlayerView(connection, match.game);
61
+ const status = new ClientStatus<any, any>(connection);
62
+ const prompts = new AiClientPrompts<P, R>(playerId, connection, match.game, view, {
63
+ ...options,
64
+ difficulty: options.difficulty ?? match.players.find((p) => p.id === playerId)?.ai?.difficulty,
65
+ memoryStore: options.memoryStore === undefined ? match.aiMemoryStore(playerId) : options.memoryStore,
66
+ disabled: options.disabled || !match.ai.enabled,
67
+ });
68
+
69
+ connection.register(view, "ClientTime");
70
+ connection.register(status, "ClientStatus");
71
+ connection.register(prompts, "ClientPrompts");
72
+
73
+ clientSide.connect(serverSide);
74
+ const serverConnection = match.connect(serverSide, playerId);
75
+
76
+ const handle: AiPlayerHandle = {
77
+ playerId,
78
+ prompts,
79
+ status,
80
+ dispose: () => {
81
+ match.ai.unregister(handle);
82
+ connection.dispose();
83
+ serverConnection.dispose();
84
+ },
85
+ };
86
+ match.ai.register(handle);
87
+ return handle;
88
+ }
@@ -0,0 +1,230 @@
1
+ import { Chit } from "../Chit";
2
+ import { GameButton } from "../GameButton";
3
+ import { PickType } from "../Pick";
4
+ import { PlayerChit } from "../PlayerChit";
5
+ import { RootChit } from "../RootChit";
6
+
7
+ /** Where an option came from. */
8
+ export type AiPickInfo = {
9
+ /** Index of the pick within the prompt */
10
+ index: number;
11
+ type: PickType;
12
+ message?: string;
13
+ help?: string;
14
+ context?: Chit;
15
+ /** Class name of the button, for ButtonPicks (e.g. "Confirm") */
16
+ buttonType?: string;
17
+ };
18
+
19
+ type AiOptionBase = {
20
+ /** The key passed to `.ai(key)` on the pick, if any */
21
+ key?: string;
22
+ /** The data passed to `.ai(key, data)` on the pick, if any */
23
+ data?: unknown;
24
+ pick: AiPickInfo;
25
+ /** @internal */
26
+ response: { idx: number; pickType: PickType; value: any };
27
+ };
28
+
29
+ /** Clicking a chit (from `Chit.pick`). `chit` comes from the AI player's own view of the board. */
30
+ export type AiChitOption = AiOptionBase & { kind: "chit"; chit: Chit };
31
+ /** Dragging `chit` onto `target` (from `Chit.dragPick`). */
32
+ export type AiDragOption = AiOptionBase & { kind: "drag"; chit: Chit; target: Chit };
33
+ /** Pressing a button. */
34
+ export type AiButtonOption = AiOptionBase & { kind: "button"; button: GameButton };
35
+
36
+ /** A single legal answer to the current prompt. */
37
+ export type AiOption = AiChitOption | AiDragOption | AiButtonOption;
38
+
39
+ export type AiContext<P extends PlayerChit, R extends RootChit<P>, M> = {
40
+ /**
41
+ * The board exactly as this player sees it: rebuilt from what the server sends this seat, so any
42
+ * property hidden by `hiddenPropertiesForSerialization` is `undefined`.
43
+ */
44
+ view: R;
45
+ /** This player's PlayerChit inside `view` */
46
+ me: P;
47
+ /** Every legal option in this prompt (useful for comparing against alternatives) */
48
+ options: AiOption[];
49
+ prompt: { message?: string; help?: string };
50
+ /** Per-bot random number generator in [0, 1) */
51
+ random: () => number;
52
+ /** The plan committed by earlier winning options. Read-only; change it by returning a `plan`. */
53
+ memory: Readonly<M>;
54
+ /** Look up a chit in `view` by id (e.g. an id stored in memory). Undefined if it no longer exists. */
55
+ find: (id: string) => Chit | undefined;
56
+ /** `params` from `connectAiPlayer` for this seat (per-seat weights, a personality…); undefined if none */
57
+ params: any;
58
+ };
59
+
60
+ /**
61
+ * What a rule returns: a plain score, or a score plus a plan. Higher scores are better, and
62
+ * `-Infinity` means "never pick this unless nothing else is possible". The plan is only
63
+ * committed to memory if this option is the one chosen. Pass a whole new memory value, or a
64
+ * function that updates the previous one.
65
+ */
66
+ export type AiScore<M> = number | { score: number; plan?: M | ((prev: M) => M) };
67
+
68
+ export type AiRule<P extends PlayerChit, R extends RootChit<P>, M> = (
69
+ option: AiOption,
70
+ ctx: AiContext<P, R, M>,
71
+ ) => AiScore<M>;
72
+
73
+ export interface GameAi<P extends PlayerChit, R extends RootChit<P>, M = Record<string, never>> {
74
+ /** Starting memory for each bot. Memory must be JSON-serializable: store chit ids, not chits. */
75
+ initialMemory?: () => M;
76
+ /** Rules keyed by the name passed to `.ai(key)` on a pick */
77
+ rules?: { [key: string]: AiRule<P, R, M> };
78
+ /**
79
+ * Scores options from untagged picks (or tags with no matching rule). If it is not supplied,
80
+ * those options score 0 when mixed with tagged picks, and a prompt with no tagged picks at all
81
+ * is answered at random, weighted by `Game.demoPickWeight`.
82
+ */
83
+ default?: AiRule<P, R, M>;
84
+ /**
85
+ * Read the board through the serialized, per-seat view instead of the live game objects. The
86
+ * live view (the default) is much faster but lets rules read hidden fields and other players'
87
+ * unfinished simultaneous moves; set this when your rules would otherwise use information the
88
+ * seat should not have.
89
+ */
90
+ serializedView?: boolean;
91
+ /**
92
+ * Default for `connectAiPlayer`'s `temperature` (softmax over scores, in score units) for every
93
+ * bot of this game, including demo and Playground bots. Unset: the `difficulty` noise.
94
+ */
95
+ temperature?: number;
96
+ }
97
+
98
+ /**
99
+ * Declares a game's AI. Set it as `ai` on your Game class.
100
+ *
101
+ * ```ts
102
+ * export const ai = defineAi<MyPlayer, MyRoot, { target?: string }>({
103
+ * initialMemory: () => ({}),
104
+ * rules: {
105
+ * "market.buy": (opt, { me }) => ({ score: value(opt.chit as Card, me), plan: { target: opt.chit.id } }),
106
+ * "pass": () => 0,
107
+ * },
108
+ * });
109
+ * ```
110
+ *
111
+ * @group AI
112
+ */
113
+ export function defineAi<P extends PlayerChit, R extends RootChit<P>, M = Record<string, never>>(
114
+ ai: GameAi<P, R, M>,
115
+ ): GameAi<P, R, M> {
116
+ return ai;
117
+ }
118
+
119
+ /** @internal */
120
+ export type NormalizedScore<M> = { score: number; plan?: M | ((prev: M) => M) };
121
+
122
+ /** @internal */
123
+ export function normalizeScore<M>(score: AiScore<M>): NormalizedScore<M> {
124
+ if (typeof score === "number") {
125
+ return { score: Number.isNaN(score) ? 0 : score };
126
+ }
127
+ return { score: Number.isNaN(score?.score) ? 0 : (score?.score ?? 0), plan: score?.plan };
128
+ }
129
+
130
+ /** @internal */
131
+ export function applyPlan<M>(memory: M, plan: NormalizedScore<M>["plan"]): M {
132
+ if (plan === undefined) {
133
+ return memory;
134
+ }
135
+ return typeof plan === "function" ? (plan as (prev: M) => M)(memory) : plan;
136
+ }
137
+
138
+ /**
139
+ * Picks an index from scored entries: the best score wins, near-ties are broken at random, and
140
+ * `noise` (0 = none, 1 = a lot) blurs the scores so bots aren't perfectly predictable. Entries
141
+ * scoring -Infinity are only chosen when nothing else is available.
142
+ * @internal
143
+ */
144
+ export function chooseIndex(scores: number[], noise: number, random: () => number): number {
145
+ if (scores.length === 0) {
146
+ return -1;
147
+ }
148
+
149
+ let candidates = scores.map((score, index) => ({ score, index })).filter((s) => s.score !== -Infinity);
150
+ if (candidates.length === 0) {
151
+ candidates = scores.map((score, index) => ({ score: 0, index }));
152
+ }
153
+
154
+ const finite = candidates.map((c) => c.score).filter((s) => Number.isFinite(s));
155
+ const spread = finite.length > 1 ? Math.max(...finite) - Math.min(...finite) : 0;
156
+ const scale = (spread || 1) * Math.max(0, noise);
157
+ const jittered = candidates.map((c) => ({ ...c, score: c.score + (random() - 0.5) * scale }));
158
+
159
+ const best = Math.max(...jittered.map((c) => c.score));
160
+ const epsilon = Number.isFinite(best) ? Math.max(1e-9, Math.abs(best) * 1e-9) : 0;
161
+ const top = jittered.filter((c) => (Number.isFinite(best) ? best - c.score <= epsilon : c.score === best));
162
+ return top[Math.floor(random() * top.length)].index;
163
+ }
164
+
165
+ /**
166
+ * Softmax choice: probability ∝ exp((score − best) / temperature). `-Infinity` options are only
167
+ * chosen when nothing else is possible; temperature ≤ 0 picks the best (ties at random).
168
+ * @internal
169
+ */
170
+ export function chooseSoftmax(scores: number[], temperature: number, random: () => number): number {
171
+ if (scores.length === 0) return -1;
172
+ let idx = scores.map((s, i) => i).filter((i) => scores[i] !== -Infinity);
173
+ if (idx.length === 0) idx = scores.map((_, i) => i);
174
+ const vals = idx.map((i) => (Number.isFinite(scores[i]) ? scores[i] : scores[i] > 0 ? Number.MAX_VALUE : 0));
175
+ const best = Math.max(...vals);
176
+ if (!(temperature > 0)) {
177
+ const top = idx.filter((_, k) => vals[k] === best);
178
+ return top[Math.floor(random() * top.length)];
179
+ }
180
+ const w = vals.map((v) => Math.exp((v - best) / temperature));
181
+ const total = w.reduce((a, b) => a + b, 0);
182
+ let r = random() * total;
183
+ for (let k = 0; k < idx.length; k++) {
184
+ r -= w[k];
185
+ if (r <= 0) return idx[k];
186
+ }
187
+ return idx[idx.length - 1];
188
+ }
189
+
190
+ /**
191
+ * Chooses an index with probability proportional to its weight. Used when a prompt has no AI
192
+ * rules at all, and matches the old "bad AI" demo behaviour.
193
+ * @internal
194
+ */
195
+ export function chooseWeighted(weights: number[], random: () => number): number {
196
+ const total = weights.reduce((sum, w) => sum + Math.max(0, w), 0);
197
+ if (total <= 0) {
198
+ return Math.floor(random() * weights.length);
199
+ }
200
+ let roll = random() * total;
201
+ for (let i = 0; i < weights.length; i++) {
202
+ roll -= Math.max(0, weights[i]);
203
+ if (roll < 0) {
204
+ return i;
205
+ }
206
+ }
207
+ return weights.length - 1;
208
+ }
209
+
210
+ /** Small seedable PRNG (mulberry32). @internal */
211
+ export function createRandom(seed: number = Math.floor(Math.random() * 2 ** 32)): () => number {
212
+ let a = seed >>> 0;
213
+ return () => {
214
+ a = (a + 0x6d2b79f5) >>> 0;
215
+ let t = a;
216
+ t = Math.imul(t ^ (t >>> 15), t | 1);
217
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
218
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
219
+ };
220
+ }
221
+
222
+ /** FNV-1a string hash, used for situation fingerprints. @internal */
223
+ export function hashString(s: string): string {
224
+ let h = 0x811c9dc5;
225
+ for (let i = 0; i < s.length; i++) {
226
+ h ^= s.charCodeAt(i);
227
+ h = Math.imul(h, 0x01000193);
228
+ }
229
+ return (h >>> 0).toString(36) + ":" + s.length.toString(36);
230
+ }
@@ -0,0 +1,172 @@
1
+ import { Game } from "../Game";
2
+ import { Match } from "../Match";
3
+ import { EphemeralMatchStorage } from "../MatchStorage";
4
+ import { PlayerChit } from "../PlayerChit";
5
+ import { PlayerInfo } from "../PlayerInfo";
6
+ import { RootChit } from "../RootChit";
7
+ import { AiPlayerStats } from "./AiClientPrompts";
8
+ import { AiPlayerHandle, connectAiPlayer } from "./connectAiPlayer";
9
+
10
+ export type SimulateMatchesOptions = {
11
+ /** Number of seats. Default: whatever `Root.setupDemoGame()` returns */
12
+ players?: number;
13
+ /** Number of matches to play. Default 1 */
14
+ games?: number;
15
+ /** Stop a match after this many answered prompts (all bots combined). Default 5000 */
16
+ maxPrompts?: number;
17
+ /** Stop a match if nothing happens for this long. Default 5000ms */
18
+ stallMs?: number;
19
+ /** Stop a match after this long. Default 120000ms */
20
+ timeoutMs?: number;
21
+ /** Options passed to the match. Default: `Root.getCurrentlySelectedMatchOptions()` after `setupDemoGame()` */
22
+ matchOptions?: any;
23
+ difficulty?: number;
24
+ /** Let bots log untagged prompts and warnings. Default false */
25
+ log?: boolean;
26
+ /** How the bots read the board (see ConnectAiPlayerOptions.view). Default: the game's choice */
27
+ view?: "live" | "serialized";
28
+ };
29
+
30
+ export type SimulatedMatch = {
31
+ outcome: "finished" | "stalled" | "error" | "maxPrompts" | "timeout";
32
+ prompts: number;
33
+ durationMs: number;
34
+ winners: string[];
35
+ error?: string;
36
+ stats: { [playerId: string]: AiPlayerStats };
37
+ };
38
+
39
+ export type SimulationReport = {
40
+ matches: SimulatedMatch[];
41
+ finished: number;
42
+ averagePrompts: number;
43
+ stepBacks: number;
44
+ rejections: number;
45
+ stalls: number;
46
+ stuck: number;
47
+ ruleErrors: number;
48
+ /** Untagged pick messages the bots hit, with counts: a to-do list for writing rules */
49
+ untagged: { [message: string]: number };
50
+ };
51
+
52
+ /**
53
+ * Plays whole matches with an AI in every seat, headlessly, and reports whether they finish.
54
+ * Use it in a test to check that a game's AI never gets stuck:
55
+ *
56
+ * ```ts
57
+ * test("bots can finish a game", async () => {
58
+ * const report = await simulateMatches(new MyGame(), { players: 3, games: 5 });
59
+ * expect(report.finished).toBe(5);
60
+ * });
61
+ * ```
62
+ *
63
+ * @group AI
64
+ */
65
+ export async function simulateMatches<P extends PlayerChit, R extends RootChit<P>>(
66
+ game: Game<P, R>,
67
+ options: SimulateMatchesOptions = {},
68
+ ): Promise<SimulationReport> {
69
+ const matches: SimulatedMatch[] = [];
70
+ for (let i = 0; i < (options.games ?? 1); i++) {
71
+ matches.push(await simulateOne(game, options, i));
72
+ }
73
+
74
+ const all = matches.flatMap((m) => Object.values(m.stats));
75
+ const sum = (f: (s: AiPlayerStats) => number) => all.reduce((acc, s) => acc + f(s), 0);
76
+ const untagged: { [message: string]: number } = {};
77
+ all.forEach((s) =>
78
+ Object.entries(s.untagged).forEach(([message, count]) => (untagged[message] = (untagged[message] ?? 0) + count)),
79
+ );
80
+
81
+ return {
82
+ matches,
83
+ finished: matches.filter((m) => m.outcome === "finished").length,
84
+ averagePrompts: matches.length ? matches.reduce((acc, m) => acc + m.prompts, 0) / matches.length : 0,
85
+ stepBacks: sum((s) => s.stepBacks),
86
+ rejections: sum((s) => s.rejections),
87
+ stalls: sum((s) => s.stalls),
88
+ stuck: sum((s) => s.stuck),
89
+ ruleErrors: sum((s) => s.ruleErrors),
90
+ untagged,
91
+ };
92
+ }
93
+
94
+ async function simulateOne<P extends PlayerChit, R extends RootChit<P>>(
95
+ game: Game<P, R>,
96
+ options: SimulateMatchesOptions,
97
+ index: number,
98
+ ): Promise<SimulatedMatch> {
99
+ const started = Date.now();
100
+ const tempRoot = new game.chitLibrary.Root() as R;
101
+ const defaultPlayers = tempRoot.setupDemoGame();
102
+ const matchOptions = options.matchOptions ?? tempRoot.getCurrentlySelectedMatchOptions();
103
+
104
+ const players: PlayerInfo[] = [];
105
+ for (let i = 0; i < (options.players ?? defaultPlayers); i++) {
106
+ const info = new PlayerInfo(`p${i}`, `Bot ${i + 1}`);
107
+ info.ai = { difficulty: options.difficulty };
108
+ players.push(info);
109
+ }
110
+
111
+ const match = new Match(game, players, new EphemeralMatchStorage(`simulation-${index}`, true), matchOptions);
112
+ match.immediateNotify = true; // headless: see Match.immediateNotify
113
+ await match.load();
114
+
115
+ const stallMs = options.stallMs ?? 5000;
116
+ const bots: AiPlayerHandle[] = players.map((p) =>
117
+ connectAiPlayer(match, p.id, { log: options.log ?? false, stallWarningMs: stallMs, view: options.view }),
118
+ );
119
+ const prompts = () => bots.reduce((acc, b) => acc + b.prompts.stats.promptsAnswered, 0);
120
+ const progress = () => bots.reduce((acc, b) => acc + b.prompts.stats.promptsAnswered + b.prompts.stats.stepBacks, 0);
121
+
122
+ let error: string | undefined;
123
+ const run = match.start().catch((e) => {
124
+ error = e instanceof Error ? e.message : String(e);
125
+ });
126
+
127
+ const outcome = await new Promise<SimulatedMatch["outcome"]>((resolve) => {
128
+ let lastProgress = -1;
129
+ let lastProgressAt = Date.now();
130
+ const timer = setInterval(() => {
131
+ const finish = (o: SimulatedMatch["outcome"]) => {
132
+ clearInterval(timer);
133
+ resolve(o);
134
+ };
135
+ if (match.result.value) return finish("finished");
136
+ if (error || match.errorState.value) return finish("error");
137
+ if (prompts() > (options.maxPrompts ?? 5000)) return finish("maxPrompts");
138
+ if (Date.now() - started > (options.timeoutMs ?? 120000)) return finish("timeout");
139
+
140
+ const p = progress();
141
+ if (p !== lastProgress) {
142
+ lastProgress = p;
143
+ lastProgressAt = Date.now();
144
+ } else if (Date.now() - lastProgressAt > stallMs && bots.every((b) => b.prompts.idle || b.prompts.stalled)) {
145
+ // Idle bots have nothing to answer; stalled ones answered and the server never reacted
146
+ return finish("stalled");
147
+ }
148
+ }, 20);
149
+ });
150
+
151
+ if (outcome === "finished") {
152
+ await run;
153
+ }
154
+
155
+ // Let in-flight answers settle so disposing doesn't reject them mid-flight
156
+ const settleUntil = Date.now() + 1000;
157
+ while (Date.now() < settleUntil && !bots.every((b) => b.prompts.idle || b.prompts.stalled)) {
158
+ await new Promise((resolve) => setTimeout(resolve, 10));
159
+ }
160
+ await new Promise((resolve) => setTimeout(resolve, 10));
161
+
162
+ const result: SimulatedMatch = {
163
+ outcome,
164
+ prompts: prompts(),
165
+ durationMs: Date.now() - started,
166
+ winners: match.result.value?.winners.map((w) => w.id ?? "") ?? [],
167
+ error: error ?? match.errorState.value,
168
+ stats: Object.fromEntries(bots.map((b) => [b.playerId, b.prompts.stats])),
169
+ };
170
+ bots.forEach((b) => b.dispose());
171
+ return result;
172
+ }
@@ -8,6 +8,9 @@ import { PromptSerialization } from "../Prompt";
8
8
  import { RootChit } from "../RootChit";
9
9
  import { ServerPrompts } from "../serverTransport/ServerPrompts";
10
10
 
11
+ /**
12
+ * @deprecated Random-only bot that can also see hidden state. Use `connectAiPlayer` instead.
13
+ */
11
14
  export class BadAIClientPrompts<P extends PlayerChit, R extends RootChit<P>> extends ConnectionObject {
12
15
  private serverPrompts: ServerPrompts<P, R>;
13
16
 
@@ -1,7 +1,7 @@
1
1
  import { useChit, useChits } from "../hooks/useChits";
2
2
  import { PlayerChit } from "../game/PlayerChit";
3
3
  import { RootChit } from "../game/RootChit";
4
- import { TokenDefinition } from "../components/TokenizedMessage";
4
+ import { buildTokenMap, TokenMap } from "../utilities/TokenizedText";
5
5
  import { useGameTheme } from "./useGameTheme";
6
6
  import { useGame } from "./useGame";
7
7
 
@@ -11,10 +11,6 @@ export function useTokenMap() {
11
11
  const root = useChit<RootChit<PlayerChit>>("root");
12
12
  const playerChits = useChits<PlayerChit>(root?.players.map((p) => p.id ?? "") ?? []);
13
13
 
14
- const tokenMap: { [key: string]: TokenDefinition } = { ...(game.tokenMap ?? {}) };
15
- playerChits?.forEach((p) => {
16
- tokenMap[p.playerId] = { label: p.name ?? "??", color: p.color ?? theme.actionLogTextColor, image: p.imageUrl };
17
- });
18
- tokenMap["warning"] = { label: "⚠️" };
14
+ const tokenMap: TokenMap = buildTokenMap(game.tokenMap, playerChits ?? [], theme.actionLogTextColor);
19
15
  return tokenMap;
20
16
  }
@@ -51,11 +51,8 @@ class WebGLRendererWrapper {
51
51
  const gl = this.renderer.getContext();
52
52
  this.memoryExtension = gl.getExtension("WEBGL_debug_renderer_info");
53
53
  this.loseContextExt = gl.getExtension("WEBGL_lose_context");
54
- this.isWebGL2 =
55
- typeof WebGL2RenderingContext !== "undefined" &&
56
- gl instanceof WebGL2RenderingContext;
54
+ this.isWebGL2 = typeof WebGL2RenderingContext !== "undefined" && gl instanceof WebGL2RenderingContext;
57
55
 
58
- this.renderer.setPixelRatio(this.pixelRatio);
59
56
  this.renderer.shadowMap.enabled = true;
60
57
  this.renderer.setClearColor(0xffffff, 1.0);
61
58
 
@@ -115,7 +112,6 @@ class WebGLRendererWrapper {
115
112
  this._restoreScheduled = false;
116
113
 
117
114
  // Re-apply renderer state
118
- this.renderer.setPixelRatio(this.pixelRatio);
119
115
  this.renderer.shadowMap.enabled = true;
120
116
  this.renderer.setClearColor(0xffffff, 1.0);
121
117
  this.renderer.setScissorTest(true);
@@ -186,6 +182,10 @@ class WebGLRendererWrapper {
186
182
  return this._contextLost;
187
183
  }
188
184
 
185
+ get maxAnisotropy(): number {
186
+ return this.renderer.capabilities.getMaxAnisotropy();
187
+ }
188
+
189
189
  onDirty(cb: () => void): () => void {
190
190
  this._dirtyCallbacks.add(cb);
191
191
  return () => this._dirtyCallbacks.delete(cb);
@@ -222,7 +222,9 @@ class WebGLRendererWrapper {
222
222
 
223
223
  const composer = new EffectComposer(this.renderer, width, height);
224
224
  const renderPass = new RenderPass();
225
- const outlinePass = new IDBasedOutlinePass(new Vector2(width, height), this.pixelRatio);
225
+ // width/height are already physical pixels; pixelRatio=1 so the pass
226
+ // doesn't scale them again when creating its internal render targets.
227
+ const outlinePass = new IDBasedOutlinePass(new Vector2(width, height), 1);
226
228
  const outputPass = new OutputPass();
227
229
 
228
230
  // Configure transparency
@@ -319,12 +321,27 @@ class WebGLRendererWrapper {
319
321
  }
320
322
  }
321
323
 
322
- render(sceneWrapper: SceneWrapper, camera: Camera, context2d: CanvasRenderingContext2D, theme: GameTheme, viewerId?: string): boolean {
324
+ render(
325
+ sceneWrapper: SceneWrapper,
326
+ camera: Camera,
327
+ context2d: CanvasRenderingContext2D,
328
+ theme: GameTheme,
329
+ viewerId?: string,
330
+ ): boolean {
323
331
  if (this._contextLost) {
324
- // Still lost — keep trying to restore. The previous attempt may have used
325
- // the setSize fallback that doesn't always trigger `webglcontextrestored`.
326
- this.maybeScheduleRestore();
327
- return false;
332
+ // On some mobile browsers (Android Chrome, iOS Safari) the context may be
333
+ // silently restored after a screen lock without firing `webglcontextrestored`.
334
+ // Detect this by checking the actual GL state instead of relying on the event.
335
+ const glCheck = this.renderer.getContext();
336
+ if (glCheck && !glCheck.isContextLost()) {
337
+ this.handleContextRestored();
338
+ // fall through to render
339
+ } else {
340
+ // Still lost — keep trying to restore. The previous attempt may have used
341
+ // the setSize fallback that doesn't always trigger `webglcontextrestored`.
342
+ this.maybeScheduleRestore();
343
+ return false;
344
+ }
328
345
  }
329
346
 
330
347
  // Detect silent context loss — on some Android WebViews the `webglcontextlost`
@@ -337,11 +354,11 @@ class WebGLRendererWrapper {
337
354
  return false;
338
355
  }
339
356
 
357
+ // Use physical pixel dimensions directly — Viewer.tsx is responsible for
358
+ // passing a canvas sized at the correct physical resolution.
340
359
  const canvas = context2d.canvas;
341
- const width = Math.floor(canvas.width / this.pixelRatio);
342
- const height = Math.floor(canvas.height / this.pixelRatio);
343
- const targetWidth = Math.ceil(width * this.pixelRatio);
344
- const targetHeight = Math.ceil(height * this.pixelRatio);
360
+ const width = canvas.width;
361
+ const height = canvas.height;
345
362
 
346
363
  // Ensure renderer can accommodate this size
347
364
  this.ensureRendererSize(width, height, viewerId);
@@ -353,8 +370,8 @@ class WebGLRendererWrapper {
353
370
  entry.referenceCount++;
354
371
 
355
372
  try {
356
- // Set scissor to render only to target region
357
- this.renderer.setScissor(0, 0, targetWidth, targetHeight);
373
+ // Set scissor and viewport in physical pixels (pixelRatio=1 on the renderer).
374
+ this.renderer.setScissor(0, 0, width, height);
358
375
  this.renderer.setViewport(0, 0, width, height);
359
376
 
360
377
  // Clear *depth only* in this panel's scissor region before composer.render().
@@ -383,18 +400,21 @@ class WebGLRendererWrapper {
383
400
  return false;
384
401
  }
385
402
 
386
- // Copy the rendered result to the 2D canvas
403
+ // Copy the rendered result to the 2D canvas.
404
+ // WebGL origin is bottom-left; canvas/DOM is top-left. When the renderer
405
+ // is larger than this viewer (multi-viewer sharing), the rendered region
406
+ // sits at the bottom of the WebGL canvas, so offset by the difference.
387
407
  const webglCanvas = this.renderer.domElement;
388
408
  context2d.drawImage(
389
409
  webglCanvas,
390
410
  0,
391
- webglCanvas.height - targetHeight, // Invert Y axis
392
- targetWidth,
393
- targetHeight, // Source width, height
411
+ webglCanvas.height - height, // Y-flip for bottom-left WebGL origin
412
+ width,
413
+ height,
414
+ 0,
394
415
  0,
395
- 0, // Dest x, y
396
- targetWidth,
397
- targetHeight, // Dest width, height
416
+ width,
417
+ height,
398
418
  );
399
419
  return true;
400
420
  } finally {