@pretty-chitty/core 1.2.18 → 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 (139) 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/Playground.d.ts.map +1 -1
  15. package/dist/components/Playground.js +37 -11
  16. package/dist/components/Playground.js.map +1 -1
  17. package/dist/components/TokenizedMessage.d.ts +2 -6
  18. package/dist/components/TokenizedMessage.d.ts.map +1 -1
  19. package/dist/components/TokenizedMessage.js +1 -35
  20. package/dist/components/TokenizedMessage.js.map +1 -1
  21. package/dist/components/TopBarPlayers.d.ts.map +1 -1
  22. package/dist/components/TopBarPlayers.js +1 -1
  23. package/dist/components/TopBarPlayers.js.map +1 -1
  24. package/dist/game/Chit.js +2 -2
  25. package/dist/game/Chit.js.map +1 -1
  26. package/dist/game/ConnectionTransport.d.ts +3 -0
  27. package/dist/game/ConnectionTransport.d.ts.map +1 -1
  28. package/dist/game/ConnectionTransport.js +13 -4
  29. package/dist/game/ConnectionTransport.js.map +1 -1
  30. package/dist/game/Game.d.ts +8 -1
  31. package/dist/game/Game.d.ts.map +1 -1
  32. package/dist/game/Match.d.ts +66 -0
  33. package/dist/game/Match.d.ts.map +1 -1
  34. package/dist/game/Match.js +151 -3
  35. package/dist/game/Match.js.map +1 -1
  36. package/dist/game/MatchStorage.d.ts +8 -1
  37. package/dist/game/MatchStorage.d.ts.map +1 -1
  38. package/dist/game/MatchStorage.js +11 -3
  39. package/dist/game/MatchStorage.js.map +1 -1
  40. package/dist/game/Pick.d.ts +14 -0
  41. package/dist/game/Pick.d.ts.map +1 -1
  42. package/dist/game/Pick.js +15 -0
  43. package/dist/game/Pick.js.map +1 -1
  44. package/dist/game/PlayerChit.d.ts +3 -0
  45. package/dist/game/PlayerChit.d.ts.map +1 -1
  46. package/dist/game/PlayerChit.js +3 -0
  47. package/dist/game/PlayerChit.js.map +1 -1
  48. package/dist/game/PlayerInfo.d.ts +8 -0
  49. package/dist/game/PlayerInfo.d.ts.map +1 -1
  50. package/dist/game/PlayerInfo.js +6 -3
  51. package/dist/game/PlayerInfo.js.map +1 -1
  52. package/dist/game/PlayerPromptStatusChit.d.ts.map +1 -1
  53. package/dist/game/PlayerPromptStatusChit.js +3 -1
  54. package/dist/game/PlayerPromptStatusChit.js.map +1 -1
  55. package/dist/game/Turn.d.ts +5 -0
  56. package/dist/game/Turn.d.ts.map +1 -1
  57. package/dist/game/Turn.js +18 -7
  58. package/dist/game/Turn.js.map +1 -1
  59. package/dist/game/TurnState.d.ts +8 -0
  60. package/dist/game/TurnState.d.ts.map +1 -1
  61. package/dist/game/TurnState.js +7 -0
  62. package/dist/game/TurnState.js.map +1 -1
  63. package/dist/game/ai/AiClientPrompts.d.ts +160 -0
  64. package/dist/game/ai/AiClientPrompts.d.ts.map +1 -0
  65. package/dist/game/ai/AiClientPrompts.js +525 -0
  66. package/dist/game/ai/AiClientPrompts.js.map +1 -0
  67. package/dist/game/ai/AiLiveView.d.ts +2 -0
  68. package/dist/game/ai/AiLiveView.d.ts.map +1 -0
  69. package/dist/game/ai/AiLiveView.js +48 -0
  70. package/dist/game/ai/AiLiveView.js.map +1 -0
  71. package/dist/game/ai/AiPlayerView.d.ts +2 -0
  72. package/dist/game/ai/AiPlayerView.d.ts.map +1 -0
  73. package/dist/game/ai/AiPlayerView.js +89 -0
  74. package/dist/game/ai/AiPlayerView.js.map +1 -0
  75. package/dist/game/ai/connectAiPlayer.d.ts +43 -0
  76. package/dist/game/ai/connectAiPlayer.d.ts.map +1 -0
  77. package/dist/game/ai/connectAiPlayer.js +58 -0
  78. package/dist/game/ai/connectAiPlayer.js.map +1 -0
  79. package/dist/game/ai/defineAi.d.ts +119 -0
  80. package/dist/game/ai/defineAi.d.ts.map +1 -0
  81. package/dist/game/ai/defineAi.js +122 -0
  82. package/dist/game/ai/defineAi.js.map +1 -0
  83. package/dist/game/ai/simulateMatches.d.ts +62 -0
  84. package/dist/game/ai/simulateMatches.d.ts.map +1 -0
  85. package/dist/game/ai/simulateMatches.js +108 -0
  86. package/dist/game/ai/simulateMatches.js.map +1 -0
  87. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts +3 -0
  88. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts.map +1 -1
  89. package/dist/game/badAiTransport/BadAIClientPrompts.js +3 -0
  90. package/dist/game/badAiTransport/BadAIClientPrompts.js.map +1 -1
  91. package/dist/hooks/useTokenMap.d.ts +2 -4
  92. package/dist/hooks/useTokenMap.d.ts.map +1 -1
  93. package/dist/hooks/useTokenMap.js +2 -5
  94. package/dist/hooks/useTokenMap.js.map +1 -1
  95. package/dist/index.d.ts +21 -1
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +8 -1
  98. package/dist/index.js.map +1 -1
  99. package/dist/utilities/CanvasStack/CanvasStack.d.ts +11 -0
  100. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  101. package/dist/utilities/CanvasStack/CanvasStack.js +62 -15
  102. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  103. package/dist/utilities/TokenizedText.d.ts +49 -0
  104. package/dist/utilities/TokenizedText.d.ts.map +1 -0
  105. package/dist/utilities/TokenizedText.js +47 -0
  106. package/dist/utilities/TokenizedText.js.map +1 -0
  107. package/package.json +1 -1
  108. package/src/library/components/ClientTrustMatchViewer.tsx +32 -2
  109. package/src/library/components/DemoWrapper.tsx +4 -12
  110. package/src/library/components/Gallery/BuiltItem.ts +4 -0
  111. package/src/library/components/Gallery/GalleryController.ts +3 -1
  112. package/src/library/components/Playground.tsx +77 -12
  113. package/src/library/components/TokenizedMessage.tsx +2 -63
  114. package/src/library/components/TopBarPlayers.tsx +6 -1
  115. package/src/library/game/Chit.ts +2 -2
  116. package/src/library/game/ConnectionTransport.ts +12 -3
  117. package/src/library/game/Game.ts +9 -1
  118. package/src/library/game/Match.ts +162 -3
  119. package/src/library/game/MatchStorage.ts +14 -4
  120. package/src/library/game/Pick.ts +20 -0
  121. package/src/library/game/PlayerChit.ts +4 -1
  122. package/src/library/game/PlayerInfo.ts +13 -3
  123. package/src/library/game/PlayerPromptStatusChit.ts +3 -1
  124. package/src/library/game/Turn.ts +19 -7
  125. package/src/library/game/TurnState.ts +8 -0
  126. package/src/library/game/ai/AI_GUIDE.md +434 -0
  127. package/src/library/game/ai/AiClientPrompts.ts +681 -0
  128. package/src/library/game/ai/AiLiveView.ts +63 -0
  129. package/src/library/game/ai/AiPlayerView.ts +112 -0
  130. package/src/library/game/ai/ai.test.ts +475 -0
  131. package/src/library/game/ai/connectAiPlayer.ts +88 -0
  132. package/src/library/game/ai/defineAi.ts +230 -0
  133. package/src/library/game/ai/simulateMatches.ts +172 -0
  134. package/src/library/game/badAiTransport/BadAIClientPrompts.ts +3 -0
  135. package/src/library/hooks/useTokenMap.ts +2 -6
  136. package/src/library/index.ts +34 -2
  137. package/src/library/utilities/CanvasStack/CanvasStack.ts +68 -28
  138. package/src/library/utilities/TokenizedText.test.ts +32 -0
  139. 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
  }
