# Game clocks & timing

Most BGS games use a separate thinking-time budget for each player. Real-time games can instead manage their own shared clock, with BGS waking the engine at its next deadline. The default remains player clocks.

## What the creator configures

At game creation, the host picks two values, stored on the game as `options.timing`:

- **`timePerGame`** (seconds) — each player's total clock for the whole game. Everyone starts with
  `remainingTime = timePerGame`.
- **`timePerMove`** (seconds) — an increment/refund added back after each of your moves.

Two optional modifiers:

- **`timer: { start, end }`** — a daily play window, in UTC seconds-of-day (e.g. `{ start: 28800, end: 61200 }` =
  8:00–17:00 UTC). Clocks only tick inside the window: elapsed time and deadlines are computed skipping the paused
  hours. Default is the full day (`{ start: 0, end: 86399 }`). The window must span at least 3 hours.
- **`scheduledStart`** — the game starts by itself at that date (at most 10 days out) instead of as soon as it's
  full. If the game is **ready** (all seats filled, and the host has set any final options) when the date passes,
  it starts; if it still isn't ready at the scheduled date, the game is **cancelled** ("not fully ready at
  scheduled start date") rather than held open. The host has until the scheduled start to finish setup.

Players receive an email one hour before a scheduled game and an inbox reminder ten minutes before.
Browser reminders use the notification setting for this device and require the site to be open.
Scheduled-game emails have their own setting and unsubscribe link. The table also has an **Add to calendar** button.

If the host changes the time, everyone who joined must confirm again. Players can leave without a penalty;
those who don't respond are never started into the game. If confirmations or setup are still missing at the new
start time, the table is cancelled without an inactivity penalty. Time changes and cancellations appear in the
inbox immediately; emails are grouped for five minutes. Email limits apply per recipient, and outdated reminders
are discarded.

Shorter `timePerGame`/`timePerMove` values make a "live" game; the usual settings make asynchronous games that
play out over days.

## Play now

For an unscheduled live game, **Play now** holds your seat for 5, 15 or 30 minutes (default: 15).
You can extend the wait. Keep BGS open (you can play another game while waiting); after 90 seconds without a connection, your seat is released.
Switching browser tabs does not itself release your seat.

When a player joins the last open seat, that join counts as their ready confirmation. The players already
waiting have two minutes to confirm. Missing confirmations release only those seats; the other players and
chat stay. Any player change resets the ready check; a new player filling the table is automatically ready,
while the waiting players must confirm again. Waiting costs no karma or Elo and sends no emails.
Player clocks start only after everyone is ready and the game begins.

A banner appears wherever you are on BGS when your table is ready or your live game starts.
You can enable sound and browser alerts too. Opening the game clears its start alert.
The lobby puts live tables first; games scheduled more than 15 minutes away keep their normal position.

Quick tables are available on individual boardgame pages. The main lobby features Gaia Project
(Lost Fleet, preference-split auction), Powergrid (fast bids) and Container.
Primordial Soup uses new genes and Outpost uses sealed bidding; other games use their usual defaults.

The lobby offers shared standard tables, created when someone first joins. Each person can hold one
Play now seat at a time. Scheduled games and persistent tables keep their separate start rules.

## How clocks move

