---
title: "Games · Apphaven"
description: "What a game is built from: saves, scores, daily challenges, tables with turns, hidden hands, and what isn't available."
url: "https://apphaven.com/docs/agent/games/"
---

# Games: what to build them from

Apphaven has no game engine and nothing made for games. A game is an ordinary app: a page that
draws and plays, records for what must outlast the tab (saves, scores, tables), rules for whose
they are, operations for the writes the server should guard, and realtime so players see each
other's moves. This topic says which parts to combine and where the edges are; the parts
themselves are in `config` (with "logic"), `sdk` and `realtime`.

**The game runs in the page, never on the server.** The server stores records, applies rules
and validations to each write, and passes messages. It doesn't know the game's rules, so what a
page sends (a score, a board, a move) is that page's claim, bounded only by what the config checks.

## The shape of a game app

- A Vite app, or plain files for something small; canvas or DOM, as the game needs. Make it
  installable (overview, "Make it installable") so it opens full screen from the home screen.
- Art and sound are workspace files. Bulk assets (sprites, levels, music) go in a static folder
  (`frontend.static: [assets]`, or `uploads/` for what the owner adds), referenced by address
  (`/assets/ship.png`) and never imported; 25 MB a file. Import only the few the game can't
  start without, so the build carries them.
- Offline: the installable recipe's service worker keeps the built app opening without a
  connection, and `/api` and `/_apphaven` never go through it. So a solo game plays offline
  from what the page holds; sign-in, saves, scores and realtime wait for the connection. The SDK
  keeps no queue of unsent writes, and static folders aren't in the build, so they load from the
  network unless the worker is told to cache them.

## Saves and progress

```yaml
models:
  Save:
    fields:
      player: { type: user, default: $user.id, readonly: true, required: true, unique: true }   # one each
      level: { type: integer, default: 1, min: 1 }
      progress: json        # whatever the game needs to resume
    access: { read: player == $user.id, create: $user != null, update: player == $user.id, delete: player == $user.id }
```

```js
let save = JSON.parse(localStorage.getItem("save") ?? "null") ?? { level: 1, progress: {} };
let record = null;
app.auth.onChange(async (user) => {
  if (!user) return (record = null);                       // signed out: this device only
  const { items } = await app.db.Save.list({ limit: 1 });  // the rule leaves only theirs
  record = items[0] ?? (await app.db.Save.create(save));   // first sign-in: what they played comes along
  save = { level: record.level, progress: record.progress };
});
async function checkpoint() {                              // a level cleared, a pause: not every frame
  localStorage.setItem("save", JSON.stringify(save));
  if (record) await app.db.Save.update(record.id, save).catch(() => {});   // offline: the next one sends it
}
```

Signed out, a visitor has no identity: `$user` is null, no record can be theirs, and there are
no guest accounts. Let them play from `localStorage` and offer sign-up when there is something
worth keeping (a score to post, a streak).

## Scores and leaderboards

Close the model to direct writes and take scores through one operation, so each passes the
same checks.

```yaml
models:
  Score:
    fields:
      player: { type: user, default: $user.id, readonly: true, required: true }
      points: { type: integer, required: true, min: 0, max: 100000 }
      seconds: { type: integer, required: true, min: 5, max: 3600 }   # how long the run took
    indexes: [[points]]
    access: { read: true }
operations:
  submitScore:
    model: Score
    action: create
    input: [points, seconds]
    access: $user != null
    validate:
      - { check: points <= seconds * 50, message: That score isn't possible in that time. }
      - check: count(Score, player == $row.player && created_at > dateadd($now, -1, 'minutes')) <= 6
        message: Slow down a little.
```

```js
try { await app.ops.submitScore({ data: { points, seconds } }); }
catch (e) { if (e.status === 400 || e.status === 422) show(e.message); else throw e; }

const runs = await app.db.Score.list({ sort: "-points", limit: 10, expand: ["player"] });   // the top runs
const best = await app.db.Score.aggregate({ group_by: ["player"], max: ["points"], sort: "-max_points", limit: 10, expand: ["player"] });   // one row a player
const { items: [mine] } = await app.db.Score.aggregate({ max: ["points"], filter: "player == $user.id" });   // mine?.max_points
```

