@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
@@ -21,6 +21,11 @@ import {
21
21
  InputLabel,
22
22
  IconButton,
23
23
  Tooltip,
24
+ Checkbox,
25
+ FormControlLabel,
26
+ FormGroup,
27
+ FormLabel,
28
+ Typography,
24
29
  } from "@mui/material";
25
30
  import { Add, Delete, Refresh, GridOn, PhoneIphone, Tab as TabIcon, Upload, Download, LinkOff } from "@mui/icons-material";
26
31
  import useLocalStorageState from "use-local-storage-state";
@@ -51,6 +56,8 @@ interface SavedMatchInfo {
51
56
  playerCount: number;
52
57
  matchOptions: any;
53
58
  createdAt: number;
59
+ /** Seat indexes played by AI */
60
+ aiSeats?: number[];
54
61
  }
55
62
 
56
63
  // Helper functions for match storage
@@ -119,7 +126,7 @@ function NewMatchDialog({
119
126
  }: {
120
127
  open: boolean;
121
128
  onClose: () => void;
122
- onCreate: (name: string, playerCount: number, matchOptions: any) => void;
129
+ onCreate: (name: string, playerCount: number, matchOptions: any, aiSeats: number[]) => void;
123
130
  configOptions: SelectablePropertyInfo[];
124
131
  minPlayers: number;
125
132
  maxPlayers: number;
@@ -129,17 +136,24 @@ function NewMatchDialog({
129
136
  const [name, setName] = useState(`Match ${Date.now()}`);
130
137
  const [playerCount, setPlayerCount] = useState(defaultPlayerCount);
131
138
  const [matchOptions, setMatchOptions] = useState<any>({ ...defaultMatchOptions });
139
+ const [aiSeats, setAiSeats] = useState<number[]>([]);
132
140
 
133
141
  useEffect(() => {
134
142
  if (open) {
135
143
  setName(`Match ${new Date().toLocaleString()}`);
136
144
  setPlayerCount(defaultPlayerCount);
137
145
  setMatchOptions({ ...defaultMatchOptions });
146
+ setAiSeats([]);
138
147
  }
139
148
  }, [open, defaultPlayerCount, defaultMatchOptions]);
140
149
 
141
150
  const handleCreate = () => {
142
- onCreate(name, playerCount, matchOptions);
151
+ onCreate(
152
+ name,
153
+ playerCount,
154
+ matchOptions,
155
+ aiSeats.filter((seat) => seat < playerCount),
156
+ );
143
157
  onClose();
144
158
  };
145
159
 
@@ -174,6 +188,27 @@ function NewMatchDialog({
174
188
  ))}
175
189
  </Select>
176
190
  </FormControl>
191
+ <FormControl component="fieldset">
192
+ <FormLabel component="legend">AI players</FormLabel>
193
+ <FormGroup row>
194
+ {[...new Array(playerCount)].map((_, seat) => (
195
+ <FormControlLabel
196
+ key={seat}
197
+ label={generatePlayerName(seat)}
198
+ control={
199
+ <Checkbox
200
+ checked={aiSeats.includes(seat)}
201
+ onChange={(e) =>
202
+ setAiSeats((prev) =>
203
+ e.target.checked ? [...prev, seat] : prev.filter((s) => s !== seat),
204
+ )
205
+ }
206
+ />
207
+ }
208
+ />
209
+ ))}
210
+ </FormGroup>
211
+ </FormControl>
177
212
  {configOptions.map((option) => (
178
213
  <FormControl key={option.fieldName} fullWidth>
179
214
  <InputLabel>{option.config.label}</InputLabel>
@@ -477,9 +512,26 @@ function PlayerEditor({
477
512
  );
478
513
  }
479
514
 
515
+ /** Seats a person plays in the Playground. AI seats play themselves, so they get no view. */
516
+ function humanSeats(match: Match<any, any>) {
517
+ return match.players.filter((p) => !p.ai);
518
+ }
519
+
520
+ function NoHumanSeats() {
521
+ return (
522
+ <Box sx={{ p: 2 }}>
523
+ <Typography>Every seat in this match is played by AI, so there is nothing to show.</Typography>
524
+ </Box>
525
+ );
526
+ }
527
+
480
528
  function MatchGrid({ match, disconnectSignal }: { match: Match<any, any>; disconnectSignal: number }) {
481
- let rows = Math.ceil(Math.sqrt(match.players.length));
482
- let columns = Math.ceil(match.players.length / rows);
529
+ const seats = humanSeats(match);
530
+ if (seats.length === 0) {
531
+ return <NoHumanSeats />;
532
+ }
533
+ let rows = Math.ceil(Math.sqrt(seats.length));
534
+ let columns = Math.ceil(seats.length / rows);
483
535
 
484
536
  if (rows > columns) {
485
537
  const t = rows;
@@ -487,7 +539,7 @@ function MatchGrid({ match, disconnectSignal }: { match: Match<any, any>; discon
487
539
  columns = t;
488
540
  }
489
541
 
490
- const playerRows = match.players.reduce((acc: PlayerInfo[][], player, i) => {
542
+ const playerRows = seats.reduce((acc: PlayerInfo[][], player, i) => {
491
543
  const rowIndex = Math.floor(i / columns);
492
544
  acc[rowIndex] ??= [];
493
545
  acc[rowIndex].push(player);
@@ -512,7 +564,11 @@ function MatchTabs({ match, disconnectSignal }: { match: Match<any, any>; discon
512
564
  const [tabIndex, setTabIndex] = useLocalStorageState("selectedPlayerIndex", {
513
565
  defaultValue: 0,
514
566
  });
515
- if (tabIndex >= match.players.length && tabIndex > 0) {
567
+ const seats = humanSeats(match);
568
+ if (seats.length === 0) {
569
+ return <NoHumanSeats />;
570
+ }
571
+ if (tabIndex >= seats.length && tabIndex > 0) {
516
572
  setTabIndex(0);
517
573
  return null;
518
574
  }
@@ -526,12 +582,12 @@ function MatchTabs({ match, disconnectSignal }: { match: Match<any, any>; discon
526
582
  textColor="inherit"
527
583
  variant="fullWidth"
528
584
  >
529
- {match.players.map((p) => (
585
+ {seats.map((p) => (
530
586
  <Tab label={p.name} key={p.id} />
531
587
  ))}
532
588
  </Tabs>
533
589
  <Box flex={1} sx={{ height: "100%" }}>
534
- {[match.players[tabIndex].id].map((id) => (
590
+ {[seats[tabIndex].id].map((id) => (
535
591
  <PlayerEditor key={id} playerId={id} match={match} disconnectSignal={disconnectSignal} />
536
592
  ))}
537
593
  </Box>
@@ -540,10 +596,14 @@ function MatchTabs({ match, disconnectSignal }: { match: Match<any, any>; discon
540
596
  }
541
597
 
542
598
  function MatchPhone({ match, disconnectSignal }: { match: Match<any, any>; disconnectSignal: number }) {
599
+ const seats = humanSeats(match);
600
+ if (seats.length === 0) {
601
+ return <NoHumanSeats />;
602
+ }
543
603
  return (
544
604
  <Box sx={{ height: "100%", width: "100%", overflow: "scroll" }}>
545
- <Stack direction={"row"} sx={{ width: `${390 * match.players.length}px` }}>
546
- {match.players.map((p) => (
605
+ <Stack direction={"row"} sx={{ width: `${390 * seats.length}px` }}>
606
+ {seats.map((p) => (
547
607
  <Box key={p.id} sx={{ width: `390px`, height: "684px" }}>
548
608
  <PlayerEditor showBack playerId={p.id} match={match} disconnectSignal={disconnectSignal} />
549
609
  </Box>
@@ -575,7 +635,10 @@ function Editor({
575
635
 
576
636
  const players: PlayerInfo[] = [];
577
637
  for (let i = 0; i < matchInfo.playerCount; i++) {
578
- players.push(new PlayerInfo(`p${i}`, generatePlayerName(i)));
638
+ const isAi = matchInfo.aiSeats?.includes(i);
639
+ const player = new PlayerInfo(`p${i}`, isAi ? `${generatePlayerName(i)} (AI)` : generatePlayerName(i));
640
+ player.ai = isAi ? {} : undefined;
641
+ players.push(player);
579
642
  }
580
643
 
581
644
  const newMatch = new Match(game, players, newStorage, matchInfo.matchOptions);
@@ -585,6 +648,7 @@ function Editor({
585
648
  if (cancelled) {
586
649
  return;
587
650
  }
651
+ newMatch.seatAiPlayers({ thinkMs: [400, 900] });
588
652
  newMatch.start();
589
653
  setMatch(newMatch);
590
654
  });
@@ -693,7 +757,7 @@ export default function Playground({ game }: { game: Game<any, any> }) {
693
757
  });
694
758
  }, [loadingStates]);
695
759
 
696
- const handleCreateMatch = (name: string, playerCount: number, matchOptions: any) => {
760
+ const handleCreateMatch = (name: string, playerCount: number, matchOptions: any, aiSeats: number[]) => {
697
761
  const matchId = generateMatchId();
698
762
  const newMatchInfo: SavedMatchInfo = {
699
763
  matchId,
@@ -701,6 +765,7 @@ export default function Playground({ game }: { game: Game<any, any> }) {
701
765
  playerCount,
702
766
  matchOptions,
703
767
  createdAt: Date.now(),
768
+ aiSeats,
704
769
  };
705
770
  saveMatchMeta(gameName, newMatchInfo);
706
771
  const matchIds = loadMatchList(gameName);
@@ -4,12 +4,9 @@ import Color from "color";
4
4
  import { ImageSpec } from "../utilities/CanvasStack/CanvasOperations";
5
5
  import { UpdatingCanvasImage } from "./UpdatingCanvasImage";
6
6
  import { StaticImage } from "../utilities/StaticImage";
7
+ import { TokenDefinition, parseMessageTokens } from "../utilities/TokenizedText";
7
8
 
8
- export interface TokenDefinition {
9
- image?: string | ImageSpec;
10
- label?: string;
11
- color?: string;
12
- }
9
+ export type { TokenDefinition } from "../utilities/TokenizedText";
13
10
 
14
11
  export interface TokenizedMessageProps {
15
12
  message: string;
@@ -17,22 +14,6 @@ export interface TokenizedMessageProps {
17
14
  tokenMap?: Record<string, TokenDefinition>;
18
15
  }
19
16
 
20
- // Token parsing types
21
- interface ParsedToken {
22
- type: "token";
23
- name: string;
24
- definition?: TokenDefinition;
25
- key: string;
26
- }
27
-
28
- interface ParsedText {
29
- type: "text";
30
- content: string;
31
- key: string;
32
- }
33
-
34
- type ParsedElement = ParsedToken | ParsedText;
35
-
36
17
  // Color utility function
37
18
  function calculateBackgroundColor(textColor: string): string {
38
19
  const color = Color(textColor);
@@ -141,48 +122,6 @@ function Token({ name, definition, fontSize }: TokenProps) {
141
122
  );
142
123
  }
143
124
 
144
- // Parser function
145
- function parseMessageTokens(message: string, tokenMap: Record<string, TokenDefinition>): ParsedElement[] {
146
- const elements: ParsedElement[] = [];
147
- const tokenRegex = /:([a-zA-Z0-9_-]+):/g;
148
- let lastIndex = 0;
149
- let match;
150
-
151
- while ((match = tokenRegex.exec(message)) !== null) {
152
- const tokenName = match[1];
153
-
154
- // Add text before the token
155
- if (match.index > lastIndex) {
156
- elements.push({
157
- type: "text",
158
- content: message.substring(lastIndex, match.index),
159
- key: `text-${lastIndex}`,
160
- });
161
- }
162
-
163
- // Add the token
164
- elements.push({
165
- type: "token",
166
- name: tokenName,
167
- definition: tokenMap[tokenName],
168
- key: `token-${match.index}`,
169
- });
170
-
171
- lastIndex = match.index + match[0].length;
172
- }
173
-
174
- // Add remaining text after last token
175
- if (lastIndex < message.length) {
176
- elements.push({
177
- type: "text",
178
- content: message.substring(lastIndex),
179
- key: `text-${lastIndex}`,
180
- });
181
- }
182
-
183
- return elements;
184
- }
185
-
186
125
  // Main Component
187
126
  export function TokenizedMessage({ message, fontSize, tokenMap = {} }: TokenizedMessageProps) {
188
127
  const elements = parseMessageTokens(message, tokenMap);
@@ -117,7 +117,12 @@ function PlayerInfoRow({ headers, player }: { player: PlayerChit; headers?: bool
117
117
  <PlayerInfoCell size={size} key={spark.id} spark={spark} />
118
118
  ))}
119
119
  <TextPlayerInfoCell size={size} width={NAME_WIDTH} text={player.name} />
120
- <TextPlayerInfoCell size={size} width={PROMPT_WIDTH} text={player.promptStatus.latestPromptMessage ?? ""} />
120
+ {/* This cell is single-line, ellipsized text, so use the plain-text prompt (player tokens become names). */}
121
+ <TextPlayerInfoCell
122
+ size={size}
123
+ width={PROMPT_WIDTH}
124
+ text={player.promptStatus.latestPromptMessageText ?? player.promptStatus.latestPromptMessage ?? ""}
125
+ />
121
126
  </Stack>
122
127
  );
123
128
  }
@@ -640,14 +640,14 @@ export class Chit extends ObjectWithProps {
640
640
  if (rule) {
641
641
  if (rule.fields === "all") {
642
642
  Object.keys(data)
643
- .filter((a) => a !== "id" && !a.startsWith("_") && !data[a].___orderedOutlet)
643
+ .filter((a) => a !== "id" && !a.startsWith("_") && !data[a]?.___orderedOutlet)
644
644
  .forEach((key) => {
645
645
  delete data[key];
646
646
  });
647
647
  } else {
648
648
  rule.fields
649
649
  .filter((k) => {
650
- if (data[k].___orderedOutlet) {
650
+ if (data[k]?.___orderedOutlet) {
651
651
  throw new Error("Cannot mask ordered outlets");
652
652
  }
653
653
  return true;
@@ -10,6 +10,9 @@ export interface ConnectionTransport {
10
10
  const LOCAL_LATENCY_SIMULATION = 50;
11
11
 
12
12
  export class LocalConnectionTransport implements ConnectionTransport {
13
+ /** @param latencyMs Max simulated latency per message (each message waits a random 0..latencyMs) */
14
+ constructor(private latencyMs: number = LOCAL_LATENCY_SIMULATION) {}
15
+
13
16
  disposed = false;
14
17
  public connected = new EventChannel(false);
15
18
  private cbs: ((message: any) => void)[] = [];
@@ -46,7 +49,13 @@ export class LocalConnectionTransport implements ConnectionTransport {
46
49
  this.connectedTransport.cbs.forEach((cb) => cb(copied));
47
50
  }
48
51
  });
49
- setTimeout(() => this.processMessageOnQueue(), Math.random() * LOCAL_LATENCY_SIMULATION);
52
+ if (this.latencyMs <= 0 && typeof setImmediate === "function") {
53
+ // No simulated latency (in-process bots, simulations): a timer of 0 still waits ≥1 ms per
54
+ // message in Node, which dominated headless games. setImmediate keeps the queue's order.
55
+ setImmediate(() => this.processMessageOnQueue());
56
+ } else {
57
+ setTimeout(() => this.processMessageOnQueue(), Math.random() * this.latencyMs);
58
+ }
50
59
  }
51
60
 
52
61
  processMessageOnQueue() {
@@ -66,8 +75,8 @@ export class LocalConnectionTransport implements ConnectionTransport {
66
75
 
67
76
  setTimeout(() => {
68
77
  // Create fresh transport pair
69
- const newClient = new LocalConnectionTransport();
70
- const newServer = new LocalConnectionTransport();
78
+ const newClient = new LocalConnectionTransport(this.latencyMs);
79
+ const newServer = new LocalConnectionTransport(this.latencyMs);
71
80
  newClient.connect(newServer);
72
81
 
73
82
  // Notify client listeners with new client transport
@@ -6,8 +6,9 @@ import { GameButton } from "./GameButton";
6
6
  import { PlayerChit } from "./PlayerChit";
7
7
  import { RootChit } from "./RootChit";
8
8
  import { ChitRenderSpec } from "../rendering/ChitRenderSpec";
9
- import { TokenDefinition } from "../components/TokenizedMessage";
9
+ import { TokenDefinition } from "../utilities/TokenizedText";
10
10
  import { GameMetaData } from "./GameMetaData";
11
+ import type { GameAi } from "./ai/defineAi";
11
12
 
12
13
  export interface IChitLibrary<P extends PlayerChit, R extends RootChit<P>> {
13
14
  [key: string]: new () => Chit;
@@ -61,4 +62,11 @@ export interface Game<P extends PlayerChit, R extends RootChit<P>> {
61
62
  * @param pick the pick we are looking at
62
63
  */
63
64
  demoPickWeight?(picks: any[], pick: any): number;
65
+
66
+ /**
67
+ * Optional rules for AI players (see `defineAi`). Tag picks with `.ai(key)` and add a rule
68
+ * per key; AI players then score every legal option using only what their seat can see, and
69
+ * pick the best. Without this, AI players pick at random (weighted by `demoPickWeight`).
70
+ */
71
+ ai?: GameAi<P, R, any>;
64
72
  }
@@ -4,7 +4,7 @@ import { ConnectionTransport } from "./ConnectionTransport";
4
4
  import { Game, GameResult } from "./Game";
5
5
  import { ServerTime } from "./serverTransport/ServerTime";
6
6
  import { PlayerInfo } from "./PlayerInfo";
7
- import { MismatchError, RerunError, Turn } from "./Turn";
7
+ import { DestroyError, MismatchError, RerunError, Turn } from "./Turn";
8
8
  import { TurnState } from "./TurnState";
9
9
  import { IMatchStorage } from "./MatchStorage";
10
10
  import { ServerPrompts } from "./serverTransport/ServerPrompts";
@@ -12,13 +12,79 @@ import { EventChannel } from "../utilities/EventChannel";
12
12
  import { RootChit } from "./RootChit";
13
13
  import { ServerStatus } from "./serverTransport/ServerStatus";
14
14
  import { PlayerChit } from "./PlayerChit";
15
+ import { AiPlayerHandle, ConnectAiPlayerOptions, connectAiPlayer } from "./ai/connectAiPlayer";
16
+ import type { AiMemoryStore } from "./ai/AiClientPrompts";
17
+
18
+ /** Options for {@link Match.seatAiPlayers}: applied to every bot it seats. */
19
+ export type SeatAiPlayersOptions = Omit<ConnectAiPlayerOptions, "difficulty" | "params" | "choose" | "memoryStore">;
20
+
21
+ /**
22
+ * The bots attached to a match, however they were seated ({@link Match.seatAiPlayers} or
23
+ * `connectAiPlayer`), and the one switch a host needs over them.
24
+ *
25
+ * @group AI
26
+ */
27
+ export class MatchAiControls {
28
+ private _enabled = true;
29
+ private _handles: AiPlayerHandle[] = [];
30
+
31
+ /** Every bot currently attached, in seating order */
32
+ get handles(): readonly AiPlayerHandle[] {
33
+ return this._handles;
34
+ }
35
+
36
+ /** Ids of the seats that have a bot */
37
+ get seatedPlayerIds(): string[] {
38
+ return this._handles.map((h) => h.playerId);
39
+ }
40
+
41
+ /** True when no bot is in the middle of answering a prompt (safe to tear the match down) */
42
+ get idle(): boolean {
43
+ return this._handles.every((h) => h.prompts.idle);
44
+ }
45
+
46
+ /**
47
+ * Whether the bots answer prompts. Default true. Set it false on every copy of a match but one
48
+ * when several copies run at once (each browser tab in client-trust mode, or two bundle versions
49
+ * of a match on a server), otherwise each copy answers the same prompt. Bots keep their memory
50
+ * while paused and answer the pending prompt when resumed. Applies to bots seated later too.
51
+ */
52
+ get enabled(): boolean {
53
+ return this._enabled;
54
+ }
55
+ set enabled(enabled: boolean) {
56
+ this._enabled = enabled;
57
+ this._handles.forEach((h) => h.prompts.setEnabled(enabled));
58
+ }
59
+
60
+ /** @internal */
61
+ register(handle: AiPlayerHandle) {
62
+ this._handles.push(handle);
63
+ }
64
+
65
+ /** @internal */
66
+ unregister(handle: AiPlayerHandle) {
67
+ this._handles = this._handles.filter((h) => h !== handle);
68
+ }
69
+
70
+ /** @internal */
71
+ disposeAll() {
72
+ [...this._handles].forEach((h) => h.dispose());
73
+ this._handles = [];
74
+ }
75
+ }
15
76
 
16
77
  export class Match<P extends PlayerChit, R extends RootChit<P>> {
17
78
  public state: TurnState = new TurnState();
18
79
  public result = new EventChannel<undefined | GameResult<P>>(undefined);
19
80
  public turn = new EventChannel<undefined | Turn<GameResult<P>, P, R>>(undefined);
20
81
  public errorState = new EventChannel<undefined | string>(undefined);
82
+ /** The AI players attached to this match and the switch that pauses them. See {@link seatAiPlayers}. */
83
+ public readonly ai = new MatchAiControls();
21
84
  private onChangeCallbacks: (() => void)[] = [];
85
+ private connections: Connection[] = [];
86
+ private unsubscribeStorage?: () => void;
87
+ private disposed = false;
22
88
 
23
89
  constructor(
24
90
  public game: Game<P, R>,
@@ -32,7 +98,10 @@ export class Match<P extends PlayerChit, R extends RootChit<P>> {
32
98
  if (savedState !== null) {
33
99
  this.state.deserialize(savedState);
34
100
  }
35
- this.matchStorage.registerNewStateCallback((savedState) => {
101
+ this.unsubscribeStorage = this.matchStorage.registerNewStateCallback((savedState) => {
102
+ if (this.disposed) {
103
+ return;
104
+ }
36
105
  this.state = new TurnState();
37
106
  this.state.deserialize(savedState);
38
107
  if (this.errorState.value) {
@@ -121,6 +190,11 @@ export class Match<P extends PlayerChit, R extends RootChit<P>> {
121
190
  return;
122
191
  }
123
192
 
193
+ if (e instanceof DestroyError || this.disposed) {
194
+ // The turn was torn down on purpose (dispose, or a reload replacing it): not an error
195
+ return;
196
+ }
197
+
124
198
  throw e;
125
199
  }
126
200
  }
@@ -133,11 +207,77 @@ export class Match<P extends PlayerChit, R extends RootChit<P>> {
133
207
  connection.register(new ServerTime(this, playerId, connection));
134
208
  connection.register(new ServerPrompts(playerId, this, connection));
135
209
  connection.register(new ServerStatus(this, connection));
210
+ this.connections.push(connection);
136
211
  return connection;
137
212
  }
138
213
 
214
+ /**
215
+ * Seats an engine AI in every seat whose `PlayerInfo.ai` is set and that has no bot yet, and
216
+ * returns the handles of the bots it created. Call it after `load()` and before (or after)
217
+ * `start()`. Hosts opt in by calling it; the `ai` flag on its own does nothing, so a harness that
218
+ * seats its own bots with `connectAiPlayer` is never doubled up. Seats already taken by a
219
+ * `connectAiPlayer` bot are skipped, so the two can be mixed: hand-seat the bot under test, then
220
+ * call this for the rest.
221
+ *
222
+ * Each bot's `difficulty` comes from its seat's `ai` info; everything else from `options`.
223
+ * Bots follow {@link MatchAiControls.enabled} and are disposed with the match.
224
+ *
225
+ * ```ts
226
+ * const match = new Match(game, players, storage, options);
227
+ * await match.load();
228
+ * match.seatAiPlayers({ thinkMs: [400, 900] });
229
+ * match.start();
230
+ * ```
231
+ *
232
+ * @group AI
233
+ */
234
+ seatAiPlayers(options: SeatAiPlayersOptions = {}): AiPlayerHandle[] {
235
+ const seated = new Set(this.ai.seatedPlayerIds);
236
+ return this.players
237
+ .filter((p) => p.ai && !seated.has(p.id))
238
+ .map((p) => connectAiPlayer(this, p.id, { ...options, difficulty: p.ai?.difficulty }));
239
+ }
240
+
241
+ /**
242
+ * Where a bot in `playerId`'s seat keeps its plan memory: a slot in this match's saved state, so
243
+ * it is persisted by whatever `IMatchStorage` the host supplied and comes back after a reload.
244
+ * `connectAiPlayer` uses this by default.
245
+ * @internal
246
+ */
247
+ aiMemoryStore(playerId: string): AiMemoryStore {
248
+ return {
249
+ read: () => this.state.ai?.[playerId],
250
+ write: (memory) => {
251
+ const ai = (this.state.ai ??= {});
252
+ ai[playerId] = memory;
253
+ },
254
+ };
255
+ }
256
+
257
+ /**
258
+ * Headless runs only (simulations, testbeds): notify once per event-loop pass on setImmediate
259
+ * instead of the 0 ms debounce timer, which waits ≥1 ms per change in Node. Every prompt
260
+ * response waits for the next notification (ServerPrompts.resolvePrompt), so that timer was most
261
+ * of a simulated game's run time. Off by default: servers and browsers keep the debounce.
262
+ */
263
+ public immediateNotify = false;
139
264
  private _timeout?: NodeJS.Timeout | number = undefined;
265
+ private _notifyQueued = false;
140
266
  private notify() {
267
+ if (this.disposed) {
268
+ return;
269
+ }
270
+ if (this.immediateNotify && typeof setImmediate === "function") {
271
+ // Not a re-deferring debounce: with several bots answering every pass it would never fire,
272
+ // and the prompt responses waiting on it would stall.
273
+ if (this._notifyQueued) return;
274
+ this._notifyQueued = true;
275
+ setImmediate(() => {
276
+ this._notifyQueued = false;
277
+ this.processNotify();
278
+ });
279
+ return;
280
+ }
141
281
  clearTimeout(this._timeout);
142
282
  this._timeout = setTimeout(() => this.processNotify(), 0);
143
283
  }
@@ -145,6 +285,9 @@ export class Match<P extends PlayerChit, R extends RootChit<P>> {
145
285
  private _isSaving = false;
146
286
  private _saveStateNeeded = false;
147
287
  private processNotify() {
288
+ if (this.disposed) {
289
+ return;
290
+ }
148
291
  this.onChangeCallbacks.forEach((cb) => cb());
149
292
 
150
293
  // TODO: this is a promise going nowhere... do we block on saving?
@@ -174,8 +317,24 @@ export class Match<P extends PlayerChit, R extends RootChit<P>> {
174
317
  });
175
318
  }
176
319
 
320
+ /**
321
+ * Tears the match down: disposes its bots and every connection made through `connect`, stops
322
+ * listening to storage, and destroys the running turn so no prompt stays pending. Nothing is
323
+ * saved after this. A disposed match cannot be restarted; make a new one.
324
+ */
177
325
  public dispose() {
178
- // TODO: cleanup
326
+ if (this.disposed) {
327
+ return;
328
+ }
329
+ this.disposed = true;
330
+ clearTimeout(this._timeout);
331
+ this.ai.disposeAll();
332
+ this.connections.forEach((c) => c.dispose());
333
+ this.connections = [];
334
+ this.unsubscribeStorage?.();
335
+ this.unsubscribeStorage = undefined;
336
+ this.onChangeCallbacks = [];
337
+ this.turn.value?.destroy();
179
338
  }
180
339
 
181
340
  public onChange(cb: () => void, callNow = true) {
@@ -51,15 +51,25 @@ export class LocalMatchStorage implements IMatchStorage {
51
51
  }
52
52
 
53
53
  export class EphemeralMatchStorage implements IMatchStorage {
54
- constructor(private matchId: string) {}
54
+ /**
55
+ * @param lazy Headless runs only (simulations, testbeds): keep a reference to the saved state and
56
+ * turn it into JSON only when read. Saves get much cheaper (stringifying the whole match on every
57
+ * change cost ~10% of a headless game), but a read returns the match as it is *now*, not as of the
58
+ * last save. Off by default: every save is a snapshot.
59
+ */
60
+ constructor(
61
+ private matchId: string,
62
+ private lazy = false,
63
+ ) {}
55
64
  private onChangeCallbacks: ((state: any) => void)[] = [];
56
65
 
57
- private state: string = "{}";
66
+ private state: any = "{}";
58
67
 
59
68
  async readState(): Promise<any> {
60
69
  const result = this.state;
61
70
  if (result) {
62
- return JSON.parse(result);
71
+ // A string is a snapshot (or the initial empty state); an object is a lazy reference.
72
+ return JSON.parse(typeof result === "string" ? result : JSON.stringify(result));
63
73
  }
64
74
  return null;
65
75
  }
@@ -70,7 +80,7 @@ export class EphemeralMatchStorage implements IMatchStorage {
70
80
  winners?: PlayerChit[],
71
81
  notify = false,
72
82
  ): Promise<void> {
73
- this.state = JSON.stringify(newState);
83
+ this.state = this.lazy ? newState : JSON.stringify(newState);
74
84
  if (notify) {
75
85
  this.notify(newState);
76
86
  }