@@ -11,6 +11,8 @@ export { Chit } from "./game/Chit";
11
11
  export { Turn } from "./game/Turn";
12
12
  /** @group Core Game Elements */
13
13
  export { Pick, ButtonPick, ChitPick, DragTarget, DragPick } from "./game/Pick";
14
+ /** @group Supporting Types */
15
+ export type { PickAiTag } from "./game/Pick";
14
16
  /** @group Core Game Elements */
15
17
  export { GameTheme } from "./game/GameTheme";
16
18
  /** @group Chits */
@@ -35,6 +37,31 @@ export { ChildOutlet, NonEditable, Ordered, Selectable } from "./utilities/Annot
35
37
  /** @group Chit Annotations */
36
38
  export type { SelectableChoice, SelectableConfig, SelectablePropertyInfo } from "./utilities/Annotations";
37
39
 
40
+ /** @group AI */
41
+ export { defineAi } from "./game/ai/defineAi";
42
+ /** @group AI */
43
+ export type {
44
+ GameAi,
45
+ AiRule,
46
+ AiScore,
47
+ AiContext,
48
+ AiOption,
49
+ AiChitOption,
50
+ AiDragOption,
51
+ AiButtonOption,
52
+ AiPickInfo,
53
+ } from "./game/ai/defineAi";
54
+ /** @group AI */
55
+ export { connectAiPlayer } from "./game/ai/connectAiPlayer";
56
+ /** @group AI */
57
+ export type { ConnectAiPlayerOptions, AiPlayerHandle } from "./game/ai/connectAiPlayer";
58
+ /** @group AI */
59
+ export type { AiPlayerOptions, AiPlayerStats, AiDecision, AiMemoryStore } from "./game/ai/AiClientPrompts";
60
+ /** @group AI */
61
+ export { simulateMatches } from "./game/ai/simulateMatches";
62
+ /** @group AI */
63
+ export type { SimulateMatchesOptions, SimulatedMatch, SimulationReport } from "./game/ai/simulateMatches";
64
+
38
65
  /** @group Buttons */