- `expand` on a user field gives `{ id, name, image }`, never the email: a public board shows
  the names people signed up with. Tell the owner.
- **The server can check** who the player is (`default: $user.id`, `readonly`), ranges (`min`,
  `max`), one a day (`unique`, next section), a rate (the `count` check), that the numbers sent
  agree with each other, and its own clock: `created_at` is the server's, so a run that starts
  as a record and is finished by an update operation whose `validate` compares `$now` with
  `created_at` can't claim a time shorter than it took.
- **It can't check** that the game was played. Someone who reads the page's code can send any
  score the checks allow. Tight bounds make cheating dull, not impossible; a board with prizes
  needs an owner who looks at it (the dashboard's Data page) and deletes.
- A signed-out entry (a typed name, `access: true`) belongs to nobody, and anyone can post as
  anyone. Rank only signed-in players.

## A daily challenge

One puzzle a day for everyone, one result a player. `today()` is the day in `app.timezone`, the
same for every player; the page's clock is the device's.

```yaml
app:
  timezone: Europe/London
models:
  Puzzle:
    fields:
      day: { type: date, required: true, unique: true }
      clue: { type: string, required: true }
    access: { read: "day <= today('Europe/London')", write: $user.role == 'admin' }   # tomorrow's stays hidden
  Result:
    fields:
      player: { type: user, default: $user.id, readonly: true, required: true }
      day: { type: date, default: = today(), readonly: true, required: true }
      tries: { type: integer, required: true, min: 1, max: 6 }
      solved: { type: boolean, required: true }
    unique: [[player, day]]          # a second result that day answers 409 conflict
    access: { read: true, create: $user != null }
operations:
  today:
    model: Puzzle
    action: get
    where: day == today('Europe/London')   # in a rule or an operation's where, give today() the zone
    access: true
```

```js
const puzzle = await app.ops.today();                    // 404 not_found: nobody loaded one for today
const { items } = await app.db.Result.list({ filter: "player == $user.id", sort: "-day", limit: 200 });
const prev = (d) => new Date(Date.parse(d) - 86400000).toISOString().slice(0, 10);
let streak = 0, day = items[0]?.day;                     // days the server stamped, newest first
for (const r of items) { if (r.day !== day || !r.solved) break; streak++; day = prev(day); }
```

An automation on a schedule can make tomorrow's puzzle (`on: schedule`, `every: 1 day`,
`at: "00:05"`: `logic`, "Automations"), from records an admin loaded ahead: a step can't make
random values, so it picks, it doesn't invent. Or someone loads puzzles ahead (an
admin screen, or you with `insert_records`), or the page builds the puzzle from the day with a
seeded generator and no Puzzle record; then the answer is in the page's code for anyone who
looks. The streak comes from stored results, whose days the server stamps, so a day can't be
typed in; whether each was solved is still the page's claim. It is alive while the newest day
is today's or yesterday's.

## Rooms and tables

A table is a record, and its channel is that record. Seats say who plays; row-level rules make
the table its players'. The page makes the short code (formulas have no random); `unique`
refuses a taken one.