The game-server maintains, per current player, a `timerStart` timestamp and a `deadline` (computed from the
player's `remainingTime`, skipping the paused hours when a `timer` window is set).

Saving a move settles elapsed thinking time and synchronizes active players with
`currentPlayer(data)`. Leaving players pause their clocks; returning players resume
from their remaining time.

- Without `timeIncrements`, a normal save credits `timePerMove` to the mover.
- With `timeIncrements`, each increase in a player's count credits that many
  increments immediately, on normal and live saves alike.
- An unchanged count earns no time. Dropped or quit players receive no increments.

A credited clock is capped at `timePerGame` and has a floor of `timePerMove`.
Pausing or reopening alone does not provide that floor or a free increment. If a
player stays active after receiving time, their deadline reflects the new balance.
During live updates, players who remain active without receiving time keep their
existing clock and deadline.

Games can have several current players at once (e.g. 6nimmt!, where everyone picks a card simultaneously) — each
current player has their own `timerStart`/`deadline`, and each clock only runs while that player is current.

## Timeouts, drops, and inactivity

### Automatic enforcement at 60+2 or faster

For games with **at most 1 hour per player and at most 2 minutes per move**
(`timePerGame <= 3600` and `timePerMove <= 120`), the game-server checks timeouts roughly every second,
even when nobody has the game open. Both limits must be met; a missing base clock does not qualify, while an
omitted increment means zero. This is narrower than the live/async labels used in game listings.
Solo games and engine-managed clocks are excluded, and bots are never timeout-drop targets.

- **One eligible player remains:** BGS automatically awards that player the win when every opponent has left
  or timed out. Active bot opponents prevent this automatic win. No new karma penalty is applied.
- **Several players can continue:** timed-out human players are automatically dropped through the engine's
  [`dropPlayer`](./engine-api.md#dropplayer). Each dropped player loses **1 karma**, once per game.
  The same rule applies to a manual timeout drop in these games; clicking first cannot impose a harsher penalty.
- **Everyone remaining has timed out:** the game is cancelled without selecting a winner or applying new
  karma penalties.

Eligibility is rechecked under the game lock. A move that renews a player's deadline before timeout processing
prevents that stale timeout from dropping them. Automatic enforcement is background processing, not a precision timer.

### Manual claims and slower games

- **The last remaining player can claim the win at any speed.** When every opponent has left or their
  current-turn deadline has passed, the remaining player can **Claim win** from the sidebar or compact rail
  (`POST /gameplay/:id/claim-win`). It takes effect directly, without a confirmation dialog. This applies to 1v1
  and larger games. The claimant must still be in the game and must not have timed out. Solo games, active bot
  opponents, and engine-managed clocks are excluded.
- **Claimed and automatic wins have the same result.** The game-server drops newly timed-out opponents in the
  engine, stopping if the engine ends or cancels, but BGS records a non-cancelled win regardless of the engine's
  outcome. Opponents share second place; normal Elo rules apply. No new karma penalty is created, and earlier
  penalties are not refunded. Stored departure history remains intact. Destructive admin replay skips claimed
  games to preserve this result.
- **Slower games keep manual timeout drops.** A participant can drop a timed-out current player
  (`POST /game/:id/drop/:userId`). Outside the automatic-enforcement threshold, a timeout drop still costs
  **10 karma**. The applied penalty is stored with the dropped player, so later karma recalculation preserves it.
- **Inactivity sweep.** If a deadline stays expired for 24 hours, a warning is posted in the game chat; if nothing
  moves for 10 days past the deadline, the game is **cancelled for inactivity** (penalty-free — no Elo/karma
  effect, as with a player-agreed cancel). A warning can only repeat after a move resets it.

## What this means for engine authors

- **BGS manages ordinary player clocks.** Most engines do not need to track thinking time. Engines with
  real-time phases use the trusted context and wakeup hooks described below.
- **`dropPlayer` must be robust.** It is called exactly when a player ran out of time (or quit): possibly early in
  the game, possibly mid-decision, possibly when they are the current player. Either turn them into an AI or
  remove them cleanly, and if they were current, pass the turn to the next non-dropped player. See
  [bot players](./bots.md) for how dropped players relate to bots.
- **Each completed decision earns time once.** With [`timeIncrements`](./engine-api.md#timeincrements), each
  player's count increase earns one increment, including on live saves. Without it, normal saves credit the mover.
  Ready pauses your clock; reopening resumes it. Unchanged counts never earn another increment.
- **Keep `move` and available-moves computation fast.** Engine calls run with a hard timeout — see
  [Architecture](./architecture.md).

## Games with their own clock

Set the game version's **Time control** to **Game manages its own clock** (`timeControl: "engine"`). BGS then hides player clock settings and does not assign per-player deadlines, time increments, inactivity drops, or turn emails. Scheduling a future start still works.

Implement both `advanceTime(data, context)` and `nextWakeup(data)`:

```ts
export function nextWakeup(data) {
	return data.phase === "flight" ? data.nextAnnouncementAt : null;
}

export function advanceTime(data, { now }) {
	const next = structuredClone(data);
	while (next.nextAnnouncementAt !== null && next.nextAnnouncementAt <= now) {
		processNextAnnouncement(next);
	}
	return next;
}
```

Deadlines are absolute Unix milliseconds. `null` means the engine is waiting for players: useful for repairs, campaign decisions, or an untimed resolution phase. A returned deadline must be later than `context.now`.

BGS supplies `context.now` to `init`, `move`, `dropPlayer`, and `stripSecret`. It is assigned on the server after acquiring the game lock and never moves backwards for a game. Never trust a timestamp sent inside a player move. A browser may interpolate a countdown from the latest server time for display; the engine decides whether a move arrived in time.

BGS saves the next wakeup in MongoDB and checks due games roughly every 250 ms, even with no connected viewers. Waking is not a precision timer: your engine must consume **all** events up to `now`, tolerate repeated calls, and catch up after a restart. Before processing a move, BGS commits any due events under the same game lock. Rejecting a late move cannot roll back a closed phase.

`advanceTime` returns the complete, serializable state to persist; BGS does not run `toSave` on it. Use `isLiveUpdate` for intermediate announcements. Endings still receive normal result processing. A failed wakeup is logged and retried after 30 seconds; other games can continue.

Game-managed clocks currently do not support analysis mode. A simulation clock needs its own adapter before those games can safely offer analysis.

Throw `InvalidMoveError` (from `@boardgamers/protocol/engine`) for an expected invalid command, such as playing after a phase closes. BGS returns HTTP 422 instead of recording an internal server failure.

## Continuing at the same table

Set a game version's **Persistent table** to `live` or `async` to keep the crew, chat and table URL between games. Each play still has its own result and replay. Waiting tables do not expire.

- **Live:** everyone stays seated; the next game opens directly into its engine's preparation screen. The engine must check readiness before timed play. Space Alert uses two-minute ready confirmations and a shared countdown; expired readiness or a lost connection returns the crew to waiting.
- **Async:** everyone stays seated but confirms the next game once. The last confirmation starts it; nobody needs to be online together.

Changing setup creates a fresh game with fresh readiness. Players can leave between games without changing earlier results. Table reservations never send invitation emails.

Without this setting, the ordinary **Play again** flow below applies.

**Play again** creates a separate game with the same seats and fresh randomness. Other players must confirm their seats again; the host then starts. These reservations send no invitation emails and consume no thinking time. Setup options and expansions can change between games. The table's stable URL opens its current game, and history is paginated by game number.

Each completed game keeps its original state and replay. The next game receives only the engine's versioned `tableProgress` checkpoint through `context.table.progress`. Match characters by account ID; carry no hands or seeds. See the [engine hooks](./engine-api.md#clock-presence-and-tables-protocol-08).

BGS tracks loaded, visible participant viewers with an eight-second connection lease, renewed every two seconds. Multiple tabs count as one present player. Disconnects and game deadlines are processed in order, including after a server restart. Engines receive seat changes through `presenceChanged`, not ordinary moves. Readiness is separate consent: a heartbeat never extends it.

Progress stays at its table; it is not an account-wide character service. A short campaign can also stay inside one game, returning `null` from `nextWakeup` between missions.

For cooperative games, choose **Unrated** (`rating: "none"`) on the game version. New games then skip Elo settlement; past results stay unchanged.
