@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.
- package/dist/components/ClientTrustMatchViewer.d.ts +14 -1
- package/dist/components/ClientTrustMatchViewer.d.ts.map +1 -1
- package/dist/components/ClientTrustMatchViewer.js +25 -2
- package/dist/components/ClientTrustMatchViewer.js.map +1 -1
- package/dist/components/DemoWrapper.d.ts.map +1 -1
- package/dist/components/DemoWrapper.js +4 -11
- package/dist/components/DemoWrapper.js.map +1 -1
- package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
- package/dist/components/Gallery/BuiltItem.js +3 -0
- package/dist/components/Gallery/BuiltItem.js.map +1 -1
- package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
- package/dist/components/Gallery/GalleryController.js +3 -1
- package/dist/components/Gallery/GalleryController.js.map +1 -1
- package/dist/components/PanelSpark.js +1 -1
- package/dist/components/PlayerImage.d.ts.map +1 -1
- package/dist/components/PlayerImage.js +21 -1
- package/dist/components/PlayerImage.js.map +1 -1
- package/dist/components/Playground.d.ts.map +1 -1
- package/dist/components/Playground.js +37 -11
- package/dist/components/Playground.js.map +1 -1
- package/dist/components/TokenizedMessage.d.ts +2 -6
- package/dist/components/TokenizedMessage.d.ts.map +1 -1
- package/dist/components/TokenizedMessage.js +1 -35
- package/dist/components/TokenizedMessage.js.map +1 -1
- package/dist/components/TopBarPlayers.d.ts.map +1 -1
- package/dist/components/TopBarPlayers.js +1 -1
- package/dist/components/TopBarPlayers.js.map +1 -1
- package/dist/game/Chit.js +2 -2
- package/dist/game/Chit.js.map +1 -1
- package/dist/game/ConnectionTransport.d.ts +3 -0
- package/dist/game/ConnectionTransport.d.ts.map +1 -1
- package/dist/game/ConnectionTransport.js +13 -4
- package/dist/game/ConnectionTransport.js.map +1 -1
- package/dist/game/Game.d.ts +8 -1
- package/dist/game/Game.d.ts.map +1 -1
- package/dist/game/Match.d.ts +66 -0
- package/dist/game/Match.d.ts.map +1 -1
- package/dist/game/Match.js +151 -3
- package/dist/game/Match.js.map +1 -1
- package/dist/game/MatchStorage.d.ts +8 -1
- package/dist/game/MatchStorage.d.ts.map +1 -1
- package/dist/game/MatchStorage.js +11 -3
- package/dist/game/MatchStorage.js.map +1 -1
- package/dist/game/Pick.d.ts +14 -0
- package/dist/game/Pick.d.ts.map +1 -1
- package/dist/game/Pick.js +15 -0
- package/dist/game/Pick.js.map +1 -1
- package/dist/game/PlayerChit.d.ts +4 -0
- package/dist/game/PlayerChit.d.ts.map +1 -1
- package/dist/game/PlayerChit.js +8 -2
- package/dist/game/PlayerChit.js.map +1 -1
- package/dist/game/PlayerInfo.d.ts +8 -0
- package/dist/game/PlayerInfo.d.ts.map +1 -1
- package/dist/game/PlayerInfo.js +6 -3
- package/dist/game/PlayerInfo.js.map +1 -1
- package/dist/game/PlayerPromptStatusChit.d.ts.map +1 -1
- package/dist/game/PlayerPromptStatusChit.js +3 -1
- package/dist/game/PlayerPromptStatusChit.js.map +1 -1
- package/dist/game/Turn.d.ts +11 -2
- package/dist/game/Turn.d.ts.map +1 -1
- package/dist/game/Turn.js +118 -68
- package/dist/game/Turn.js.map +1 -1
- package/dist/game/TurnState.d.ts +8 -0
- package/dist/game/TurnState.d.ts.map +1 -1
- package/dist/game/TurnState.js +7 -0
- package/dist/game/TurnState.js.map +1 -1
- package/dist/game/ai/AiClientPrompts.d.ts +160 -0
- package/dist/game/ai/AiClientPrompts.d.ts.map +1 -0
- package/dist/game/ai/AiClientPrompts.js +525 -0
- package/dist/game/ai/AiClientPrompts.js.map +1 -0
- package/dist/game/ai/AiLiveView.d.ts +2 -0
- package/dist/game/ai/AiLiveView.d.ts.map +1 -0
- package/dist/game/ai/AiLiveView.js +48 -0
- package/dist/game/ai/AiLiveView.js.map +1 -0
- package/dist/game/ai/AiPlayerView.d.ts +2 -0
- package/dist/game/ai/AiPlayerView.d.ts.map +1 -0
- package/dist/game/ai/AiPlayerView.js +89 -0
- package/dist/game/ai/AiPlayerView.js.map +1 -0
- package/dist/game/ai/connectAiPlayer.d.ts +43 -0
- package/dist/game/ai/connectAiPlayer.d.ts.map +1 -0
- package/dist/game/ai/connectAiPlayer.js +58 -0
- package/dist/game/ai/connectAiPlayer.js.map +1 -0
- package/dist/game/ai/defineAi.d.ts +119 -0
- package/dist/game/ai/defineAi.d.ts.map +1 -0
- package/dist/game/ai/defineAi.js +122 -0
- package/dist/game/ai/defineAi.js.map +1 -0
- package/dist/game/ai/simulateMatches.d.ts +62 -0
- package/dist/game/ai/simulateMatches.d.ts.map +1 -0
- package/dist/game/ai/simulateMatches.js +108 -0
- package/dist/game/ai/simulateMatches.js.map +1 -0
- package/dist/game/badAiTransport/BadAIClientPrompts.d.ts +3 -0
- package/dist/game/badAiTransport/BadAIClientPrompts.d.ts.map +1 -1
- package/dist/game/badAiTransport/BadAIClientPrompts.js +3 -0
- package/dist/game/badAiTransport/BadAIClientPrompts.js.map +1 -1
- package/dist/hooks/useTokenMap.d.ts +2 -4
- package/dist/hooks/useTokenMap.d.ts.map +1 -1
- package/dist/hooks/useTokenMap.js +2 -5
- package/dist/hooks/useTokenMap.js.map +1 -1
- package/dist/hooks/useWebGlRenderer.d.ts +1 -0
- package/dist/hooks/useWebGlRenderer.d.ts.map +1 -1
- package/dist/hooks/useWebGlRenderer.js +33 -21
- package/dist/hooks/useWebGlRenderer.js.map +1 -1
- package/dist/index.d.ts +21 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/utilities/CanvasStack/CanvasOperations.d.ts +15 -1
- package/dist/utilities/CanvasStack/CanvasOperations.d.ts.map +1 -1
- package/dist/utilities/CanvasStack/CanvasOperations.js +65 -6
- package/dist/utilities/CanvasStack/CanvasOperations.js.map +1 -1
- package/dist/utilities/CanvasStack/CanvasStack.d.ts +18 -1
- package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
- package/dist/utilities/CanvasStack/CanvasStack.js +119 -6
- package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
- package/dist/utilities/CanvasStack/PlayerCanvas.d.ts +2 -1
- package/dist/utilities/CanvasStack/PlayerCanvas.d.ts.map +1 -1
- package/dist/utilities/CanvasStack/PlayerCanvas.js +3 -2
- package/dist/utilities/CanvasStack/PlayerCanvas.js.map +1 -1
- package/dist/utilities/CanvasStack/ReactCanvas.d.ts +2 -1
- package/dist/utilities/CanvasStack/ReactCanvas.d.ts.map +1 -1
- package/dist/utilities/CanvasStack/ReactCanvas.js +2 -2
- package/dist/utilities/CanvasStack/ReactCanvas.js.map +1 -1
- package/dist/utilities/ParameterizedCanvas.d.ts +1 -0
- package/dist/utilities/ParameterizedCanvas.d.ts.map +1 -1
- package/dist/utilities/ParameterizedCanvas.js +4 -1
- package/dist/utilities/ParameterizedCanvas.js.map +1 -1
- package/dist/utilities/TokenizedText.d.ts +49 -0
- package/dist/utilities/TokenizedText.d.ts.map +1 -0
- package/dist/utilities/TokenizedText.js +47 -0
- package/dist/utilities/TokenizedText.js.map +1 -0
- package/package.json +1 -1
- package/src/library/components/ClientTrustMatchViewer.tsx +32 -2
- package/src/library/components/DemoWrapper.tsx +4 -12
- package/src/library/components/Gallery/BuiltItem.ts +4 -0
- package/src/library/components/Gallery/GalleryController.ts +3 -1
- package/src/library/components/PanelSpark.tsx +1 -1
- package/src/library/components/PlayerImage.tsx +26 -2
- package/src/library/components/Playground.tsx +77 -12
- package/src/library/components/TokenizedMessage.tsx +2 -63
- package/src/library/components/TopBarPlayers.tsx +6 -1
- package/src/library/game/Chit.ts +2 -2
- package/src/library/game/ConnectionTransport.ts +12 -3
- package/src/library/game/Game.ts +9 -1
- package/src/library/game/Match.ts +162 -3
- package/src/library/game/MatchStorage.ts +14 -4
- package/src/library/game/Pick.ts +20 -0
- package/src/library/game/PlayerChit.ts +10 -3
- package/src/library/game/PlayerInfo.ts +13 -3
- package/src/library/game/PlayerPromptStatusChit.ts +3 -1
- package/src/library/game/Turn.ts +131 -76
- package/src/library/game/TurnState.ts +8 -0
- package/src/library/game/ai/AI_GUIDE.md +434 -0
- package/src/library/game/ai/AiClientPrompts.ts +681 -0
- package/src/library/game/ai/AiLiveView.ts +63 -0
- package/src/library/game/ai/AiPlayerView.ts +112 -0
- package/src/library/game/ai/ai.test.ts +475 -0
- package/src/library/game/ai/connectAiPlayer.ts +88 -0
- package/src/library/game/ai/defineAi.ts +230 -0
- package/src/library/game/ai/simulateMatches.ts +172 -0
- package/src/library/game/badAiTransport/BadAIClientPrompts.ts +3 -0
- package/src/library/hooks/useTokenMap.ts +2 -6
- package/src/library/hooks/useWebGlRenderer.tsx +44 -24
- package/src/library/index.ts +34 -2
- package/src/library/utilities/CanvasStack/CanvasOperations.tsx +87 -17
- package/src/library/utilities/CanvasStack/CanvasStack.ts +119 -5
- package/src/library/utilities/CanvasStack/PlayerCanvas.tsx +5 -2
- package/src/library/utilities/CanvasStack/ReactCanvas.tsx +2 -2
- package/src/library/utilities/ParameterizedCanvas.ts +5 -1
- package/src/library/utilities/TokenizedText.test.ts +32 -0
- package/src/library/utilities/TokenizedText.ts +97 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
# Writing AI players for a Pretty Chitty game
|
|
2
|
+
|
|
3
|
+
This guide is for whoever is adding computer opponents to a Pretty Chitty game, whether a
|
|
4
|
+
person or a coding agent. Follow it from top to bottom. When you're done:
|
|
5
|
+
|
|
6
|
+
- every pick in the game is tagged with `.ai("key")`,
|
|
7
|
+
- `src/ai.ts` has a scoring rule for every key,
|
|
8
|
+
- a `simulateMatches` test shows that bots finish games without getting stuck.
|
|
9
|
+
|
|
10
|
+
**The goal is bots that never look broken, not bots that win.** A bot that makes reasonable,
|
|
11
|
+
legal, purposeful moves is a success. Don't build search trees, simulations or "perfect play".
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## How it works (read this first)
|
|
16
|
+
|
|
17
|
+
- A game prompts a player with `turn.pick([...picks])`. Each pick offers options: chits to
|
|
18
|
+
click (`Chit.pick`), chits to drag onto targets (`Chit.dragPick`), or buttons.
|
|
19
|
+
- You tag each pick with a key: `.ai("market.buy")`.
|
|
20
|
+
- In `src/ai.ts` you write one **rule** per key. A rule receives **one option** and returns a
|
|
21
|
+
**score**. The bot scores every option in the prompt, across all of its picks, and plays the
|
|
22
|
+
highest one.
|
|
23
|
+
- By default the bot reads the match's **live game objects** in place, so rules see everything,
|
|
24
|
+
hidden information included. That is fast. If your rules would use information the seat should
|
|
25
|
+
not have, set `serializedView: true` (see Step 4) and the bot sees only what a human in that seat
|
|
26
|
+
would.
|
|
27
|
+
- A rule may also return a **plan**, which is saved to the bot's memory if that option wins.
|
|
28
|
+
Later rules can read it, which lets a bot carry intentions across prompts.
|
|
29
|
+
|
|
30
|
+
The engine already handles these. **Do not reimplement them:**
|
|
31
|
+
|
|
32
|
+
| Situation | What the engine does |
|
|
33
|
+
|---|---|
|
|
34
|
+
| Engine-inserted Confirm prompts | Pressed automatically |
|
|
35
|
+
| "No valid moves" dead end | Undoes the last answer, marks it dead for that exact situation, tries the next best; backs up further if every option is dead |
|
|
36
|
+
| Server rejects an answer | Tries the next best option |
|
|
37
|
+
| Untagged pick | Scores 0 (or uses `default`), logs `[AI p1] no rule for "..."` once |
|
|
38
|
+
| Game has no `ai` at all | Falls back to random play weighted by `Game.demoPickWeight` |
|
|
39
|
+
| Pacing in demo mode and Playground | Pauses 400–900 ms before each answer |
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## Step 1 — Inventory every pick
|
|
44
|
+
|
|
45
|
+
Find every prompt in the game:
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
grep -rn "turn.pick\|\.pick(\|Chit.pick\|Chit.dragPick\|noValidMoves" src/
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Make a table before writing any code. Write it in your notes, not in the repo:
|
|
52
|
+
|
|
53
|
+
| File:line | What the player is deciding | Pick type | Proposed key |
|
|
54
|
+
|---|---|---|---|
|
|
55
|
+
| phases/build.ts:88 | which factory to place, and where | DragPick | `build.place` |
|
|
56
|
+
| phases/build.ts:95 | stop building | ButtonPick (Done) | `build.done` |
|
|
57
|
+
| phases/market.ts:40 | which car to buy | ChitPick | `market.buy` |
|
|
58
|
+
| phases/market.ts:46 | skip buying | ButtonPick (Pass) | `market.pass` |
|
|
59
|
+
|
|
60
|
+
**Key naming:** `phase.action`, lowercase, stable, describing the *decision* rather than the
|
|
61
|
+
UI. Give each kind of action its own key. Two picks in different places that mean the same
|
|
62
|
+
decision may share a key.
|
|
63
|
+
|
|
64
|
+
## Step 2 — Tag the picks
|
|
65
|
+
|
|
66
|
+
Add `.ai(key)` to each pick, next to `.message()`:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
await turn.pick([
|
|
70
|
+
Chit.pick(cars, (c) => buy(c)).message("buy a car").ai("market.buy"),
|
|
71
|
+
new PassButton(() => (passed = true)).pick().message("pass").ai("market.pass"),
|
|
72
|
+
Chit.dragPick(factories, DragTarget.from(hexes, place)).message("build").ai("build.place"),
|
|
73
|
+
]);
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Rules for tagging:
|
|
77
|
+
|
|
78
|
+
- **Tag picks, not prompts.** Each pick in the array gets its own `.ai()`.
|
|
79
|
+
- **Don't change game behaviour.** Only add `.ai(...)`. Don't add, remove or reorder picks,
|
|
80
|
+
change callbacks, or add buttons to make the bot's life easier. If the bot can't cope with the
|
|
81
|
+
game as written, fix the rules in `ai.ts`.
|
|
82
|
+
- **Bare buttons:** if the code passes `new PassButton(...)` directly into the array, change
|
|
83
|
+
it to `new PassButton(...).pick().ai("x.pass")`. That's the same pick with a tag.
|
|
84
|
+
- **Optional data:** `.ai("market.buy", { cost })` passes a JSON hint to the rule. **Every
|
|
85
|
+
client receives it**, so never put hidden information in it. Prefer reading values from the
|
|
86
|
+
option's chit instead.
|
|
87
|
+
- Don't tag Confirm prompts the engine inserts automatically, or `turn.noValidMoves()`.
|
|
88
|
+
|
|
89
|
+
## Step 3 — Write `src/ai.ts`
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import { defineAi } from "@pretty-chitty/core";
|
|
93
|
+
import { Player, Root, Car, Factory, Hex } from "./chits";
|
|
94
|
+
|
|
95
|
+
type Memory = {
|
|
96
|
+
/** id of the car we intend to buy, then build a factory for */
|
|
97
|
+
targetCar?: string;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
export const ai = defineAi<Player, Root, Memory>({
|
|
101
|
+
initialMemory: () => ({}),
|
|
102
|
+
|
|
103
|
+
rules: {
|
|
104
|
+
"market.buy": (opt, { me }) => {
|
|
105
|
+
if (opt.kind !== "chit") return 0;
|
|
106
|
+
const car = opt.chit as Car;
|
|
107
|
+
if (car.cost > me.money) return -Infinity;
|
|
108
|
+
return {
|
|
109
|
+
score: car.value - car.cost * 0.5,
|
|
110
|
+
plan: (prev) => ({ ...prev, targetCar: car.id }),
|
|
111
|
+
};
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
"market.pass": (_opt, { options }) => {
|
|
115
|
+
// pass only when nothing else is worth doing
|
|
116
|
+
return options.some((o) => o.key === "market.buy") ? -1 : 0;
|
|
117
|
+
},
|
|
118
|
+
|
|
119
|
+
"build.place": (opt, { memory, find, view }) => {
|
|
120
|
+
if (opt.kind !== "drag") return 0;
|
|
121
|
+
const hex = opt.target as Hex;
|
|
122
|
+
if (hex.occupied) return -Infinity;
|
|
123
|
+
let score = adjacencyBonus(hex, view);
|
|
124
|
+
if (memory.targetCar && find(memory.targetCar) && hex.region === (find(memory.targetCar) as Car).region) {
|
|
125
|
+
score += 10;
|
|
126
|
+
}
|
|
127
|
+
return score;
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
"build.done": (_opt, { options }) => (options.some((o) => o.key === "build.place") ? -2 : 1),
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Then wire it into the Game class:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
import { ai } from "./ai";
|
|
139
|
+
|
|
140
|
+
export class MyGame implements Game<Player, Root> {
|
|
141
|
+
// ...
|
|
142
|
+
ai = ai;
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### The rule signature
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
(option: AiOption, ctx: AiContext) => number | { score: number; plan?: Memory | ((prev: Memory) => Memory) }
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
**`option`**
|
|
153
|
+
|
|
154
|
+
| Field | Meaning |
|
|
155
|
+
|---|---|
|
|
156
|
+
| `kind` | `"chit"` (click a chit), `"drag"` (drag `chit` onto `target`), or `"button"` |
|
|
157
|
+
| `chit` | The chit clicked or dragged. Present for `"chit"` and `"drag"` |
|
|
158
|
+
| `target` | The drop target. Present for `"drag"` |
|
|
159
|
+
| `button` | The button instance. Present for `"button"` |
|
|
160
|
+
| `key`, `data` | From `.ai(key, data)` |
|
|
161
|
+
| `pick.message`, `pick.help`, `pick.context`, `pick.buttonType` | Where the option came from |
|
|
162
|
+
|
|
163
|
+
Narrow on `opt.kind` before using `chit`, `target` or `button`, then cast to your chit class:
|
|
164
|
+
`opt.chit as Car`.
|
|
165
|
+
|
|
166
|
+
**`ctx`**
|
|
167
|
+
|
|
168
|
+
| Field | Meaning |
|
|
169
|
+
|---|---|
|
|
170
|
+
| `view` | Root chit as this seat sees it. Query it like game code |
|
|
171
|
+
| `me` | This bot's PlayerChit inside `view` |
|
|
172
|
+
| `options` | Every legal option in this prompt. Use it to compare ("is there anything better?") |
|
|
173
|
+
| `memory` | The current plan. Frozen, so don't mutate it |
|
|
174
|
+
| `find(id)` | Look up a chit in `view` by id. `undefined` if it's gone |
|
|
175
|
+
| `random()` | Per-bot rng in [0, 1). Use it for variety, never `Math.random` |
|
|
176
|
+
| `params` | Whatever the host passed as `connectAiPlayer(…, { params })` for this seat (per-seat weights, a version, a personality); `undefined` if none |
|
|
177
|
+
| `prompt.message` | The prompt's text |
|
|
178
|
+
|
|
179
|
+
### Scores
|
|
180
|
+
|
|
181
|
+
- **Higher is better.** Only the relative order within one prompt matters.
|
|
182
|
+
- **All keys in one prompt share a scale.** A prompt offering `market.buy` and `market.pass`
|
|
183
|
+
compares their numbers directly, so pick units for the game (points or money are good) and
|
|
184
|
+
use them everywhere.
|
|
185
|
+
- **`-Infinity`** means "never, unless nothing else is legal". Use it for illegal-in-spirit or
|
|
186
|
+
self-destructive moves.
|
|
187
|
+
- **Ties are broken at random**, and a small amount of noise is added, so bots aren't robotic.
|
|
188
|
+
By default the noise is `(max − min) × (1 − difficulty)` of the prompt's scores, so one outlier
|
|
189
|
+
(a −50 "never") makes the bot nearly random among the rest, and close scores make it fully
|
|
190
|
+
predictable. Use `-Infinity` for "never" (it is left out of the spread). For noise in your own
|
|
191
|
+
units, set a **temperature**: `defineAi({ temperature: 1, … })` for every bot of the game, or
|
|
192
|
+
`connectAiPlayer(…, { temperature })` per seat. The bot then picks by softmax: an option one
|
|
193
|
+
score unit worse is chosen e≈2.7× less often at temperature 1, and temperature 0 always plays
|
|
194
|
+
the best.
|
|
195
|
+
- **Untagged options in the same prompt score 0.** Keep that in mind when choosing your scale.
|
|
196
|
+
|
|
197
|
+
## Step 4 — Hidden information
|
|
198
|
+
|
|
199
|
+
The default view is the live board: the bot *could* read other hands, deck order, and other
|
|
200
|
+
players' unfinished simultaneous moves. That is your call as the developer: if your rules only
|
|
201
|
+
read the bot's own pieces and public information, leave it — it is many times faster (a 3-player
|
|
202
|
+
Excursions game spent ~60% of its time rebuilding serialized views). If fairness depends on it,
|
|
203
|
+
opt in:
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
export const ai = defineAi<Player, Root, Memory>({ serializedView: true, rules: { … } });
|
|
207
|
+
// or per seat: connectAiPlayer(match, playerId, { view: "serialized" })
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
With `serializedView`, the bot's view is redacted exactly like a human's:
|
|
211
|
+
|
|
212
|
+
- **Every field another player might hide can be `undefined`.** Always default it:
|
|
213
|
+
`const v = card.value ?? AVERAGE_CARD_VALUE;`
|
|
214
|
+
- **A face-down deck still has its chits**, with their contents stripped. Count them, but
|
|
215
|
+
don't read them.
|
|
216
|
+
- **Never mutate what you read.** With the live view, `view` *is* the game; a rule that sets a field
|
|
217
|
+
changes the real match.
|
|
218
|
+
- **Never** read state from anywhere except `ctx` and the option: no module-level game
|
|
219
|
+
singletons, no root captured from `run()`, no imports of live state. Helper functions and
|
|
220
|
+
constant tables (card data, scoring tables) are fine to import.
|
|
221
|
+
- A rule that throws scores 0 and is counted in `ruleErrors`. A missing `?? default` is the
|
|
222
|
+
usual cause.
|
|
223
|
+
|
|
224
|
+
## Step 5 — Plans (memory across prompts)
|
|
225
|
+
|
|
226
|
+
Use plans when one intention spans several prompts. For example: "buy car X, then build in
|
|
227
|
+
X's region", "save money for the 7-cost upgrade", "go for the blue majority".
|
|
228
|
+
|
|
229
|
+
- Return `{ score, plan }`. The plan is saved **only if this option wins**, so rules can
|
|
230
|
+
propose plans freely while scoring.
|
|
231
|
+
- A plain object **replaces** memory. Use the function form to keep other fields:
|
|
232
|
+
`plan: (prev) => ({ ...prev, targetCar: car.id })`.
|
|
233
|
+
- Memory must be JSON. Store **chit ids**, not chits, and resolve them with `find(id)`.
|
|
234
|
+
- **Plans are hints, not commitments.** Other players can make them stale. Always guard:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
const target = memory.targetCar ? find(memory.targetCar) : undefined;
|
|
238
|
+
if (target && target.parent === view.market) { /* still buyable */ }
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
- When the bot backs out of a dead end, memory rolls back automatically.
|
|
242
|
+
- Clear a plan once it's done: `plan: (prev) => ({ ...prev, targetCar: undefined })`.
|
|
243
|
+
- Memory is saved inside the match state (`state.ai[playerId]`), so it survives a reload or a bot
|
|
244
|
+
re-seated in another process. That is also why it must be JSON.
|
|
245
|
+
|
|
246
|
+
Keep plans small. Most games need one or two fields, or none.
|
|
247
|
+
|
|
248
|
+
## Step 6 — Prove it with a soak test
|
|
249
|
+
|
|
250
|
+
Create `src/ai.test.ts`:
|
|
251
|
+
|
|
252
|
+
```ts
|
|
253
|
+
import { expect, test } from "vitest";
|
|
254
|
+
import { simulateMatches } from "@pretty-chitty/core";
|
|
255
|
+
import { MyGame } from "./MyGame";
|
|
256
|
+
|
|
257
|
+
test("AI players finish games without getting stuck", async () => {
|
|
258
|
+
const report = await simulateMatches(new MyGame(), { players: 3, games: 5 });
|
|
259
|
+
expect(report.finished).toBe(5);
|
|
260
|
+
expect(report.stuck).toBe(0);
|
|
261
|
+
expect(report.stalls).toBe(0);
|
|
262
|
+
expect(report.ruleErrors).toBe(0);
|
|
263
|
+
expect(report.untagged).toEqual({});
|
|
264
|
+
}, 120_000);
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Run it at each player count the game supports. How to read a failed report:
|
|
268
|
+
|
|
269
|
+
| Symptom | Likely cause |
|
|
270
|
+
|---|---|
|
|
271
|
+
| `untagged` not empty | A pick has no `.ai()` tag, or its key has no rule. The keys of `untagged` are the pick messages |
|
|
272
|
+
| `ruleErrors > 0` | A rule threw. Usually it read a hidden field without `?? default` |
|
|
273
|
+
| `outcome: "maxPrompts"` | The bot loops: a free-arrange or "keep going" pick always outscores Done/Pass. Make the stop option win once progress is made (see the cookbook) |
|
|
274
|
+
| `stepBacks` very high | Rules keep choosing moves that lead to "no valid moves". Score those moves `-Infinity` up front |
|
|
275
|
+
| `stalls > 0` | A pick callback can leave state unchanged, so the server never responds. That's a game bug; report it rather than working around it |
|
|
276
|
+
| `stuck > 0` | Every option leads to a dead end and the bot can't undo further. Usually a game bug |
|
|
277
|
+
|
|
278
|
+
To print details, use `const report = await simulateMatches(game, { log: true });` and
|
|
279
|
+
`console.log(report.matches)`.
|
|
280
|
+
|
|
281
|
+
Then watch one game in the browser: open the game's demo page (`/demo`), or use Playground
|
|
282
|
+
with AI players checked. Moves should look purposeful.
|
|
283
|
+
|
|
284
|
+
---
|
|
285
|
+
|
|
286
|
+
## Step 7 — Measure and tune (optional)
|
|
287
|
+
|
|
288
|
+
Hand-written rules encode assumptions, and some will be wrong. Three hooks let a harness test them
|
|
289
|
+
by playing:
|
|
290
|
+
|
|
291
|
+
- **`params`**: give each seat its own weights (`connectAiPlayer(…, { params: { weights } })`,
|
|
292
|
+
read as `ctx.params` in rules). Put every constant your rules use in one weights object, and a
|
|
293
|
+
tournament can play variants against each other: seat them at random, rank by the share of
|
|
294
|
+
opponents each finished ahead of, keep the best, mutate, repeat. Rotate seats every game —
|
|
295
|
+
turn order alone can be worth ±20 points of win rate.
|
|
296
|
+
- **`onDecision(d)`**: called after every choice with each option's score, the chosen index and
|
|
297
|
+
the `ctx`. Log it to compare what the bot expected with what happened.
|
|
298
|
+
- **`choose(scored, ctx)`**: return an index to force the answer. With it a harness can fork a
|
|
299
|
+
match at a decision — copy `match.state` (the decision history), load it into a new `Match`,
|
|
300
|
+
and the engine replays it to the pending prompt — then force each option in turn and play the
|
|
301
|
+
game out. Comparing options by playout finds wrong assumptions that no weight change can fix:
|
|
302
|
+
a value that should depend on the board, two things that only pay together, a goal no rule
|
|
303
|
+
pursues.
|
|
304
|
+
|
|
305
|
+
Headless runs: set `match.immediateNotify = true` and use `new EphemeralMatchStorage(id, true)`
|
|
306
|
+
(lazy saves). Both are off by default because they change behaviour a server relies on; see
|
|
307
|
+
their doc comments.
|
|
308
|
+
|
|
309
|
+
## Seating bots in a host
|
|
310
|
+
|
|
311
|
+
A seat is an AI seat when its `IPlayerInfo.ai` is set (`{}` or `{ difficulty }`). The flag on its own
|
|
312
|
+
does nothing; a host opts in by calling `match.seatAiPlayers()` once, after `load()`:
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
const match = new Match(game, players, storage, options);
|
|
316
|
+
await match.load();
|
|
317
|
+
match.seatAiPlayers({ thinkMs: [400, 900] }); // one bot per flagged seat, skipping seats a connectAiPlayer bot already holds
|
|
318
|
+
match.start();
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
`ClientTrustMatchViewer` does this for you when given `seatAi` (`true` or the options object).
|
|
322
|
+
Harnesses keep calling `connectAiPlayer` directly for the seat under test and can still call
|
|
323
|
+
`seatAiPlayers` to fill the rest.
|
|
324
|
+
|
|
325
|
+
Then three things the host owns:
|
|
326
|
+
|
|
327
|
+
- **One driver per match.** Several copies of one match can run at once: every browser tab in
|
|
328
|
+
client-trust mode, or two bundle versions of a match on a server. Each copy would answer the
|
|
329
|
+
same prompt, so set `match.ai.enabled = false` on all but one (`aiEnabled` on
|
|
330
|
+
`ClientTrustMatchViewer`). Paused bots keep their memory and answer the pending prompt when
|
|
331
|
+
re-enabled, re-reading memory from the state first in case the previous driver moved it on.
|
|
332
|
+
- **Wait for `match.ai.idle`** before tearing a match down, so an answer in flight is not lost.
|
|
333
|
+
- **`match.dispose()`** disposes the bots and every connection with the match.
|
|
334
|
+
|
|
335
|
+
The flag is copied onto the `PlayerChit` as `player.ai` and serialized publicly, so a UI can mark
|
|
336
|
+
the seat.
|
|
337
|
+
|
|
338
|
+
## Heuristic cookbook
|
|
339
|
+
|
|
340
|
+
Start every key with **1**, **2** and **6**. That alone usually stops a bot looking broken.
|
|
341
|
+
|
|
342
|
+
1. **Take immediate value.** Score = what the action is worth right now, in the game's units.
|
|
343
|
+
2. **Prefer progress to passing.** Pass/Done should lose while useful options exist:
|
|
344
|
+
|
|
345
|
+
```ts
|
|
346
|
+
"x.pass": (_o, { options }) => (options.some((o) => o.key !== "x.pass") ? -1 : 0),
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
3. **Pay attention to cost.** Score = gain − cost, in the same units.
|
|
350
|
+
4. **Finish what you start.** Commit a plan on step one and add a bonus on the next step for
|
|
351
|
+
options that fulfil it.
|
|
352
|
+
5. **Deny the leader cheaply.** Add a small bonus for taking something the leading opponent
|
|
353
|
+
clearly needs, using only public information.
|
|
354
|
+
6. **Never do the obviously broken thing:** dropping a piece onto itself or into its own
|
|
355
|
+
stack, moving something back where it came from, discarding instead of building, buying
|
|
356
|
+
what you can't use. Return `-Infinity` or a large negative.
|
|
357
|
+
7. **Converge in loops.** For "keep acting until Done" picks, track progress in memory and
|
|
358
|
+
make Done win after enough actions, or when nothing scores above 0:
|
|
359
|
+
|
|
360
|
+
```ts
|
|
361
|
+
"arrange.move": (o) => ({ score: moveValue(o), plan: (m) => ({ ...m, moves: m.moves + 1 }) }),
|
|
362
|
+
"arrange.done": (_o, { memory }) => (memory.moves >= 3 ? 10 : -10),
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
Reset the counter when the loop starts again (for example, when the round number in
|
|
366
|
+
`view` changes).
|
|
367
|
+
|
|
368
|
+
8. **Add a little personality.** `ctx.random() * 0.5` on near-equal choices makes bots feel
|
|
369
|
+
less mechanical. The engine already adds some noise (or set a `temperature`). For bots that
|
|
370
|
+
differ from each other, give each seat its own weights through `params`.
|
|
371
|
+
|
|
372
|
+
## Anti-patterns
|
|
373
|
+
|
|
374
|
+
- ❌ Changing game code, picks or callbacks to make the AI easier.
|
|
375
|
+
- ❌ Reading hidden state from anywhere other than `ctx`.
|
|
376
|
+
- ❌ Calling `Math.random()` or `Date.now()` in rules. Use `ctx.random()`.
|
|
377
|
+
- ❌ Mutating `memory` or any chit in `view`. Rules must be side-effect free.
|
|
378
|
+
- ❌ Expensive work in rules, such as cloning the board or simulating turns. Rules run once per
|
|
379
|
+
option, and drags can have hundreds of options. Keep each rule cheap, and precompute shared
|
|
380
|
+
values outside the per-option logic where possible.
|
|
381
|
+
- ❌ Scoring everything the same. That gives a random bot with extra steps.
|
|
382
|
+
- ❌ Leaving `untagged` non-empty "for later".
|
|
383
|
+
|
|
384
|
+
## Reference
|
|
385
|
+
|
|
386
|
+
```ts
|
|
387
|
+
// Tag a pick
|
|
388
|
+
pick.ai(key: string, data?: unknown): this
|
|
389
|
+
|
|
390
|
+
// Define the AI (set as `ai` on your Game)
|
|
391
|
+
defineAi<P, R, M>({
|
|
392
|
+
serializedView?: boolean, // rules see only what the seat is sent (slower)
|
|
393
|
+
temperature?: number, // default softmax temperature for every bot of the game
|
|
394
|
+
initialMemory?: () => M,
|
|
395
|
+
rules?: { [key: string]: (option, ctx) => number | { score, plan? } },
|
|
396
|
+
default?: (option, ctx) => number | { score, plan? }, // for untagged picks
|
|
397
|
+
})
|
|
398
|
+
|
|
399
|
+
// Seat every flagged seat (hosts; demo mode, Playground and ClientTrustMatchViewer do this)
|
|
400
|
+
match.seatAiPlayers({ thinkMs?, temperature?, seed?, log?, view?, onDecision? }): AiPlayerHandle[]
|
|
401
|
+
match.ai.enabled // pause/resume every bot of this match (one driver per match!)
|
|
402
|
+
match.ai.idle // true when no bot is mid-answer
|
|
403
|
+
match.ai.handles // every bot attached, however it was seated
|
|
404
|
+
|
|
405
|
+
// Seat one bot with exactly these options (harnesses)
|
|
406
|
+
connectAiPlayer(match, playerId, {
|
|
407
|
+
difficulty?: 0..1, temperature?: number, thinkMs?: number | [min, max], seed?, log?,
|
|
408
|
+
view?: "live" | "serialized", params?: unknown,
|
|
409
|
+
choose?: (scored, ctx) => number | undefined, // harnesses: force an answer
|
|
410
|
+
onDecision?: (decision) => void, // harnesses: every choice, with all scores
|
|
411
|
+
memoryStore?: AiMemoryStore | false, // default: the match state; false: in-process only
|
|
412
|
+
disabled?: boolean, // start paused
|
|
413
|
+
})
|
|
414
|
+
|
|
415
|
+
// Headless soak test
|
|
416
|
+
simulateMatches(game, { players?, games?, maxPrompts?, stallMs?, timeoutMs?, matchOptions?, difficulty?, log? })
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
- **Worked example:** `src/demo/ai.ts` with the tags in `src/demo/DemoGame.ts`, in the
|
|
420
|
+
pretty-chitty repo. It includes drag rules that avoid self-drops and cycles, a stop-after-a-
|
|
421
|
+
few-moves loop, and a plan read back by a later prompt.
|
|
422
|
+
- **Engine source:** `src/library/game/ai/` (`defineAi.ts` has the types,
|
|
423
|
+
`AiClientPrompts.ts` the bot).
|
|
424
|
+
|
|
425
|
+
## Done checklist
|
|
426
|
+
|
|
427
|
+
- [ ] Every `turn.pick` option in the game has an `.ai(key)` tag, and no game behaviour changed
|
|
428
|
+
- [ ] `src/ai.ts` has a rule for every key, and `ai` is set on the Game class
|
|
429
|
+
- [ ] Every read of a field that could be hidden has a `?? default`
|
|
430
|
+
- [ ] Pass/Done/Stop options lose while useful work remains, and win once it doesn't
|
|
431
|
+
- [ ] Obviously broken moves score `-Infinity`
|
|
432
|
+
- [ ] `simulateMatches` test: all matches finish; `stuck`, `stalls` and `ruleErrors` are 0;
|
|
433
|
+
`untagged` is empty, at every supported player count
|
|
434
|
+
- [ ] Watched one game in demo mode or Playground and the moves look purposeful
|