```yaml
models:
  Game:
    fields:
      code: { type: string, required: true, unique: true, pattern: "^[A-Z]{5}$" }
      host: { type: user, default: $user.id, readonly: true, required: true }
      status: { type: enum, values: [lobby, playing, over], default: lobby }
      turn: user                                              # whose move it is
      version: { type: integer, default: 0, readonly: true }  # goes up with every move
      board: json
    access:
      read: host == $user.id || exists(Seat, game == $row.id && player == $user.id)
      create: $user != null
  Seat:
    fields:
      game: { type: Game, required: true }
      player: { type: user, default: $user.id, readonly: true, required: true }
    unique: [[game, player]]
    access:
      read: game.host == $user.id || exists(Seat, game == $row.game && player == $user.id)
      delete: player == $user.id
    validate:
      - { check: "count(Seat, game == $row.game) <= 4", message: This table is full., on: [create] }
operations:
  join:              # someone not seated yet can't read the Game, so steps (run as the owner) find it by code
    model: Seat
    action: create
    access: $user != null
    params: { code: string }
    steps:
      - id: game
        lookup: { model: Game, where: code == upper($params.code) && status == 'lobby', limit: 1 }
      - if: $steps.game.count == 0
        stop: No open table has that code.
      - create: { model: Seat, set: { game: = first($steps.game.rows.id), player: = $user.id } }
    respond: { game: = first($steps.game.rows.id) }
  start:
    model: Game
    action: update
    params: { id: string }
    input: [board]
    access: $user != null
    where: id == $params.id && host == $user.id && status == 'lobby'
    set: { status: playing, turn: $user.id, version: = version + 1 }
```

```js
const code = Array.from(crypto.getRandomValues(new Uint8Array(5)), (b) => "ABCDEFGHJKLMNPQRSTUVWXYZ"[b % 24]).join("");
await app.db.Game.create({ code });                      // 409 conflict: taken, make another
const { game: gameId } = await app.ops.join({ code });   // the host sits down like everyone else
// The link to share is `/?join=${code}`: that page signs the person in, then calls join.
// join answers 422 (no such table, or full: show e.message) or 409 (already seated).

const table = app.realtime.channel(`Game:${gameId}`);
table.on("change", { model: "Game" }, async () => { game = await app.db.Game.get(gameId); render(); });
table.on("change", { model: "Seat" }, loadSeats);        // app.db.Seat.list({ filter: filter`game == ${gameId}`, expand: ["player"] })
table.on("presence", ({ members }) => showWhoIsHere(members));   // { key, user, state }, one per open page
table.on("status", (s) => { if (s === "resync") reload(); });
await table.subscribe({ presence: { name: me.name } }).catch(() => {});
await reload();
```

Row-level rules mean change events arrive without the record, and the page fetches it
(realtime, "Changes"). Presence is who has the table open now, not who is seated: two tabs are
there twice, a seated player with the page closed not at all. A quiz night is the same shape:
the host's page moves a `question` number on the Game, and each player's page follows the change
and creates one Reply (`unique: [[game, question, player]]`).

Two things that catch people out here:

- Records made by the steps of one operation share one `created_at`, so "the order people sat
  down" needs a tie-break (`sort: "created_at,id"`) or an order you store yourself.
- An operation whose only guard is a row-level rule (`access: exists(Seat, …)`, or the check in
  `where`) answers a signed-out caller 200 with `count: 0`, not 401. Put `$user != null` in
  `access` when the page should be told to sign in.

## Turns that can't cross

Two pages can send a move at the same moment. Guard the write in the operation's `where`, so
it applies only if the record is still as the page last saw it:

```yaml
operations:
  move:
    model: Game
    action: update
    params: { id: string, version: integer }
    input: [board, turn]
    access: $user != null && exists(Seat, game == $row.id && player == $user.id)
    where: id == $params.id && status == 'playing' && turn == $user.id && version == $params.version
    set: { version: = version + 1 }
    validate:
      - check: changed(turn) && exists(Seat, game == $row.id && player == $row.turn)
        message: Pass the turn to another player at the table.
    push: { to: turn, title: Your turn, url: "/?game={{ id }}", tag: "turn-{{ id }}" }
```

```js
async function play(board, next) {
  const { count } = await app.ops.move({ id: game.id, version: game.version, data: { board, turn: next } });
  if (count === 0) { game = await app.db.Game.get(game.id); render(); }   // someone moved first, or it isn't your turn
}
```

- `count: 0` is not an error: the `where` matched nothing and nothing was written. Fetch, draw,
  and let the player move again only if it is still their turn. A 409 is a `unique` value
  taken; a 422 is a `validate` check or a `stop`.
- Structured state goes in a `json` field: objects and arrays, at most 200,000 characters as
  JSON (a whole request, 1 MB). Rules, filters, validations and computed fields can't look
  inside json, only test it against null. So what the server must guard gets a field of its own
  (`turn`, `status`, `version`, a score), and the json is the page's claim about the rest.
