# Turn-based apps and games

Source: https://dabadata.com/docs/turn-based/ (HTML) - https://dabadata.com/docs/turn-based/index.md (this page as markdown)

A card game, a vote, an auction, a quiz: players take turns, some things are hidden, some are left to chance, and something of value moves at the end. dabadata runs such apps with no backend of yours and no loop on ours. The server owns identity, hidden data, time and order, chance and value; your clients may run the rules of the game. A machine opponent needs no backend either: its moves are the server's random picks. This page says who owns what, what a cheater can still do, which pattern to use, and the pitfalls.

## Who owns what

The goal is to move as much work as possible to the clients and leave the server the checks, so that the most a cheater can do is change their own client. That holds only while the server owns these six things:

| The server owns | With | Otherwise a cheater could |
| --- | --- | --- |
| **Identity:** you act only as yourself | Tokens; `$user.id` in rules and steps | move for others |
| **Hidden data:** each player sees what the rules allow, revealed by a condition | [Read rules](https://dabadata.com/docs/rules/index.md), [column read rules](https://dabadata.com/docs/rules/index.md#column-read-rules), a round's close | read others' cards |
| **Time and order:** deadlines, one move per round | [Rounds](https://dabadata.com/docs/tables/index.md#rounds) | change a move after seeing the others' |
| **Chance:** drawn by the server, never sent by a client | [Server-filled columns](https://dabadata.com/docs/tables/index.md#fills), the [`draw` step](https://dabadata.com/docs/rules/index.md#draw) | choose their luck |
| **Value:** coins and scores move only inside actions - on agreement, out of a pot the server fills, or by a trusted caller | [Agreement](https://dabadata.com/docs/rules/index.md#agree), [actions](https://dabadata.com/docs/rules/index.md#actions-protecting-counters-capacity-and-stock), checks | pay themselves |
| **Legality, where it is cheap:** declarative checks on moves | A `check` step with `expect` before the [`submit`](https://dabadata.com/docs/rules/index.md#submit) | play an illegal move |

Nothing here runs your code on the server: fills, draws, rounds and agreements are declared in the definition, like rules and actions. A machine opponent needs no code on the server either: its moves are the server's random fills ([a machine opponent with no backend](https://dabadata.com/docs/turn-based/index.md#machine)). Only an app with logic of its own that no client may run - a machine that must play smart with information no player may see - needs a process of yours ([optional: a trusted worker](https://dabadata.com/docs/turn-based/index.md#server-authoritative)).

## What a cheater can and cannot do

Assume a player rewrites their client, or lets a program play for them. With the server owning the six things above, they **cannot**:

- act as another user, or submit a move for anyone but themselves;
- read hidden data: another player's hand, the other moves of a round before it closes, a hidden rank (the server leaves those values out of every answer, live message and trace row they may read);
- move late, move twice, or take a move back (`round_over`, `already_in`);
- pick their randomness: a filled column or a drawn card never comes from a request;
- move value alone in a match with other players: a settlement needs their agreement, or a trusted caller;
- against the machine, take more than the pot of their own match, or touch another player's coins or matches ([exactly what they can do there](https://dabadata.com/docs/turn-based/index.md#machine-cheaters));
- change another player's client.

They **can**:

- play perfectly, with a bot or an AI helping them - no server can tell a good player from a program;
- refuse to agree, which ends in a dispute that your definition handles (stakes returned, a match void);
- leak their own cards to someone else;
- stop playing: their rounds time out, and an agreement that waits for them completes after its `wait`;
- leave the match at any moment, which ends it at once and gives the pot to the other side ([Leaving a match](https://dabadata.com/docs/turn-based/index.md#leave)).

Design so that each of these costs the cheater, not the other players: a dispute returns the stakes rather than paying anyone; an absent player times out.

## Choosing a pattern

| Your app | Pattern | Example |
| --- | --- | --- |
| One player against a machine opponent (the first choice) | [A machine opponent with no backend](https://dabadata.com/docs/turn-based/index.md#machine): the machine's moves are the server's random fills, hidden until the round closes; the player's client computes the result; the server checks it and caps it by the match's pot | The Kidnapper and Warcall against the machine |
| Players against each other, with hidden information (cards in hand) or chance | [Server-verified](https://dabadata.com/docs/turn-based/index.md#server-verified): the server deals, keeps time and checks moves; the clients compute results; value moves on agreement | The Kidnapper and Warcall player against player |
| Players against each other, all information open, no chance | [Lockstep](https://dabadata.com/docs/turn-based/index.md#lockstep): the server orders and times the moves; every client computes the same state | Chess, go, tic-tac-toe |
| Simultaneous moves that must stay secret even from the server until all are in | Add [commit-reveal](https://dabadata.com/docs/turn-based/index.md#commit-reveal) inside one of the above | A sealed bid, rock-paper-scissors with an untrusted host |
| Optional, rarely needed: a machine that plays smart with information no client may hold, or rules no client may compute (real money) | [A trusted worker](https://dabadata.com/docs/turn-based/index.md#server-authoritative) of yours makes the machine's moves and settles alone | The `card-duel-referee` template |

Coins, points or anything else of value: in every pattern it moves only inside an action - by [agreement](https://dabadata.com/docs/rules/index.md#agree) of the players' clients, out of a pot the server filled (against the machine), or by a trusted caller (`authority`). Never give clients a write rule on a balance.

## A machine opponent with no backend

The first choice for one player against the machine: no worker, no server function, no process of yours. The machine's moves are the server's random fills on the round row, hidden from the player until the round closes. The player's browser computes the result with the same game code it uses against people and sends it; the server checks everything it can check without game code, and caps what the settlement can pay by a pot the server fills itself each round. This is how the Kidnapper and Warcall play their machine levels.

- **The machine's move is a fill.** When a round is inserted, the server fills a column with its own randomness: a random card of the machine's hand (`random: { where }`) or a random value (`random: { int }`). A [column read rule](https://dabadata.com/docs/rules/index.md#column-read-rules) such as `status = 'closed'` leaves it out of every answer, live message and trace row the player may read until the round closes, so the player's choice cannot react to it.
- **The player is the round's only participant.** The round closes when their move is in, or lazily at the deadline; then the machine's card is readable.
- **The client computes, the server checks.** The player's client reads the revealed move and the machine's card, runs the battle and calls a settle action. Its first steps are the guard: the player's own match, still being played, its current round, closed (so every move in it was on time) and not yet settled; the round is marked settled under its row lock, so the same round is never settled twice.
- **The server fills the pot.** Each round, an action takes the player's stake from their wallet and adds it plus the house's share to the match's pot. Steps have no arithmetic, so the house's share comes from a table an admin keeps: one row per level and stake with the share and the sum already worked out. Payouts come out of the pot (a check keeps `pot >= 0`), and the end actions take no amount from the client: a win pays `$step.m.pot`, the server's own number.
- **Levels differ by payout only.** A machine that plays at random is the same opponent at every level; a level changes the house's share, and so what a win pays.

A trimmed definition: a high-card duel against the machine. The player holds three cards dealt by the server; each round they play one, against the machine's random rank:

```json
"tables": {
  "wallets": {
    "columns": { "user": { "type": "userId", "unique": true }, "coins": { "type": "int", "default": 0 } },
    "checks": { "coins_not_negative": "coins >= 0" },
    "rules": { "read": { "owner": "user" }, "create": "nobody", "update": "nobody", "delete": "nobody" }
  },
  "deck": {
    "columns": { "rank": { "type": "int" }, "copies": { "type": "int" } },
    "rules": { "read": "anyone", "create": { "role": "admin" }, "update": { "role": "admin" }, "delete": { "role": "admin" } }
  },
  "house": {
    "columns": {
      "level":  { "type": "int" },
      "stake":  { "type": "int" },
      "amount": { "type": "int" },
      "pair":   { "type": "int" }
    },
    "checks": { "amount_not_negative": "amount >= 0", "stake_positive": "stake > 0" },
    "rules": { "read": "anyone", "create": { "role": "admin" }, "update": { "role": "admin" }, "delete": { "role": "admin" } }
  },
  "matches": {
    "columns": {
      "player": { "type": "userId" },
      "level":  { "type": "int" },
      "status": { "type": "text", "default": "playing" },
      "round":  { "type": "int", "default": 1 },
      "stake":  { "type": "int" },
      "pair":   { "type": "int" },
      "put":    { "type": "int" },
      "pot":    { "type": "int" },
      "score":  { "type": "int", "default": 0 }
    },
    "checks": { "pot_not_negative": "pot >= 0" },
    "rules": { "read": { "owner": "player" } }
  },
  "hands": {
    "columns": {
      "match": { "type": "ref", "table": "matches", "onDelete": "cascade" },
      "owner": { "type": "userId" },
      "rank":  { "type": "int" },
      "used":  { "type": "bool", "default": false }
    },
    "rules": { "read": { "owner": "owner" } }
  },
  "rounds": {
    "columns": {
      "match":     { "type": "ref", "table": "matches", "onDelete": "cascade" },
      "number":    { "type": "int" },
      "player":    { "type": "userId" },
      "deadline":  { "type": "datetime", "optional": true },
      "status":    { "type": "text", "default": "open" },
      "submitted": { "type": "json", "optional": true },
      "timed_out": { "type": "json", "optional": true },
      "closed_at": { "type": "datetime", "optional": true },
      "settled":   { "type": "bool", "default": false },
      "machine_rank": { "type": "int", "random": { "int": [2, 14] },
                        "read": { "where": "status = 'closed'" } }
    },
    "unique": [["match", "number"]],
    "round": {
      "participants": ["player"], "deadline": "deadline", "status": "status",
      "submitted": "submitted", "timedOut": "timed_out", "closedAt": "closed_at",
      "moves": { "table": "moves", "round": "round", "participant": "player" }
    },
    "rules": { "read": { "owner": "player" } }
  },
  "moves": {
    "columns": {
      "round":  { "type": "ref", "table": "rounds", "onDelete": "cascade" },
      "player": { "type": "userId" },
      "card":   { "type": "ref", "table": "hands" },
      "rank":   { "type": "int" }
    },
    "unique": [["round", "player"]],
    "rules": { "read": { "owner": "player" } }
  }
}
```

`machine_rank` is the machine's move: filled by the server when the round is inserted, never by a request, and left out for the player until the round's `status` is `closed`. No table has a client `create`, `update` or `delete` rule, so rounds (and with them the fills) are inserted only by the actions below: nobody can insert rounds until they like the machine's card. The admin's settings page writes the `house` rows: `amount` = stake x the level's win factor, rounded; `pair` = stake + amount. `wallets` is as in the [`card-duel` template](https://dabadata.com/docs/turn-based/index.md#templates): one row per player, its id the user id, a check `coins >= 0`.

**Play: the match starts in one action.** Nobody has to accept: the house row is read with a `check` and its numbers are used through `$step`; the player pays round 1, the pot gets the stake and the house's share, the server deals the hand and opens round 1 (and draws the machine's rank for it):

```json
"play_machine": {
  "allow": "authenticated",
  "params": { "house": { "type": "ref", "table": "house" } },
  "steps": [
    { "op": "check", "table": "house", "id": "$params.house", "expect": { "stake": { "$gt": 0 } }, "ref": "h" },
    { "op": "update", "table": "wallets", "id": "$user.id",
      "expect": { "coins": { "$gte": "$step.h.stake" } }, "values": { "coins": { "$dec": "$step.h.stake" } } },
    { "op": "insert", "table": "matches", "ref": "m", "values": {
      "player": "$user.id", "level": "$step.h.level", "stake": "$step.h.stake", "pair": "$step.h.pair",
      "put": "$step.h.stake", "pot": "$step.h.pair" } },
    { "op": "draw", "pool": { "table": "deck", "value": "rank", "weight": "copies" }, "replacement": false,
      "count": 3, "for": ["$user.id"], "into": "hands",
      "values": { "match": "$step.m.id", "owner": "$each", "rank": "$pool" } },
    { "op": "insert", "table": "rounds", "values": {
      "match": "$step.m.id", "number": 1, "player": "$user.id", "deadline": { "$after": 30 } } }
  ]
}
```

**A move.** The same as against a person: the card is the player's own, unused, in this match; the `submit` records it once, before the deadline, and closes the round:

```json
"play_card": {
  "allow": "authenticated",
  "params": { "round": { "type": "ref", "table": "rounds" }, "card": { "type": "ref", "table": "hands" } },
  "steps": [
    { "op": "check", "table": "rounds", "id": "$params.round", "expect": { "status": "open" }, "ref": "r" },
    { "op": "check", "table": "matches", "id": "$step.r.match", "expect": { "status": "playing" } },
    { "op": "update", "table": "hands", "id": "$params.card", "ref": "h",
      "expect": { "owner": "$user.id", "used": false, "match": "$step.r.match" }, "values": { "used": true } },
    { "op": "submit", "table": "rounds", "id": "$params.round",
      "values": { "card": "$params.card", "rank": "$step.h.rank" } }
  ]
}
```

**Settle a round: guard, then the pot.** The client computes the round from the revealed `machine_rank` and its move, and sends the new score. One participant needs no [agreement](https://dabadata.com/docs/rules/index.md#agree): the guard is the action's first steps. The second one marks the round settled, so a second call for it fails (409, nothing changes). Then the match goes on: the next stake from the wallet, the stake and the house's share into the pot, the next round:

```json
"settle_machine_round": {
  "allow": "authenticated",
  "params": { "match": { "type": "ref", "table": "matches" }, "round": { "type": "ref", "table": "rounds" },
              "score": { "type": "int" } },
  "steps": [
    { "op": "check", "table": "matches", "id": "$params.match", "ref": "m",
      "expect": { "player": "$user.id", "status": "playing" } },
    { "op": "update", "table": "rounds", "id": "$params.round",
      "expect": { "match": "$params.match", "number": "$step.m.round", "status": "closed", "settled": false },
      "values": { "settled": true } },
    { "op": "update", "table": "wallets", "id": "$user.id",
      "expect": { "coins": { "$gte": "$step.m.stake" } }, "values": { "coins": { "$dec": "$step.m.stake" } } },
    { "op": "update", "table": "matches", "id": "$params.match", "ref": "m2",
      "expect": { "status": "playing", "round": "$step.m.round" },
      "values": { "score": "$params.score", "round": { "$inc": 1 },
                  "put": { "$inc": "$step.m.stake" }, "pot": { "$inc": "$step.m.pair" } } },
    { "op": "insert", "table": "rounds", "values": {
      "match": "$params.match", "number": "$step.m2.round", "player": "$user.id", "deadline": { "$after": 30 } } }
  ]
}
```

**The end: one action per outcome, no amount from the client.** The same two guard steps, then a win pays the whole pot and empties it. `settle_machine_draw` pays `$step.m.put` (the player's own stakes) and `settle_machine_loss` pays nothing; both empty the pot the same way, and what is left is the house's:

```json
"settle_machine_win": {
  "allow": "authenticated",
  "params": { "match": { "type": "ref", "table": "matches" }, "round": { "type": "ref", "table": "rounds" },
              "score": { "type": "int" } },
  "steps": [
    { "op": "check", "table": "matches", "id": "$params.match", "ref": "m",
      "expect": { "player": "$user.id", "status": "playing" } },
    { "op": "update", "table": "rounds", "id": "$params.round",
      "expect": { "match": "$params.match", "number": "$step.m.round", "status": "closed", "settled": false },
      "values": { "settled": true } },
    { "op": "update", "table": "wallets", "id": "$step.m.player", "values": { "coins": { "$inc": "$step.m.pot" } } },
    { "op": "update", "table": "matches", "id": "$params.match", "expect": { "status": "playing", "pot": "$step.m.pot" },
      "values": { "status": "over", "score": "$params.score", "pot": { "$dec": "$step.m.pot" } } }
  ]
}
```

The client side is the one of [player against player](https://dabadata.com/docs/turn-based/index.md#server-verified), with one caller: when the round closes, read the round (its `machine_rank` is now there) and your move, compute the result with your game code, and call `settle_machine_round`, or the end action your game code names. A player who left the tab open with no move times out at the deadline; their client (or their next visit) settles the round the same way.

### What a cheater can and cannot do against the machine

A player who rewrites their client **cannot**:

- see the machine's card before they choose: the column read rule leaves it out until the round is closed, in rows, live messages and the trace alike;
- choose or re-roll the machine's card: it is a server fill on insert, and rounds are inserted only by guarded actions;
- move late, move twice, or settle a round that is not closed, a future round, or a round already settled;
- settle another player's match, or touch another player's coins: every settle step expects `player = $user.id`, and their wallet is the only one the steps change;
- take more than the pot: the payout is the server's own `pot`, which holds only the stakes they paid and the house's shares of the rounds played; a check keeps it at zero or above, and the end empties it exactly;
- choose the house's share: it comes from the admin's table, read by the action, never from a param.

They **can**:

- claim to win every round of their own machine match and so take its pot - at most their own stakes plus the house's shares of the rounds they paid for. That is the whole risk, and it is bounded per match by the house table. Every match keeps its moves and the revealed machine cards, so you can replay matches afterwards with the same game code and flag an account whose claimed results do not match;
- never settle a round they lost: nothing is paid, and their stakes stay in the pot. Keep each player to one live match ([Many apps in one project](https://dabadata.com/docs/many-apps/index.md#live-match)) so such a match blocks their next one, and give your admins an action that ends a stale match;
- leave at any moment: the match ends, the house keeps the pot ([Leaving a match](https://dabadata.com/docs/turn-based/index.md#leave)).

So a modified client can at most take its own machine match's pot, never touch another player. If that bound is too much for your app - real money, or a house share you cannot afford to lose to a cheater - the result must be computed where no player can touch it: an [optional trusted worker](https://dabadata.com/docs/turn-based/index.md#server-authoritative).

## Server-verified (player against player)

The pattern for players against each other. The server deals the cards, draws each round's chance, keeps each player's hand hidden, runs the rounds and checks that a move is legal. Both clients run the same game code on the revealed moves, and the result is written only when they agree. This is how the Kidnapper's player-against-player matches run, with no process of ours or yours. A ready, complete version of this pattern is the [`card-duel` template](https://dabadata.com/docs/turn-based/index.md#templates). A trimmed definition:

```json
"tables": {
  "matches": {
    "columns": {
      "player_a": { "type": "userId" },
      "player_b": { "type": "userId" },
      "status":   { "type": "text", "default": "invited" },
      "round":    { "type": "int", "default": 1 },
      "score_a":  { "type": "int", "default": 0 },
      "score_b":  { "type": "int", "default": 0 }
    },
    "rules": { "read": { "any": [{ "owner": "player_a" }, { "owner": "player_b" }] } }
  },
  "deck": {
    "columns": { "card": { "type": "text" }, "copies": { "type": "int" } },
    "rules": { "read": "anyone" }
  },
  "hands": {
    "columns": {
      "match": { "type": "ref", "table": "matches", "onDelete": "cascade" },
      "owner": { "type": "userId" },
      "card":  { "type": "text" },
      "life":  { "type": "int", "default": 100 },
      "alive": { "type": "bool", "default": true }
    },
    "rules": { "read": { "owner": "owner" } }
  },
  "rounds": {
    "columns": {
      "match":     { "type": "ref", "table": "matches", "onDelete": "cascade" },
      "number":    { "type": "int" },
      "mover_a":   { "type": "userId", "optional": true },
      "mover_b":   { "type": "userId", "optional": true },
      "deadline":  { "type": "datetime", "optional": true },
      "status":    { "type": "text", "default": "open" },
      "submitted": { "type": "json", "optional": true },
      "timed_out": { "type": "json", "optional": true },
      "closed_at": { "type": "datetime", "optional": true },
      "pick_a": { "type": "ref", "table": "hands", "optional": true,
                  "random": { "where": "match = $row.match and owner = $row.mover_a and alive = true" } },
      "pick_b": { "type": "ref", "table": "hands", "optional": true,
                  "random": { "where": "match = $row.match and owner = $row.mover_b and alive = true" } }
    },
    "round": {
      "participants": ["mover_a", "mover_b"], "deadline": "deadline", "status": "status",
      "submitted": "submitted", "timedOut": "timed_out", "closedAt": "closed_at",
      "moves": { "table": "moves", "round": "round", "participant": "player" }
    },
    "rules": { "read": { "any": [{ "owner": "mover_a" }, { "owner": "mover_b" }] } }
  },
  "moves": {
    "columns": {
      "round":  { "type": "ref", "table": "rounds", "onDelete": "cascade" },
      "player": { "type": "userId" },
      "card":   { "type": "ref", "table": "hands" },
      "kind":   { "type": "text" }
    },
    "unique": [["round", "player"]],
    "rules": { "read": { "any": [
      { "owner": "player" },
      { "via": { "table": "rounds", "match": { "id": "$row.round" }, "where": "status = 'closed'" } }
    ] } }
  }
}
```

No table has a `create`, `update` or `delete` rule: clients change data only through actions (a `challenge` action, not shown, inserts the match with both players). Each player reads their own hand; a move is readable by its player at once and by everyone in the match when the round closes. `pick_a` and `pick_b` are filled by the server when a round is inserted: a random live card of each player (the game's "random card of the round", and the card a timed-out player plays).

**Start: deal.** The invited player accepts; one transaction marks the match as playing, deals five cards to each player from a finite deck and opens round 1 with a 30-second deadline:

```json
"accept_match": {
  "allow": "authenticated",
  "params": { "match": { "type": "ref", "table": "matches" } },
  "steps": [
    { "op": "update", "table": "matches", "id": "$params.match", "ref": "m",
      "expect": { "player_b": "$user.id", "status": "invited" }, "values": { "status": "playing" } },
    { "op": "draw", "pool": { "table": "deck", "value": "card", "weight": "copies" }, "replacement": false,
      "count": 5, "for": ["$step.m.player_a", "$step.m.player_b"], "into": "hands",
      "values": { "match": "$params.match", "owner": "$each", "card": "$pool" } },
    { "op": "insert", "table": "rounds", "values": {
      "match": "$params.match", "number": "$step.m.round",
      "mover_a": "$step.m.player_a", "mover_b": "$step.m.player_b", "deadline": { "$after": 30 } } }
  ]
}
```

**A move.** The check steps are the legality test: the match is still being played (a player may have [left](https://dabadata.com/docs/turn-based/index.md#leave) with the round still open), and the card is the caller's, alive and in this match. The `submit` step records it once, before the deadline, and closes the round when both are in. The move's `kind` comes from the server's row (`$step.h.card`), not from the client:

```json
"play": {
  "allow": "authenticated",
  "params": { "round": { "type": "ref", "table": "rounds" }, "card": { "type": "ref", "table": "hands" } },
  "steps": [
    { "op": "check", "table": "rounds", "id": "$params.round", "expect": { "status": "open" }, "ref": "r" },
    { "op": "check", "table": "matches", "id": "$step.r.match", "expect": { "status": "playing" } },
    { "op": "check", "table": "hands", "id": "$params.card", "ref": "h",
      "expect": { "owner": "$user.id", "alive": true, "match": "$step.r.match" } },
    { "op": "submit", "table": "rounds", "id": "$params.round",
      "values": { "card": "$params.card", "kind": "$step.h.card" } }
  ]
}
```

**The result: agreement.** When the round closes, both clients read the two moves (now revealed), compute the battle with the same code, and call `settle_round` with the same params. The `guard` runs on every call before anything is recorded: it accepts only the match's current round, once it is closed. The steps run once, when both submissions are in and equal:

```json
"settle_round": {
  "allow": "authenticated",
  "params": {
    "match": { "type": "ref", "table": "matches" }, "round": { "type": "ref", "table": "rounds" },
    "hands": { "type": "json" }, "score_a": { "type": "int" }, "score_b": { "type": "int" }
  },
  "agree": {
    "table": "matches", "id": "$params.match", "key": "$params.round",
    "participants": ["player_a", "player_b"], "wait": 20,
    "guard": { "steps": [
      { "op": "check", "table": "rounds", "id": "$params.round", "ref": "gr",
        "expect": { "match": "$params.match", "status": "closed" } },
      { "op": "check", "table": "matches", "id": "$params.match",
        "expect": { "status": "playing", "round": "$step.gr.number" } }
    ] },
    "onMismatch": { "steps": [
      { "op": "update", "table": "matches", "id": "$agree.id", "values": { "status": "disputed" } }
    ] }
  },
  "steps": [
    { "op": "check", "table": "rounds", "id": "$params.round", "ref": "r", "expect": { "status": "closed" } },
    { "op": "update", "table": "hands", "each": "$params.hands", "id": "$item.id",
      "expect": { "match": "$params.match" }, "values": { "life": "$item.life", "alive": "$item.alive" } },
    { "op": "update", "table": "matches", "id": "$params.match", "ref": "m",
      "expect": { "round": "$step.r.number", "status": "playing" },
      "values": { "score_a": "$params.score_a", "score_b": "$params.score_b", "round": { "$inc": 1 } } },
    { "op": "insert", "table": "rounds", "values": {
      "match": "$params.match", "number": "$step.m.round",
      "mover_a": "$step.m.player_a", "mover_b": "$step.m.player_b", "deadline": { "$after": 30 } } }
  ]
}
```

The key is the round row, so each round has its own agreement and a made-up key fails the guard (404 or 409, nothing recorded). The settle steps check the match's state again with `expect`, and they name players through the row (`$step.m.player_a`), never `$user.id`: whichever participant's call settles it is `$user` there. The last round is settled by a second action, `settle_end`, with the same `agree` (the same match, key and guard) and steps that end the match instead of opening a round; both clients call it when their game code says the match is over. Stakes and payouts belong in the same steps: take the stake into a pot on the match, pay out of the pot, and keep a check `pot >= 0` on the table, so that even two colluding accounts cannot create coins.

The client side:

```js
// Move.
await db.action("play", { round: roundId, card: cardId });

// Know when the round ends: live, and at the deadline (the server's clock).
db.subscribe("rounds", { where: { match } }, { onChange: ({ row }) => row.status === "closed" && onClosed(row) });
const round = db.round("rounds", roundId);
const st = await round.status();
setTimeout(() => round.status(), Date.parse(st.deadline) - Date.parse(st.now));   // closes it if nobody did

// Settle: the same params on both clients.
async function onClosed(row) {
  const moves = await db.query("moves", { where: { round: row.id } });
  const outcome = battle(row, moves);   // your game code, identical on both clients
  const { agreement } = await db.action("settle_round", { match, round: row.id, ...outcome });
  if (agreement.status === "waiting") {
    // The other player has not answered: call again when the wait is over.
    setTimeout(() => db.action("settle_round", { match, round: row.id, ...outcome }), Date.parse(agreement.until) - Date.now());
  }
}
```

## Optional: a trusted worker (server-authoritative)

**Most apps do not need this.** A machine that plays at random needs no backend ([a machine opponent with no backend](https://dabadata.com/docs/turn-based/index.md#machine)), and players against each other need none either. Use a worker only when your app needs trusted logic of its own: a machine that plays smart with information no client may hold (it reads the player's hand to choose), a secret no player may hold, or a result no client may compute because the value at stake is too high for the pot cap (real money). That logic runs in a trusted process of yours: a [**background worker**](https://dabadata.com/docs/workers/index.md) whose role may do just that and nothing else. It needs no loop and no public address. It signs in as a hosted user that holds the worker role (keys never open sockets) and keeps a [live subscription](https://dabadata.com/docs/live/index.md) to the matches and rounds against the machine; each change becomes a job on a queue its copies share. A job reads the round, chooses the machine's card, calls an action and ends. The machine's thinking time and the round's deadline are delayed jobs, not timers in a process, so any number of identical copies can run. If your backend already has a public HTTPS address, a [webhook](https://dabadata.com/docs/webhooks/index.md) on `rounds` can be the event source instead, with a [restricted key](https://dabadata.com/docs/projects/index.md#restricted) of the role for the writes ([Webhooks instead](https://dabadata.com/docs/workers/index.md#webhooks)).

The same definition, with two additions. The worker plays the machine's seat through an action only its role may call, naming the participant explicitly; the `expect` keeps it to the machine's seat:

```json
"roles": ["referee"],
"actions": {
  "machine_play": {
    "allow": { "role": "referee" },
    "params": { "round": { "type": "ref", "table": "rounds" }, "card": { "type": "ref", "table": "hands" } },
    "steps": [
      { "op": "check", "table": "rounds", "id": "$params.round", "expect": { "mover_b": "bot" }, "ref": "r" },
      { "op": "check", "table": "hands", "id": "$params.card", "ref": "h",
        "expect": { "owner": "bot", "alive": true, "match": "$step.r.match" } },
      { "op": "submit", "table": "rounds", "id": "$params.round", "participant": "$step.r.mover_b",
        "values": { "card": "$params.card", "kind": "$step.h.card" } }
    ]
  }
}
```

And it is the `authority` of the match's agreements: a caller who passes the authority rule settles alone, at once. Add it to `settle_round` and `settle_end`:

```json
"agree": {
  "table": "matches", "id": "$params.match", "key": "$params.round",
  "participants": ["player_a", "player_b"], "wait": 20,
  "authority": { "role": "referee" },
  "guard": { "steps": [ ... ] }
}
```

The worker computes each battle and calls `settle_round` as its own user; the player's client may call it too, and the authority's call decides. Every write is guarded (`expect`, `already_in`, `round_over`, `already_settled`), so a job that runs twice - a retry, or two copies of the worker seeing the same change - changes nothing. If the worker's credential leaks, it can play the machine's seat and settle matches - nothing else - and you disable that user (or revoke that key) alone. The [`card-duel-referee` template](https://dabadata.com/docs/turn-based/index.md#templates) is this pattern ready to use.

> **Note:** Server functions - your code run by dabadata in a sandbox - are not built yet (see [Not built yet](https://dabadata.com/docs/features/index.md#not-built)). Until they are, the trusted code of this pattern runs in a process of yours. [Background workers](https://dabadata.com/docs/workers/index.md) describes that process, the queue and the deployment, with an example worker kit from the repository.

## Lockstep (open information)

When every player sees everything and nothing is left to chance (chess, go, tic-tac-toe), there is nothing to hide and nothing to draw. Each turn is a round with one participant, the player to move; the server orders the turns, times them and stores every move. Every client computes the same position from the same ordered moves, and any dispute is settled by replaying them.

```json
"turns": {
  "columns": {
    "game":   { "type": "ref", "table": "games", "onDelete": "cascade" },
    "number": { "type": "int" },
    "mover":  { "type": "userId" },
    "other":  { "type": "userId" },
    "deadline": { "type": "datetime", "optional": true },
    "status": { "type": "text", "default": "open" }
  },
  "round": { "participants": ["mover"], "deadline": "deadline", "status": "status",
             "moves": { "table": "game_moves", "round": "turn", "participant": "player" } },
  "rules": { "read": { "any": [{ "owner": "mover" }, { "owner": "other" }] } }
},
"game_moves": {
  "columns": { "turn": { "type": "ref", "table": "turns" }, "player": { "type": "userId" }, "move": { "type": "text" } },
  "unique": [["turn", "player"]],
  "rules": { "read": "authenticated" }
}
```

```json
"move": {
  "allow": "authenticated",
  "params": { "turn": { "type": "ref", "table": "turns" }, "move": { "type": "text" } },
  "steps": [
    { "op": "check", "table": "turns", "id": "$params.turn", "expect": { "mover": "$user.id" }, "ref": "t" },
    { "op": "submit", "table": "turns", "id": "$params.turn", "values": { "move": "$params.move" } },
    { "op": "update", "table": "games", "id": "$step.t.game", "values": { "turns": { "$inc": 1 } }, "ref": "g" },
    { "op": "insert", "table": "turns", "values": {
      "game": "$step.t.game", "number": "$step.g.turns",
      "mover": "$step.t.other", "other": "$step.t.mover", "deadline": { "$after": 300 } } }
  ]
}
```

The submit closes the turn at once (its only participant is in), and the next turn opens for the other player in the same transaction. The server does not know the rules of chess, so it cannot refuse an illegal move; the other client does, by replaying. End the game with an action that both clients call with the result, settled by [agreement](https://dabadata.com/docs/rules/index.md#agree); a client that replays an illegal move disagrees, and the dispute handles it. A player who lets the clock run out times out: the opponent's client sees it in the turn's status and claims the game the same way.

## Commit-reveal (a building block)

Rounds already keep a move hidden from the other players until the round closes. Commit-reveal goes further: the move stays secret even from the server until everyone is in. dabadata has **no commit-reveal feature**; you build it with two rounds and a hash column, and the clients do the checking:

1. **Commit round.** Each player submits `{ hash }`, where `hash = sha256(move + salt)` computed on their device with a fresh random salt. The hash may be readable by everyone at once.
2. **Reveal round.** Opened when the commit round closes; each player submits `{ move, salt }`.
3. **Check and settle.** Every client recomputes each player's hash from the revealed move and salt and compares it with the commitment, then settles by [agreement](https://dabadata.com/docs/rules/index.md#agree). A mismatch, or a player who does not reveal before the deadline, is the game's to decide (usually: that player loses the round).

The server never verifies the hash: declarative steps compute no sha256. The guarantee comes from the agreement - an honest client refuses a result built on a reveal that does not match. The same two rounds give lockstep games a shared random seed nobody chose: each player commits a random value, and after the reveal the seed is a hash of all of them. Do not use that for a hidden deck: every client can compute it. Hidden draws belong to the server ([`draw`](https://dabadata.com/docs/rules/index.md#draw), [fills](https://dabadata.com/docs/tables/index.md#fills)).

## Leaving a match: end it at once

A player may want to leave at any moment: while choosing, with both moves in, while a battle plays on screen, between rounds. Make leaving one action that ends the match in one transaction, not a flag that the other player's client or a worker must notice later:

- **The match is over now.** The leaver takes a loss and is free for a new match.
- **The pot goes to the other side:** to the other player, or, against a machine, to the house.
- **Nothing waits.** No round is settled and no agreement is waited for. The round may stay open; what comes after is refused by the guards already in place: a move checks that the match is still being played ([the `play` action](https://dabadata.com/docs/turn-based/index.md#server-verified)), every settlement's `guard` expects it too, so a late move or settlement answers 409 and records nothing. If your app runs a [worker](https://dabadata.com/docs/turn-based/index.md#server-authoritative), its job that then finds the match over does nothing.
- **A race is safe.** The leave's last step expects the status and the pot it read; a settlement expects the match to be playing. Transactions are serializable, so when both run at once one of them fails as a whole and nothing is paid twice.
- **One action per seat.** Steps cannot branch on who the caller is, so declare `leave_a` (it expects `player_a` to be the caller and pays `player_b`), `leave_b` the other way round, and one for a match against the machine that pays nobody. The page calls the one for its seat.

```json
"leave_a": {
  "allow": "authenticated",
  "params": { "match": { "type": "ref", "table": "matches" } },
  "steps": [
    { "op": "check", "table": "matches", "id": "$params.match", "ref": "m",
      "expect": { "status": "playing", "player_a": "$user.id" } },
    { "op": "update", "table": "wallets", "id": "$step.m.player_b", "values": { "coins": { "$inc": "$step.m.pot" } } },
    { "op": "update", "table": "matches", "id": "$params.match", "expect": { "status": "playing", "pot": "$step.m.pot" },
      "values": { "status": "over", "winner": "b", "reason": "left:a", "pot": { "$dec": "$step.m.pot" } } }
  ]
}
```

`wallets` is as in the [`card-duel` template](https://dabadata.com/docs/turn-based/index.md#templates): one row per player, its id the user id. Against the machine, pay the pot into the house's wallet if your app keeps one (the `card-duel-referee` template does), or, when the house keeps no balance, drop the payment step and just empty the pot. Record the loss, the win and a ledger row in the same steps if your app keeps them. The Kidnapper does this with `withdraw_a`, `withdraw_b` and `withdraw_machine` (`examples/kidnapper/kidnapper.ts`), which also clear each player's one live match ([Many apps in one project](https://dabadata.com/docs/many-apps/index.md#live-match)).

## Start from a template

Two curated templates are complete, tested definitions of the patterns above. Pick one when you create a project in the console, or send `"template": "<slug>"` with `POST /v1/workspaces/:id/projects`; `GET /v1/templates` lists them ([Start from a template](https://dabadata.com/docs/agents/index.md#templates)).

| Pattern | Start from | What it holds |
| --- | --- | --- |
| [A machine opponent with no backend](https://dabadata.com/docs/turn-based/index.md#machine) | `card-duel`, changed | No template of its own yet. Keep the wallets, the deck, the hands and `play`; add the `house` table and the machine's hidden fill on `rounds`; replace the challenge and the agreements with `play_machine`, `settle_machine_round` and one end action per outcome, as in the [example above](https://dabadata.com/docs/turn-based/index.md#machine). |
| [Server-verified](https://dabadata.com/docs/turn-based/index.md#server-verified) | `card-duel` | A high-card duel of 3 rounds. `open_wallet` (100 coins, once), `challenge` and `accept` (stakes into the match's pot; 3 cards each, their values random fills hidden from the other player), `play` (your own unused card of this match, before the 60-second deadline), moves revealed at the close, `settle_round` and `settle_end` by agreement (`wait` 30 s; a mismatch voids the match and returns the stakes). The payout comes out of the pot and must empty it exactly, so no agreement can create coins. |
| [Optional: a trusted worker](https://dabadata.com/docs/turn-based/index.md#server-authoritative) | `card-duel-referee` | The same duel plus a machine seat (`"bot"`) and a trusted [worker](https://dabadata.com/docs/workers/index.md) with the role `worker`: a hosted user with that role holding a live subscription, or a [restricted key](https://dabadata.com/docs/projects/index.md#restricted) of that role behind a webhook. It plays the machine with `machine_play` (only the machine's seat and cards) and is the agreements' `authority`, so it settles alone. `challenge_machine` takes the machine's stake from the house wallet, which you open and fund with the secret key (`open_house`, `fund_house`). No worker code is included: the worker reacts to each change of `rounds` (from its subscription or a webhook), plays, calls the round's status at the deadline and settles. |
| [Lockstep](https://dabadata.com/docs/turn-based/index.md#lockstep) | `card-duel`, changed | No template of its own. Keep the wallets, the pot and the settle actions; drop `hands` and the deal; make each turn a round with one participant (the player to move) and open the next turn in the move action, as in the [lockstep](https://dabadata.com/docs/turn-based/index.md#lockstep) example. |
| [Commit-reveal](https://dabadata.com/docs/turn-based/index.md#commit-reveal) | `card-duel`, changed | No template: it is not a feature. Use two rounds per move (a `hash` column, then the move and its salt) and let the clients check the hash before they settle, as described [above](https://dabadata.com/docs/turn-based/index.md#commit-reveal). |

The clients' rules of the duel are in each template's description: the higher card scores a point, a player who timed out scores nothing for that round, and after round 3 both clients call `settle_end` with the scores and a payout (`pay_a + pay_b` = the pot).

## Time without a loop: the lazy close

Nothing on the server wakes up at a round's deadline. A round closes in one of three ways, all inside a call someone makes anyway:

- **Early:** the last participant's submit closes it, in the same transaction.
- **At the deadline, by a status call:** `GET /v1/rounds/<table>/<id>` (`db.round(table, id).status()`) after the deadline closes an open round first and marks the participants not in as timed out. The clients know the deadline, so each sets a timer and calls status when it comes; the first call closes the round.
- **By a late submit:** it closes the round and answers `409 round_over` with the closed status.

The close is an ordinary update of the round row, so a [live](https://dabadata.com/docs/live/index.md) subscriber gets the closed round like any change, and read rules written on `status = 'closed'` reveal the moves at that moment. Agreements complete the same way: a call after the `wait`, by anyone in it, settles or disputes a waiting agreement. Use the `now` of a status answer, not the device's clock, to time the call: phones drift.

## Pitfalls

- **A guard on every agreement that moves value.** Without `agree.guard`, a participant can submit for a key long before it is due - so its `wait` starts early and runs out while the other player is still playing - or submit for a made-up key and settle it alone once the wait is over. Guard with check steps that accept only the current round, closed, of a match still being played; a failing guard records nothing.
- **No `$user.id` in settled steps.** The steps of an agreement run in the call that settles it, so `$user` is whichever participant (or the authority) made that call. Name players through the row: `$step.m.player_a`.
- **Moves are final.** Once submitted, a move cannot be updated or deleted by end users, restricted keys or action steps (400); only the secret key and the console may, as repairs. Do not design a "change my move" action.
- **Params must be computed identically on every client.** Submissions are compared as canonical JSON of the validated params: key order does not matter, everything else does. Use integers (no `0.1 + 0.2`), no timestamps or device-local values, the same game code version on every client (put a version in the params if it may differ), and round the same way everywhere.
- **Canonical order.** Arrays compare in order. Sort every list you send (cards by id, players by seat), and apply the moves of a round in a fixed order (seat a, then seat b), never in the order they arrived.
- **Waiting and absent players.** After `wait` seconds, the submissions present settle alone if they agree with each other - so a player whose tab closed is settled by the other player's client. That keeps a match moving, and it means a settlement must never be able to do more harm than the game allows: bound it with `expect` (this match's cards, this round), checks (a pot that cannot go below zero) and fixed steps. Choose `wait` long enough for a slow phone to answer.
- **Disputes.** A cheater can always disagree. The `onMismatch` steps must leave them no better off than an honest end: return the stakes, void the match, flag it for review - never pay the side that disputed.
- **No amounts from the client against the machine.** A settlement the player sends alone must not name what it pays: pay the server's own numbers (`$step.m.pot`, the player's stakes), one action per outcome, and fill the pot only in the server's steps from a table only admins write. Then a modified client can at most take its own match's pot.
- **Re-rolling.** A random fill runs on every insert. If a client could insert rounds or hands itself, it could insert until it liked the result. Insert them only in actions, guarded by `expect` (the match is playing, this is the current round).
- **Keep the trace closed to players.** Filled values and moves are traced like any write. The trace leaves out columns a reader may not read, but a `trace.read` open to players can still show them other players' rows and when a move was made. Leave `trace.read` to the developer (the default) or an admin role in any game with hidden information.
- **Retries are safe.** Submitting the same agreement again answers its status and records nothing twice; a second move in a round is refused (409 `conflict`, `already_in`). A client may retry after a network error without harm.
