> ## Documentation Index
> Fetch the complete documentation index at: https://docs.opengame.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Leaderboards with columns, modes and runs

> Show stats in columns next to the score, split an OpenGame leaderboard by game mode, and list all runs, with Der Koloss as the worked example.

A board can show more than one number for each player. This page builds the board Der Koloss uses. The score is the round a run reached. Kills, downs, revives, points and time are columns next to it. Each run is tagged solo or co-op, and the board stores all runs.

## Before you start

* A board that already works with `submit()` and `top()`, from [Add a leaderboard](https://docs.opengame.io/guides/leaderboards.md).
* The SDK, or a current copy of `og-platform.js`. A copy built before runs existed has no `submitRun`, so copy it again from `@opengamehq/sdk/og-platform`.

## Declare the board

```json opengame.json theme={"system"}
{
  "leaderboards": [
    {
      "key": "rounds",
      "label": "Rounds survived",
      "order": "desc",
      "min": 1,
      "max": 500,
      "scoreLabel": "Round",
      "format": "integer",
      "keep": "runs",
      "runsPerPlayer": 50,
      "columns": [
        { "key": "kills", "label": "Kills", "format": "integer", "min": 0, "max": 100000 },
        { "key": "downs", "label": "Downs", "format": "integer", "order": "asc" },
        { "key": "revives", "label": "Revives", "format": "integer" },
        { "key": "points", "label": "Points", "format": "integer" },
        { "key": "time", "label": "Time", "format": "duration_s", "order": "asc" }
      ],
      "variants": [
        {
          "key": "mode",
          "label": "Mode",
          "values": [
            { "key": "solo", "label": "Solo" },
            { "key": "coop", "label": "Co-op" }
          ]
        }
      ]
    }
  ]
}
```

The score uses the fields it always had: `key`, `label`, `order`, `min` and `max`. These fields are new:

| Field | Meaning |
| - | - |
| `scoreLabel` | What the score column is called, such as `Round`. `label` is still the heading above the board. Up to 24 characters. |
| `format` | How the score is shown: `number` (the default), `integer`, `duration_ms`, `duration_s`, `percent` or `distance_m`. |
| `keep` | `best` (the default), `runs`, or `career` for a board that adds up another board's runs. See [Best run or all runs](#best-run-or-all-runs) and [Career boards](#career-boards). |
| `runsPerPlayer` | Required when `keep` is `runs`. Leave it out otherwise. From 1 to 100. |
| `columns` | Up to 8 stats next to the score. |
| `variants` | Up to 3 ways to split the board, such as a mode or a map. |

Each column takes these fields:

| Field | Meaning |
| - | - |
| `key` | Lowercase letters, digits and underscores, starting with a letter. Up to 32 characters. `score`, `rank`, `player`, `name` and `all` are taken. |
| `label` | The column heading. Up to 24 characters. |
| `format` | As for the score. `number` when left out. |
| `order` | `desc` (the default) when more is better, `asc` when less is. The board uses it when sorted by this column. |
| `sortable` | `true` by default. Set `false` for a stat players should read but not rank by. |
| `min`, `max` | Optional. The range a real value falls in, checked the same way as the score's range. |

A variant has a `key`, a `label` and from 1 to 12 `values`, each with its own `key` and `label`. A value cannot be keyed `all`: the board with no filter is already "All". Since a run may leave a variant out, each variant counts as its values plus one, and those counts multiplied together must stay at 48 or under. Der Koloss has 1 variant with 2 values, which makes 3 combinations.

`opengame check` checks each board with the same rules as the game API, and names the board and the field when one is invalid.

## Best run or all runs

`keep` sets how many rows one player can have on the board.

* **`best`** stores one run a player for each combination of tags: their best solo run, their best co-op run and their best untagged run. A read shows each player once, by their best run for the column it sorts by. Sorted by kills, a player's highest-kill run is the row, even when a different run reached a later round.
* **`runs`** stores all runs, up to `runsPerPlayer` a player for each combination of tags. Once a player has that many, a new run replaces their lowest-ranked one by score, and only when it is better. A read shows all stored runs, so the same player can appear several times.

Der Koloss uses `runs`, because its old site ranked 2,239 runs, not one per player, and a player who got to round 30 twice should see both.

## Submit a run at game over

Call `submitRun` once, when the run ends:

```js js/leaderboard-client.js theme={"system"}
import { og } from "./og-platform.js";

const saved = await og.leaderboard("rounds").submitRun({
  value: round,
  stats: { kills, downs, revives, points, time: durationSeconds },
  tags: { mode: coop ? "coop" : "solo" },
  meta: { character: persona },
});

if (!saved.ok) {
  console.warn(saved.error, saved.reason);
} else if (saved.value.ignored.length) {
  console.warn("Not on this board:", saved.value.ignored);
}
```

A game that installs the SDK from npm imports `og` from `@opengamehq/sdk` instead. `submit(value, meta)` still works and is a run with no stats and no tags.

* `value` is the score: a finite number.
* `stats` maps column keys to finite numbers. A stat the board does not declare is dropped and named in `ignored`, such as `stats.headshots`, and the run still counts. All of them together fit in 512 bytes.
* `tags` maps variant keys to value keys. A key or value the board does not declare fails, and the run is not saved: with `invalid_run` in local play, and with `invalid_request` on OpenGame. A run tagged with a mode the board does not have would appear only under "All".

Each stat is checked with the column's `min` and `max` the same way as the score: outside the range it is stored at the limit and the run is `clamped`, and past 10 times the limit the run is `rejected`. The run gets the lowest of those states, so one implausible stat takes the run off the board. `saved.value.best` is `true` when the run was kept on the board.

## Read the board

`top()` takes a sort, a filter and an offset as well as a limit:

```js theme={"system"}
const board = og.leaderboard("rounds");

// Co-op runs with the most kills first, second page of 25.
const page = await board.top({
  sort: "kills",
  filter: { mode: "coop" },
  limit: 25,
  offset: 25,
});

if (page.ok) {
  const { entries, total, shape } = page.value;
  for (const entry of entries) {
    const { rank, name, score, stats, tags } = entry;
    addRow(rank, name ?? "Guest", score, stats.kills, stats.time, tags.mode);
  }
  showPageCount(total);
}

// The player's own row and the rows near it, under the same filter.
const mine = await board.me({ filter: { mode: "coop" } });
const nearby = await board.around({ sort: "kills", filter: { mode: "coop" } });
```

* `sort` is `score` (the default) or a column's key. Each sorts in the column's `order`, so sorted by `time`, the shortest run is first. Sorting by a column declared `sortable: false` fails: with `invalid_query` in local play, and with `invalid_request` on OpenGame.
* `filter` shows only runs with those tags. Leave it out for "All", which is all runs, tagged or not.
* `offset` skips rows, for `top()` only, from 0 to 10,000. A page has at most 100 rows.

Each entry has `stats` and `tags` next to `score`. A run that left a stat or a variant out has no key for it, so draw an empty cell. The page has `total`, the number of rows under that filter, and `shape`, which has the board's `scoreLabel`, `format`, `keep`, `columns` and `variants`. Draw the column headings and the mode tabs from `shape`, not from a copy in the game, so a board edited in `opengame.json` looks the same in the game and on OpenGame. `shape` does not include the column bounds, because OpenGame uses them to keep implausible runs off the board and does not publish them.

The SDK checks that the game API applied the sort, filter and offset in the request. If it did not, the read fails with `invalid_response`, so your game does not show all runs under a Solo tab.

## Career boards

A career board shows one row per player with totals across every match they played, such as
matches, wins, win rate and average place. You don't submit to it. Name the board whose runs
feed it with `from`, and each accepted run on that board updates the player's career row in
the same request.

Super Smash Royale feeds its career board from `kills`, a best board of KOs in a match with a
`placement` column and a `map` variant:

```json theme={"system"}
{
  "key": "career", "label": "Career", "order": "desc",
  "keep": "career", "from": "kills", "scoreAgg": "sum",
  "scoreLabel": "Eliminations", "format": "integer",
  "columns": [
    { "key": "matches", "label": "Matches", "agg": "count", "format": "integer" },
    { "key": "wins", "label": "Wins", "agg": "count", "where": { "of": "placement", "op": "eq", "value": 1 }, "format": "integer" },
    { "key": "win_rate", "label": "Win rate", "agg": "ratio", "of": ["wins", "matches"], "scale": 100,
      "requires": { "column": "matches", "atLeast": 5 }, "format": "percent", "decimals": 1 },
    { "key": "avg_place", "label": "Avg. place", "agg": "avg", "of": "placement", "order": "asc", "decimals": 1 },
    { "key": "best", "label": "Best match", "agg": "max", "of": "score", "format": "integer" }
  ],
  "variants": [{ "key": "map", "label": "Map", "values": [
    { "key": "sunreach", "label": "Sunreach Shores" }, { "key": "riftwild", "label": "Riftwild Kingdom" } ] }]
}
```

* `scoreAgg` is how each run's score adds into the row's score: `sum`, `count`, `max` or `min`.
* Each column has an `agg`:
  * `count` counts runs.
  * `sum`, `max`, `min` and `avg` read `of`, which is `score` or a column of the source board.
  * `where` limits any of them to runs that match, such as `placement` equal to 1.
  * `ratio` divides two columns declared before it and multiplies by `scale`. With `requires`, the ratio is left out until that column reaches `atLeast`, so one lucky match does not top the win rate.
* `decimals` fixes how many decimals a column shows, so `13.0%` lines up with `22.1%`. An average or a ratio shows one unless you set it.
* Variants must be the source board's, with the same values. A run counts towards the player's row for its own map and towards their All row.
* Only accepted runs count. A clamped or refused run on the source board adds nothing.
* A career board has no `min` or `max`. Every run it counts was already held to the source board's bounds.
* A career board that holds rows keeps its `from`, its `scoreAgg` and the `agg` of every column it has. You can rename it, change a column's label, format or decimals, and add a column. To count a different way, declare a new board.
* In local play a career board stays empty: the SDK checks its declaration and turns down runs sent to it, but only OpenGame adds runs up.
* `og.player.stats()` reads the player's row for all runs on every career board at once. [Read stats back into your game](https://docs.opengame.io/guides/leaderboards.md#read-stats-back-into-your-game) has an XP and levels example.

A career board's totals are the game's own numbers added up, so they are labelled as the
game's claim, as every leaderboard number is.

## Each number is the game's claim

A stat is as forgeable as a score. Anybody with a browser console can send `kills: 99999`. The bounds keep a wild number off the board, but a forged one inside them still appears. OpenGame labels the board as what the game reported, and does not use it to award prizes.

## Test the board

Locally, the SDK reads `./opengame.json` with the same rules as `opengame check`. A local board has one entry, your best run by score, under either `keep` value. That entry has the run's stats and tags. A filter shows it or hides it, sorting does not move it, and any offset skips it. Changing a board's bounds, order, keep rule, columns or variants starts it fresh; changing a label does not.

`top()` results are cached for 30 seconds, so a new run can take that long to appear there.

Before you release:

1. Submit a solo run and a co-op run in your private preview, with each stat filled in.
2. Read `top({ filter: { mode: "solo" } })` and confirm only the solo run is there, then read with no filter and confirm both are.
3. Sort by each column you declared sortable, and confirm `time` puts the shortest run first.
4. Submit a run with a stat the board does not declare, and confirm `ignored` names it.
5. On a `keep: "runs"` board, submit more runs than `runsPerPlayer` and confirm the lowest-ranked run is replaced.

## Fix a problem

| Code | What to do |
| - | - |
| `invalid_run` | A stat is not a finite number, or a tag is not one the board declares. The `reason` names the field. |
| `invalid_query` | Sort by `score` or a sortable column, filter by declared variants, and pass an `offset` to `top()` only. |
| `invalid_manifest` | A board in `opengame.json` is wrong. The `reason` names the board and the field, as `opengame check` does. |
| `invalid_response` | The game API did not apply the sort, filter or offset in the request. Retry, and report it if it repeats. |

`invalid_run` and `invalid_query` come from the checks the SDK runs before a request leaves the game, using the boards in your local `opengame.json`. On OpenGame the game API runs the same checks on the published board, and a run or a read it turns down is returned as `invalid_request` with reason `http_400`, without the field named. Test a new board in local play first.

Check `value.ignored` on a saved run. It names any stat the board does not have. If it names `stats` or `tags` themselves, the game API is older than this release and saved the score without them.

## Where next

> [card] [Add a leaderboard](https://docs.opengame.io/guides/leaderboards.md)
>
> The board fields, names, previews and error codes all boards share.

> [card] [Read the scores API](https://docs.opengame.io/api-reference/scores.md)
>
> The requests the SDK makes, for a game that calls the API itself.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.