- The server here guards whose turn it is and that it passes to a seated player. It can't tell a
  legal move from an illegal one: each page should check the board it receives against the
  game's rules and show a problem rather than play on. A record per move (a Move model pointing
  at the Game) gives a history to check and replay. Ending the game is one more operation of
  the same shape (`set: { status: over }`).

## Hidden information

Everything a page can read, its player can read. What a player mustn't see goes in a record
they can't read:

```yaml
models:
  Hand:
    fields: { game: { type: Game, required: true }, player: { type: user, required: true }, cards: json }
    unique: [[game, player]]
    access: { read: player == $user.id, create: game.host == $user.id, update: player == $user.id }
  Answer:                                  # a quiz or puzzle answer no page ever reads
    fields: { puzzle: { type: Puzzle, required: true, unique: true }, word: { type: string, required: true } }
    access: { write: $user.role == 'admin' }
operations:
  guess:
    model: Answer
    action: get
    access: $user != null
    params: { puzzle: string, word: string }
    steps:
      - id: answer
        lookup: { model: Answer, where: puzzle == $params.puzzle, limit: 1 }
      - if: $steps.answer.count == 0
        stop: There's no such puzzle.
    respond: { correct: = first($steps.answer.rows.word) == lower(trim($params.word)) }
```

- Realtime never carries a row-level record: people on `Game:abc` learn that a Hand with
  `game: abc` changed and when, not what it holds, and each page fetches its own.
- Steps run as the owner, so `guess` compares with an answer the caller can't read and hands
  back only what `respond` names. Store answers as the comparison reads them (lowercase here).
- Whoever deals knows the deal: above, the host's page creates each Hand, so the host could
  look. Nothing on the server shuffles (below). Among friends, say who deals; a card game among
  strangers for stakes isn't something to build here.

## Fast interaction

`channel.send(event, payload)` is for what nobody needs to keep: a cursor, a reaction, a
position. It reaches the others on the channel, not the sender, and is never stored or
replayed, so a page that joins a moment later never sees it. `from` is the sender's user id, set
by the server; the payload is the sender's claim. A page sends at most 20 frames a second (a
burst of 40), each payload at most 8 KiB.

**There is no server game loop**: nothing on the server ticks, simulates or decides a
collision, so fast multiplayer with server physics is out. What works:

- turn-based play and answer-at-once rounds, through records, at any pace;
- a host-run game: the host's page runs the simulation, the others send inputs as broadcasts
  and draw the state the host broadcasts about ten times a second, with a record written at
  checkpoints so a reload resumes. Every message makes two trips through the server, the host
  can cheat, and the game stops when the host's page closes: fine for a party game in one room.

## While nobody is looking

Automations start on a record's change, a sign-up, by hand, on a Stripe event or on a schedule
(`on: schedule` with `every: 1 day` and `at: "00:00"`, in the app's time zone; 15 minutes is the
shortest), and a step can `wait` from 1 second to 30 days. A schedule runs in the live app only:
in a test version, start it with `run_automation`.

```yaml
automations:
  turn_timer:
    description: Ends a game when a player hasn't moved for two days.
    on: Game.updated
    where: changed(version) && status == 'playing'
    steps:
      - id: seen
        lookup: { model: Game, where: id == $row.id, limit: 1 }
      - wait: { for: 2 days }
      - update:
          model: Game
          where: id == $row.id && status == 'playing' && version == first($steps.seen.rows.version)
          set: { status: over }
```

- The same version guard: if anyone moved during the wait, the update matches nothing. Every
  move starts a run (at most 300 a minute and 10,000 a day per environment), and a run's own
  write to its record doesn't start the same automation again. Right for a correspondence game,
  wrong for a ten-second clock.
- A short clock: store a `deadline` (`set: { deadline: "= dateadd($now, 2, 'minutes')" }`; minutes
  are the smallest unit) and give seated pages an operation with `where: … && deadline < $now`
  to call when it runs out. The clock is the server's; the trigger is a page, so it fires only
  while someone has the table open.
