# Writing a Property Deal bot

This page is for you and for the AI assistant you may be writing the bot with: paste it in whole. It says what a
bot is, what the game gives it, what it must answer, the rules it runs under, and how bots are ranked. The game
engine (`src/game.ts`, `src/cards.ts`, in the starter repo) is the source of truth. If this page and the engine
disagree, the engine is right and this page needs fixing.

## In short

- A bot is a function. The game calls it every time a player must decide something. It gets a **View** (everything
  that player may see) and returns one **Move**.
- The game is Property Deal, for 2 to 5 players. On your turn you draw 2 cards (5 if your hand is empty, as on the first turn), then make up to 3 plays (bank
  money, put down properties, play action cards), then end the turn, discarding down to 7 cards. Complete **3 full
  sets** of properties to win. Other players also have to decide things on your turn (pay rent, say no), and those
  are bot decisions too.
- Your bot is checked, then plays against the other bots in four leagues (2, 3, 4 and 5 players) and gets a
  rating in each. See "Leagues".
- Every bot is published under the **MIT licence**: anyone can download, read and build on yours.

## The bot

A bundle's default export is a factory:

```ts
export default function createBot(seed: number): { name: string; decide(view: View): Move }
```

**Design for a fresh bot on every call.** The game builds a new `createBot(seed)` for **every decision**, and it
may run on a different machine each time. Don't rely on anything surviving from one call to the next (module-level
variables, caches, things learned about the opponents), and don't rely on it *not* surviving either. Everything a
bot wants to remember must be rebuilt from `view.history` on each call. This isn't enforced today, but a bot that
leans on state will behave differently in the league than it did in your tests.

