Leaderboard
Leaderboard ranks players by a numeric score, per deck and per
variable name. Pick a variable name for each leaderboard the deck has
(e.g. 'score', 'time'). show opens Castle's own leaderboard screen;
reach for fetch only if the deck draws the scores itself.
Leaderboard.write(variable, score, options?)
Submits a score. Only the player's best score for that variable (and
scope) is kept. In the editor it does nothing — safe to call from
gameplay code unconditionally.
options is { scope?: string }. By default the score goes to the
deck's global leaderboard for variable; pass scope to write to a
separate leaderboard (for example a daily one, or a custom id):
Leaderboard.write("score", 1200);
// A daily leaderboard: scope by the current Castle day so each day gets
// its own board (see Time.getServerDate).
const { daysSinceCastleEpoch } = await Time.getServerDate();
Leaderboard.write("score", 1200, { scope: `daily-${daysSinceCastleEpoch}` });
Leaderboard.show(variable, type, options?): Promise<LeaderboardShowResult>
Opens Castle's own leaderboard screen for variable — the same board
players see on other Castle decks, with FOR YOU and GLOBAL tabs, sharing,
and profile links. This is the normal way to show a leaderboard: Castle
draws it and owns the data, so the deck gets no entries back.
type is 'high' (highest first) or 'low' (lowest first). options is
{ scope?, label? } — scope works as it does in write, and label
titles the column of scores (default 'Score'; e.g. 'Time', 'Coins').
Opening the board also submits the score the player has written this
session, so their own result is on it right away. The board appears
immediately, on a loading spinner; the promise resolves once the scores
are in. The player closes it themselves — there's no hide.
LeaderboardShowResult has a status:
'shown'— Castle opened the leaderboard.'unavailable'— this host has no leaderboard screen, or can't show one right now. Nothing was submitted; the score still saves normally.
Leaderboard.write("score", finalScore);
gameOverButton.onclick = () => Leaderboard.show("score", "high");
Leaderboard.fetch(variable, type, options?): Promise<LeaderboardData>
Fetches the leaderboard's entries so the deck can draw them itself — use
this only when Castle's own screen isn't what you want. type and
options.scope work as they do in show.
Like show, a fetch reflects the player's own score written this
session right away. Other players' recent scores still appear on their own
normal timing.
The returned LeaderboardData has:
list— array of entries, each{ place, value, username, userId? }.playerRank— the current player's place on the board (if they have a score).playerValue— the current player's score (if they have one).
const data = await Leaderboard.fetch("score", "high");
for (const entry of data.list) {
console.log(`${entry.place}. ${entry.username} — ${entry.value}`);
}
if (data.playerRank) {
console.log(`you are #${data.playerRank} with ${data.playerValue}`);
}