39
66
  export { GameButton, DynamicGameButton, ToggleGalleryButton } from "./game/GameButton";
40
67
 
@@ -42,6 +69,9 @@ export { GameButton, DynamicGameButton, ToggleGalleryButton } from "./game/GameB
42
69
  export { ParameterizedCanvas } from "./utilities/ParameterizedCanvas";
43
70
  /** @group 2D Rendering */
44
71
  export { StaticImage } from "./utilities/StaticImage";
72
+
73
+ export { tokenizedMessageToText, buildTokenMap, parseMessageTokens } from "./utilities/TokenizedText";
74
+ export type { TokenDefinition, TokenMap } from "./utilities/TokenizedText";
45
75
  /** @group 2D Rendering */
46
76
  export * as ReactCanvas from "./utilities/CanvasStack/ReactCanvas";
47
77
  /** @group 2D Rendering */
@@ -81,7 +111,7 @@ export type { Stage } from "./game/GameDeckChit";
81
111
  /** @group Supporting Types */
82
112
  export { PlayerInfo } from "./game/PlayerInfo";
83
113
  /** @group Supporting Types */
84
- export type { IPlayerInfo } from "./game/PlayerInfo";
114
+ export type { IPlayerInfo, AiSeatInfo } from "./game/PlayerInfo";
85
115
  /** @internal */
86
116
  /** @group Supporting Types */
87
117
  export { MatchViewer } from "./components/MatchViewer";
@@ -90,7 +120,9 @@ export { MatchViewer } from "./components/MatchViewer";
90
120
  export { DemoWrapper } from "./components/DemoWrapper";
91
121
  /** @internal */
92
122
  /** @group Supporting Types */
93
- export { Match } from "./game/Match";
123
+ export { Match, MatchAiControls } from "./game/Match";
124
+ /** @group AI */
125
+ export type { SeatAiPlayersOptions } from "./game/Match";
94
126
  /** @internal */
95
127
  /** @group Supporting Types */
96
128
  export { Connection } from "./game/Connection";