The `seed` is fixed by game, seat and decision number, so any decision can be replayed exactly: the same view and
seed must give the same move. Use it for all randomness (`Math.random` isn't replayable).

## Time and limits

| | |
|---|---|
| Time | **Aim for 20 ms per decision on average.** A decision that takes longer than **2 s** is replaced by a fallback move (the built-in Medium bot's move), and the fallback is logged against your bot. The 2 s includes rebuilding your memory from the history. |
| The clock | `Date.now()` and `performance.now()` **don't advance** while code runs in Workers, so a time budget never runs out. Limit a search by counting work (nodes, rollouts), not by the clock. |
| Answer size | the JSON answer is capped at **16 KB**. A move is far smaller than that. |
| Network | **none.** `fetch()` and every other outbound connection throws. |
| Environment | `env` is empty. `process` exists (Node compatibility), but **`process.env` is empty**, so read settings with a default, never assume a value. |
| Failures | a throw, a timeout, an oversized or unparseable answer, or an illegal move all get the same treatment: the Medium bot's move is played instead and the failure is logged. A bot that falls back a lot will rate badly. |
| Submission size | readable source in TypeScript or JavaScript, one or more files, about **300 KB in total**, plus optional **JSON-only** data files (for weights). We do the bundling: relative imports between your files and JSON data files only, no `node:` imports. The bundle must stay under 10 MB. |

## A worked decision

Your seat is first to play, turn 1. You hold five cards and the game asks for your move. Cut down to what matters,
the View is:

```json
{
  "phase": "playing", "me": "p1", "turn": "p1", "playsLeft": 3, "turnCount": 1, "deckCount": 96,
  "hand": [90, 20, 15, 72, 10],
  "players": [
    { "id": "p1", "name": "You", "handCount": 5, "bank": [], "props": [], "buildings": {} },
    { "id": "p2", "name": "Rival", "handCount": 5, "bank": [], "props": [], "buildings": {} }
  ],
  "pending": null,
  "history": [ { "t": "start", "players": 2 }, { "t": "turn", "seat": 0, "n": 1 }, { "t": "draw", "seat": 0, "n": 5, "cards": [90, 20, 15, 72, 10] } ]
}
```

Card ids index `CARDS` in `src/cards.ts`: 90 is Pass Go (draw 2 cards, worth £1M), 20 is the brown property Fair Acres
Gardens, 15 is £4M, 72 is Deal Breaker (steals a complete set), 10 is £2M. With nothing on the table the useful
plays are to draw more cards and to start a set. Each play uses one of your three, and Pass Go draws two new cards,
so a bot might open with:

```json
{ "type": "play", "cardId": 90 }
```

The game plays it, draws two cards, and asks again with a new View (`hand` now has 6 cards and `playsLeft` is 2). Next the bot might
play the property:

```json
{ "type": "play", "cardId": 20 }
```

then bank the £4M with `{ "type": "play", "cardId": 15 }`, which uses the last play, and finally `{ "type": "endTurn" }`. Keeping Deal Breaker in
hand is a reasonable choice: it only matters once a rival has a complete set. If a rival later plays rent on you,
you are asked again, this time with `pending` set (`stages[me] === 'pay'`), and answer with
`{ "type": "pay", "cardIds": [15] }`. A small bot that always picks a legal move and ends its turn is a valid
entry; the starter repo ships the engine and `legalMoves` to build on.

Which moves are legal at each point is listed in "Move" below. The starter repo includes `legalMoves` from `src/bot.ts`
(see the note under "Move"), which lists them all, so a bot can choose among them instead of building moves by hand.

## Leagues

There are four leagues, one per table size: **2, 3, 4 and 5 players**. A bot is entered in the leagues its author
picks, and has its own rating in each, since good play changes with the number of opponents. Ratings are on a
scale where the Medium bot is 0, shown with a ± 95% interval that narrows as games are played.

Each league has an **active pool of the top 16 bots**. A new entrant plays a few hundred qualification games; if it
rates above number 16 it joins the pool and number 16 drops out. Bots outside the pool stay on the leaderboard
with their stats, and a small share of games bring in bots from outside the pool so a dropped bot can climb back.
Medium isn't in the pools.

## View

`view(g, playerId)` in `src/game.ts`. What a person at that seat could see, and nothing more.

| Field | Meaning |
|---|---|
| `phase` | `'lobby' \| 'playing' \| 'finished'` |
| `me` | your player id |
| `turn` | id of the player whose turn it is |
| `playsLeft` | plays left this turn (3 at the start of a turn) |
| `turnCount` | turns started this game (the first turn is 1) |
| `deckCount` | cards left in the draw pile |
| `discard`, `discardTop` | the discard pile, oldest first, and its top card |
| `discardBy` | who put each `discard[i]` there (player ids) |
| `players[]` | seat order. Each: `id`, `name`, `bot`, `online`, `handCount`, `bank` (card ids), `props` (`{ id, color }`, wilds carry the colour they're played as), `buildings` (`{ [color]: { house?, hotel? } }`, card ids) |
| `hand` | your hand (card ids) |
| `pending` | an action waiting on players, or `null`: `type` (`rent`, `debt`, `birthday`, `slydeal`, `forceddeal`, `dealbreaker`), `from` (actor id), `targets` (ids still to deal with), `stages` (`{ [id]: 'respond' \| 'counter' \| 'pay' }`), `amount`, and `color`, `takeId`, `giveId` where they apply |
| `log`, `logTotal` | the last 40 human-readable log lines. For people; bots should use `history`. |
| `winner` | winner's id once the game is over |
| `historyVersion` | `1` (see Versioning) |
| `historyFrom` | `null`: `history` covers the whole game. A number: the game was already running when history recording began, and events start at that turn (see below). |
| `history` | every public change this game, filtered for your seat (below) |

Your seat is `players.findIndex(p => p.id === view.me)`. Cards are ids into `CARDS` in `src/cards.ts`
(`kind`, `name`, `value`, `color`/`colors`, `action`). There are 106.

## Move

| Move | When |
|---|---|
| `{ type: 'play', cardId, as: 'bank' }` | bank any money, rent or action card |
| `{ type: 'play', cardId }` | money (banks it), a property, Pass Go, It's My Birthday |
| `{ type: 'play', cardId, color }` | a wild (as that colour), a House or Hotel (on that complete set) |
| `{ type: 'play', cardId, color, doubles: [ids], target? }` | rent for that colour, with Double the Rent cards; `target` (a player id) only for Wild Rent |
| `{ type: 'play', cardId, target }` | Debt Collector |
| `{ type: 'play', cardId, target, takeId }` | Sly Deal (`takeId`: their property, not from a complete set) |
| `{ type: 'play', cardId, target, takeId, giveId }` | Forced Deal (`giveId`: one of your properties) |
| `{ type: 'play', cardId, target, color }` | Deal Breaker (their complete set of that colour) |
| `{ type: 'moveWild', cardId, color }` | move one of your wilds to another colour (free, your turn only) |
| `{ type: 'endTurn', discards?: [ids] }` | end your turn; over 7 cards, discard exactly the excess |
| `{ type: 'respond', accept }` | a target: `accept: false` plays your Just Say No |
| `{ type: 'respond', accept, target }` | the actor, after a target's Just Say No: `accept: false` says Just Say No back |
| `{ type: 'pay', cardIds: [ids] }` | pay from your bank, properties and buildings; at least `amount`, and no card you don't need |

`legalMoves(determinize(view, rng), view.me)` in `src/bot.ts` lists every legal move. It lists one move per
group of interchangeable cards, but any equivalent legal move is accepted.

## History

`view.history` is a list of small events, oldest first: one for every change to public state. Seats are
indexes into `players`; cards are card ids; colours are the names in `COLORS`.

**Filtering.** It's the game as a person at your seat saw it. The only hidden information in this game is
what's in each hand and the order of the draw pile, so the only difference between seats is in `draw`
events: your own draws list their `cards`, everyone else's only `n`. Every other card in the history was
face up on the table or the discard pile when the event happened.

| Event | Meaning |
|---|---|
| `{ t:'start', players }` | a new game with this many seats (everyone's table is empty) |
| `{ t:'turn', seat, n }` | turn `n` starts for `seat` (`n` = `turnCount`) |
| `{ t:'draw', seat, n, cards? }` | `seat` drew `n` cards (fewer than asked if the deck ran out); `cards` only for your own seat. The opening deal is one 5-card draw per seat. |
| `{ t:'reshuffle', n }` | the draw pile was empty: the `n` cards in the discard pile became the new draw pile (the pile is now empty) |
| `{ t:'bank', seat, card }` | from hand to bank (money, or any card played `as: 'bank'`) |
| `{ t:'prop', seat, card, color }` | property or wild from hand to the table, as `color` |
| `{ t:'move', seat, card, from, to }` | a wild on the table moved colour |
| `{ t:'build', seat, card, color }` | House or Hotel (look at `card`) from hand onto the complete `color` set |
| `{ t:'passgo', seat, card }` | Pass Go played (to the discard pile); a `draw` of 2 follows |
| `{ t:'rent', seat, card, color, amount, targets, doubles }` | rent card and its `doubles` (Double the Rent ids) played to the discard pile, in that order; each seat in `targets` owes `amount` |
| `{ t:'debt', seat, card, target, amount }` | Debt Collector played; `target` owes `amount` (5) |
| `{ t:'birthday', seat, card, targets, amount }` | It's My Birthday played; each target owes `amount` (2) |
| `{ t:'sly', seat, card, target, take }` | Sly Deal played on `target`'s property `take` |
| `{ t:'forced', seat, card, target, take, give }` | Forced Deal played: `take` theirs, `give` yours |
| `{ t:'breaker', seat, card, target, color }` | Deal Breaker played on `target`'s complete `color` set |
| `{ t:'jsn', seat, card, against }` | `seat` played Just Say No (to the discard pile) against `against`: a target blocking the actor, or the actor answering a target's Just Say No |
| `{ t:'accept', seat, against }` | the game waited for `seat` to decide and they let it go: a target accepting `against`'s action (a `pay`, `take` or `takeSet` follows; paying straight away counts), or the actor accepting `against`'s Just Say No (a `blocked` follows). Only ever from a real choice: see "Who gets asked" |
| `{ t:'blocked', seat, target }` | `seat`'s action against `target` is cancelled (the last Just Say No stood) |
| `{ t:'take', from, to, card }` | the result of a Sly Deal, or one half of a Forced Deal (two `take`s: what was taken, then what was given) |
| `{ t:'takeSet', from, to, color, cards, house?, hotel?, banked? }` | the result of a Deal Breaker: `cards` (properties) move to `to`, still as `color`; `house`/`hotel` move onto `to`'s set of that colour; `banked` are buildings that went to `to`'s bank because that set already had one |
| `{ t:'pay', from, to, cards }` | a payment (chosen, or automatic when everything you own isn't enough). `cards: []` means `from` had nothing to pay with. |
| `{ t:'discard', seat, cards }` | end-of-turn discards, from hand to the discard pile |
| `{ t:'end', seat }` | `seat` ended their turn |
| `{ t:'win', seat }` | `seat` won |

Every played action card (`passgo`, `rent` + `doubles`, `debt`, `birthday`, `sly`, `forced`, `breaker`,
`jsn`, `discard`) goes to the discard pile, in event order. Houses and Hotels stay on the table.

**Cards changing hands** (`pay`, `take`): each card goes to the same kind of place it left: bank to bank,
property to property (keeping its colour), and a House or Hotel to the receiver's **bank**.

**What happens to an action.** The action event comes first, then any `jsn` events, then the outcome for
each target: `pay`, `take`/`takeSet` or `blocked`. With several targets (rent on everyone, birthday) the
targets are settled independently, so their events can interleave. Accepting a charge has no event of its
own beyond `accept`: it shows in `view.pending` (the target's stage becomes `pay`) and later as a `pay`.

**Who gets asked (Just Say No tells).** When an action reaches a player who could answer with Just Say No, the
game waits for them (their stage is `respond`, or `counter` for the actor) only if it *asks* them. In live
games **people are always asked**, whether or not they hold a Just Say No (`alwaysAsk`), so a person being
asked says nothing about their hand. **Bots are asked only when they hold a Just Say No.** When nobody is
asked, the engine settles the step at once and there is no `accept` event, just the outcome. So an `accept`
(or a `jsn`) means the game waited for that seat; for a seat with `view.players[i].bot` set, being asked means
they held a Just Say No at that moment. The phones can see the same thing (`pending.stages` is public), so
this is no leak. In simulations and the leagues nobody has `alwaysAsk`, so everyone is treated like a bot.

**Replaying.** The history is complete: from it alone you can rebuild every seat's bank, properties and
buildings, the discard pile, every hand size and your own hand, in the same order the view shows them.
`src/replay.ts` in the starter repo is a reference replay (our tests check it against the real state after every few moves of
hundreds of random games). Copy it.

**Undo.** People can vote to take the game back to an earlier point. The history is rewound with the game:
the events after that point disappear as if they never happened, and the draw pile is reshuffled. A bot that
rebuilds everything from `history` on every call (as it must) needs to do nothing special.

**`historyFrom`.** Games already running when this history was added have no record of what came before.
Instead of a made-up past, they get `history: []` and `historyFrom: <the turn it was at>`. Events from then on
are recorded as usual, but they don't add up to the current table, so with `historyFrom !== null` read the
current state from the view and treat the history as partial. A new game always starts a full history
(`historyFrom: null`).

**Phones.** The phones show `log` and get `history: []` (the full history would make every state message
about three times bigger). Only bots are sent the history.

## Versioning

`historyVersion` is `1`. It goes up whenever the history changes in a way a bot written for the previous
version could misread: a field renamed, removed or given a new meaning, or a new event type that changes the
table (a replay that skipped it would go wrong). Fields or event types that are only informative may be added
without a change, so **ignore fields and event types you don't know**. A bot can check `historyVersion` and
fall back to reading the view alone when it doesn't recognise the version.

## Sizes

Measured with the built-in Medium bot in every seat: about 115 events (4.6 KB of JSON) in
a 2-player game, 170 (6.8 KB) at 3 players, and about 200 (8 KB) at 4 and 5 players. The largest seen was
13 KB. Random play, which drags on, gets up to ~75 KB in a 300-turn game.