- Bots: steps are formulas, lookups and writes, 12 at most, with no loops over a board. A bot
  that reads the board is played by a page (the host's), or by a web service of the owner's that
  a `call` step reaches (config, "Web requests").

## Telling someone it's their turn

- **In the app:** a write that sets a `user` field is also published on that person's own
  channel, so a page on `user:<my id>` hears every Game whose `turn` became them (the event has
  the model and id; fetch the record).
- **On the phone:** `push:` on the operation, as in `move`, reaches the devices where that player
  turned notifications on with `app.push.enable()`, from a tap (sdk, "Notifications on the
  phone"); on an iPhone only once the app is on the home screen. The `tag` makes a newer "your
  turn" replace the last. Someone with no device gets nothing, and that isn't an error.
- **By email**, for slow games: `email: { to: turn, subject: Your turn, body: … }` on the same
  operation. An address nobody confirmed gets at most 5 messages an hour, and a new live app
  sends 100 a day (config, "Sending email from an operation").

## Randomness and fairness

Formulas have no random function, and no step makes a random value.

- Solo play: the page's own `Math.random()` or `crypto.getRandomValues()`.
- The same for everyone: a `seed` in the record (the host's page picks it) and one seeded
  generator in every page. Anyone at the table can then work out what comes next: right for a
  shared board, wrong for hidden cards.
- A roll nobody chose: a record a page creates gets its `id` from the server, at random, and
  the page can't set it. Create a record per roll (`unique: [[game, turn_number]]`, so nobody rolls twice) and let
  every page derive the number from that id.
- Hidden and random together (a shuffled deck) needs someone to shuffle, and they know the order.

## Limits that shape a design

| What | Limit |
| --- | --- |
| Writes by someone signed out | 20 a minute per network address, per app: every `POST`, `PATCH` and `DELETE` to a model or operation. `app.ops` always sends `POST`, so read signed out with `app.db` |
| Any API request | 300 in 10 seconds per network address, per app, signed in or not; a room of players on one Wi-Fi shares this and the limit above |
| A list | 50 records by default, 200 at most (`offset` for more); `aggregate` 100 by default, 1,000 at most |
| A value | `string` 2,000 characters, `text` and `json` 200,000; a request body 1 MB |
| Realtime | 20 frames a second per page, 8 KiB a broadcast, 1 KiB of presence state, 20 channels a page, about 2,000 open pages per app; missed changes replay for about ten minutes |
| Steps | 12 in an operation or automation, 200 records in a `lookup` or `each`, 60 seconds for an operation |
| Automations | 300 runs a minute, 10,000 a day per environment; a `wait` of 1 second to 30 days |

Usage is what the owner pays for once the app is live, and a game draws it with every request
(API calls and the files a page loads), the database's work, each realtime frame a page sends
and each change sent to open pages, automation steps (20 to a unit), email (half a unit a
recipient), each push, and what the app keeps. A game that broadcasts ten times a second from
every player draws usage for as long as anyone plays; a turn-based one draws almost nothing
between moves. Don't poll where a channel would do, and don't promise a player count:
`app_status` shows what the app draws.

## Testing a game

- `view_page` steps click, fill and press keys by CSS selector; they can't click a point inside
  a canvas or drag. Give the game keyboard or button controls, and write what matters (score,
  whose turn, "Game over") into the page as text, so steps can drive it and the result shows.
- One call proves what one player sees: play, checkpoint, then a new call to see the save
  persisted; a score outside the bounds shows its message; signed out, the game still plays.
- Two players' **stored** state works across calls: `as: "alice"` makes a table and moves, then
  `as: "bob"` in a second call joins by the code, finds the board as alice left it, and his move
  out of turn changes nothing. That proves the rules and the turn guard.
- It doesn't prove a move reached another open page: each call closes its browser, so that
  needs two sessions open at once as different players (realtime, "Testing it"). When you can't,
  tell the owner the live update is unverified and ask them to try it with a friend.
- `run_tests` covers a private creator-owned model (Save: `owner_field: "player"`, a fixture of
  `level` only), not operations, sockets, json, or models with required links (Seat, Hand).
  Check automations with `list_runs` and pushes with `get_logs` (`PUSH` lines).

## An app that began as a game shell

An app made from a draft at apphaven.com may already hold one of two shells, built from the
parts above. The shell is a page element Apphaven serves; the game inside it is a file of the
app's own, which is where your work goes. Read the file first: its opening comment is the
contract.

- **`<ah-game>` and `games/solo.js`**: one player, rounds and a score. The shell draws Play,
  the score and the clock, the end of a round and the best scores, and saves a score through
  `submitScore` (model `GameScore`: signed in, 0 to 1,000,000, 120 an hour; the page saves a
  round only when it beats that player's best). The file exports
  `start({ stage, settings, score, time, end, signal })`: draw in `stage`, report with
  `score(n)` and `time(s)`, finish with `end(n)`, and stop when `signal` aborts.
- **`<ah-gametable>` and `games/table.js`**: two to six players in turns. The shell opens a
  table with a code and a link, seats people, shows who is here, and sends each move through
  `playTurn`, which takes it only from the player whose turn it is and only at the `version`
  they last saw (models `GameTable` and `GameSeat`; the page hears moves on `GameTable:<id>`).
  The file exports `setup({ seats })`, `apply(state, move, seat, seats)` returning
  `{ state, next, over, winner }`, `draw({ stage, state, seats, me, myTurn, play })` and
  optionally `bot(state, seat)`. A table and its seats are read only by its host and the people
  seated, and a seat is taken by the code (`takeSeat`). The state is json everyone at the table
  can read: a hand or a
  hidden answer needs a model of its own, as under "Hidden information".

Replace the stand-in game in that file and leave the element, the models and the operations as
they are: their names are what the shell calls. Take out the page's line that says the game is
a stand-in (`pc-game-standin`). Change the words people read on the page in its
HTML (`words`, the heading, "How to play"), and style what the game draws in `style.css`. When
the owner's game needs more than the shell gives (a daily puzzle, a private hand, a turn clock),
add models and operations beside the shell's, or build the page yourself from the parts above
and remove the element.

## What to build it from, and what isn't here

| You want | Build it from |
| --- | --- |
| Progress that follows the player | a Save record per player; `localStorage` until they sign up |
| A leaderboard | a Score model written by one operation with `validate`; `list` or `aggregate` with `expand` |
| One go a day, streaks | a `date` field with `default: = today()` and `unique: [[player, day]]`; the streak from stored results |
| A room with a code or a link | a Game record with a `unique` code the page makes; a `join` operation with steps |
| Seats and who is here | a Seat model with a `count` check; presence on the Game's channel |
| Moves that can't collide | an update operation guarded by `version` (or `turn`) in `where`; `count: 0` means look again |
| A hand, a secret answer | a model only its player reads; an operation with steps that compares and answers yes or no |
| Cursors, reactions, positions | `channel.send`, within 20 frames a second and 8 KiB |
| A turn clock | an automation that waits, then updates under the version guard; or a `deadline` a page claims |
| "Your turn" | the player's `user:<id>` channel, `push:` or `email:` on the move |
| Dice everyone trusts | a record per roll, the number derived from its server-made `id` |

Not available today; say so to the owner rather than imitate it:

- a server that runs the game: a tick, physics, move checking beyond formulas, anti-cheat;
- anything on a clock faster than every 15 minutes (a daily reset is an automation `on: schedule`);
- random values on the server, so no server shuffle and no deal that nobody has seen;
- guest accounts: a signed-out visitor can't own a record;
- channels that aren't a record or a person, and broadcasts kept for someone who joins later;
- voice or video, peer-to-peer connections, and matchmaking beyond records the pages read;
- app store builds and the app stores' own billing (the app installs from the browser, and it
  sells through Stripe: a game can sell things, see `logic`, "Stripe");
- sign-in with Apple or a games network (email, sign-in links and Google are in `config`).
