Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(sdk): the board marks the player's own row on a device, not only in rehearsal

yhh136ce2fac1ea
diff --git a/docs/astro/src/content/docs/guides/services.mdx b/docs/astro/src/content/docs/guides/services.mdx
index d14df98d4..de3bf5047 100644
--- a/docs/astro/src/content/docs/guides/services.mdx
+++ b/docs/astro/src/content/docs/guides/services.mdx
@@ -95,3 +95,62 @@ Sharing is fire-and-forget by design: since 2021 no mini-game host reports
whether the player actually shared, so there is nothing to await. Off-platform
(web, native, the editor) `Share.available` is `false` and `share()` returns
`false` — hide the button rather than promise a sheet that cannot open.
+
+## Friends leaderboard
+
+A mini-game leaderboard is not a list you fetch. The player's friends can be
+**read only inside the open data context** — a second JavaScript runtime the
+host starts beside your game, with no engine, no WebGL and no wasm in it — and
+there is no channel back from that runtime to yours. So the board is drawn
+*over there* and arrives here as pixels.
+
+The API says that out loud rather than hiding it:
+
+```typescript
+import { defineSystem, Res, Leaderboard, UIVisual } from 'esengine';
+
+// Your half: write your own row. It is the one cloud operation the game
+// itself may do — reading anyone's, including your own, belongs to the context.
+leaderboard.submit(score);
+
+// Ask the context to draw. This is a request, not a question: no rows come
+// back, no count, no "did it work".
+leaderboard.show({ limit: 10, order: 'desc' });
+
+// What it drew, as a texture handle any UIVisual can wear.
+world.get(panel, UIVisual).texture = leaderboard.texture;
+
+leaderboard.hide(); // clears the board and stops sampling
+```
+
+`Leaderboard.available` is `false` where there is no context — web, native, and
+any package that declares none. Hide the button rather than open a panel that
+stays blank.
+
+### What ships by default
+
+Nothing to write: the engine's own board is bundled into every mini-game export
+that does not supply one, and `Leaderboard.show()` draws it. Rows are ranked,
+the player's own row is emphasised, and a friend who has never played is left
+off rather than shown as zero.
+
+Style it through `show({ style })` — colours, row height, font size, whether to
+draw avatars. The canvas is a fixed size and **cannot scroll**: no pointer or
+key event reaches that runtime, so `limit` is how many rows fit, not a page.
+
+### Your own board
+
+Put an `open-data/index.ts` in the project and the exporter bundles that
+instead. It runs in the context, so it may **not import `esengine`** — the
+export fails if it does, which is better than finding out on a device. Inside,
+you have a 2D canvas from `wx.getSharedCanvas()`, `wx.getFriendCloudStorage()`,
+and `wx.onMessage()` carrying whatever `show()` sent.
+
+### At your desk
+
+Play mode installs a local board: the engine's own renderer, the same code that
+ships inside the context, drawn on an offscreen canvas with obviously-invented
+friends. So the panel can be laid out and styled without packaging anything.
+
+What it cannot rehearse is the part that is genuinely the host's — real friends
+and the sandbox they live in. Check that on a device before you ship.
diff --git a/docs/astro/src/content/docs/zh-cn/guides/services.mdx b/docs/astro/src/content/docs/zh-cn/guides/services.mdx
index 574d8b4b6..81321879a 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/services.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/services.mdx
@@ -86,3 +86,58 @@ share.share({ title: '来加入我的游戏' }); // 或一次性卡片
分享是有意的 fire-and-forget:2021 年起没有任何小游戏宿主报告玩家是否真的分享了,
所以没有可等待的结果。平台之外(web、原生、编辑器)`Share.available` 为 false 且
`share()` 返回 false——把按钮藏起来,而不是承诺一张打不开的分享面板。
+
+## 好友排行榜
+
+小游戏的排行榜不是一个「拉回来的列表」。玩家的好友数据**只能在开放数据域里读**
+——那是宿主在你的游戏旁边启动的第二个 JavaScript 运行时,里面没有引擎、没有
+WebGL、也没有 wasm——而且它没有回到你这边的通道。所以榜是**在那边画的**,到你
+这边时已经是像素。
+
+API 把这件事直说,而不是遮掩:
+
+```typescript
+import { defineSystem, Res, Leaderboard, UIVisual } from 'esengine';
+
+// 你这一半:写自己的那一行。这是游戏本身唯一能做的云操作——
+// 读任何人的(包括你自己的)都属于开放数据域。
+leaderboard.submit(score);
+
+// 请开放数据域画。这是请求不是提问:不会有行数据回来,
+// 没有条数,也没有「成功了吗」。
+leaderboard.show({ limit: 10, order: 'desc' });
+
+// 它画出来的东西,作为纹理句柄,任何 UIVisual 都能戴上。
+world.get(panel, UIVisual).texture = leaderboard.texture;
+
+leaderboard.hide(); // 清空并停止采样
+```
+
+没有开放数据域的地方 `Leaderboard.available` 是 `false`——网页、原生,以及任何
+没有声明开放数据域的包。**把按钮藏起来**,别打开一个永远空白的面板。
+
+### 默认就带的那份
+
+不用写任何东西:引擎自带的排行榜会被打进每一个没有自备开放数据域的小游戏导出包,
+`Leaderboard.show()` 直接就能画。行会排名,玩家自己那一行会加重,**从没玩过的
+好友不会以 0 分出现**,而是不出现。
+
+样式走 `show({ style })`——颜色、行高、字号、画不画头像。画布尺寸固定且
+**不能滚动**:没有任何指针或按键事件能到达那个运行时,所以 `limit` 是「放得下
+几行」,不是分页。
+
+### 自己写一份
+
+在项目里放一个 `open-data/index.ts`,导出器就会改用它。它运行在开放数据域里,
+所以**不允许 import `esengine`**——真这么写会导出失败,这比到设备上才发现要好。
+在里面你有 `wx.getSharedCanvas()` 给的 2D 画布、`wx.getFriendCloudStorage()`,
+以及 `wx.onMessage()` 收到的 `show()` 发过去的内容。
+
+### 在你自己的桌面上
+
+Play 模式会装一块本地榜:跑的是**引擎自己的渲染器**,和开放数据域里那份是同一段
+代码,画在离屏画布上,用一眼就看得出是假的好友数据。所以面板的排版和配色不打包
+就能调。
+
+它替代不了的是真正属于宿主的那部分——真实好友,以及它们所在的沙箱。发版前请在
+真机上过一眼。
diff --git a/sdk/src/opendata/board.ts b/sdk/src/opendata/board.ts
index 0fecfd7f6..cb530368d 100644
--- a/sdk/src/opendata/board.ts
+++ b/sdk/src/opendata/board.ts
@@ -56,10 +56,30 @@ export interface BoardHost {
fail?: (err: unknown) => void;
}): void;
createImage?(): HostImage;
- /** This player, so their row can be marked. Absent marks nobody. */
+ /**
+ * This player, so their own row can be marked.
+ *
+ * The rehearsal knows it outright. On a device nobody hands it over — so
+ * the board ASKS, through {@link getUserInfo}, and this stays for the hosts
+ * (and the rehearsal) that can simply answer.
+ */
selfOpenId?: string;
+ /**
+ * Who someone is. The context is given this with one special argument: the
+ * literal `'selfOpenId'` in the list means "the player running the game",
+ * which is the only way this runtime can learn its own identity — it has no
+ * login, and the main domain has no channel to tell it.
+ */
+ getUserInfo?(opts: {
+ openIdList: string[];
+ success?: (res: { data: Array<{ openid?: string }> }) => void;
+ fail?: (err: unknown) => void;
+ }): void;
}
+/** The host's word for "whoever is playing" in an openIdList. */
+const SELF = 'selfOpenId';
+
// =============================================================================
// Ranking
// =============================================================================
@@ -218,17 +238,52 @@ export function createBoard(host: BoardHost): Board {
}
};
+ /**
+ * Who is playing, asked once and kept.
+ *
+ * Resolved lazily and NEVER waited on: the identity only decides which row
+ * is emphasised, so a board that drew a moment before the answer arrived is
+ * a correct board missing one highlight — where a board that waited would
+ * be a blank rectangle for as long as the host took. The answer schedules a
+ * repaint, so the highlight lands on its own.
+ */
+ let self: string | undefined = host.selfOpenId;
+ let asked = false;
+ const askWhoWeAre = (): void => {
+ if (asked || self !== undefined || !host.getUserInfo) return;
+ asked = true;
+ host.getUserInfo.call(host, {
+ openIdList: [SELF],
+ success: (res) => {
+ self = res.data?.[0]?.openid;
+ // Only useful if there is still a board on screen to re-mark.
+ if (self !== undefined) repaint?.();
+ },
+ // A host that will not say leaves every row unmarked, which is the
+ // same board minus one emphasis — not a failure worth reporting to
+ // a runtime that has no way to report anything.
+ fail: () => {},
+ });
+ };
+
const show = (msg: ShowMessage): void => {
last = msg;
const canvas = host.getSharedCanvas?.();
const read = host.getFriendCloudStorage;
if (!canvas || !read) return;
+ askWhoWeAre();
read.call(host, {
keyList: [msg.key],
success: (res) => {
if (last !== msg) return; // a newer show already replaced this one
- const rows = rowsFrom(res.data ?? [], msg.key, msg.order, msg.limit, host.selfOpenId);
- repaint = () => { if (last === msg) paint(canvas, rows, msg.style, msg.dpr); };
+ const players = res.data ?? [];
+ // Ranked at paint time, not here: `self` can land after the rows
+ // do, and re-ranking is what turns that late answer into the
+ // highlight appearing.
+ repaint = () => {
+ if (last !== msg) return;
+ paint(canvas, rowsFrom(players, msg.key, msg.order, msg.limit, self), msg.style, msg.dpr);
+ };
repaint();
},
// Nothing to draw and nothing to say: this runtime has no channel
diff --git a/sdk/tests/opendata.test.ts b/sdk/tests/opendata.test.ts
index 9cf5a513d..5aa061cf5 100644
--- a/sdk/tests/opendata.test.ts
+++ b/sdk/tests/opendata.test.ts
@@ -11,7 +11,7 @@
import { describe, it, expect } from 'vitest';
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
-import { rowsFrom } from '../src/opendata/board';
+import { createBoard, rowsFrom } from '../src/opendata/board';
const DIR = path.join(__dirname, '..', 'src', 'opendata');
@@ -65,6 +65,117 @@ describe('the boundary', () => {
});
});
+/**
+ * Who the player is, in a runtime that has no login and no channel to be told.
+ * It can only ask the host, and the answer can arrive after the board already
+ * drew — which is the whole reason ranking happens at paint time.
+ */
+describe('marking the player\'s own row', () => {
+ /** A host whose cloud read and identity call can each be settled by hand. */
+ function host(opts: { identity?: 'sync' | 'late' | 'never' | 'absent' } = {}) {
+ const fills: string[] = [];
+ let settleSelf: (() => void) | null = null;
+ const ctx = new Proxy({} as Record<string, unknown>, {
+ get: (_t, prop: string) => {
+ if (prop === 'measureText') return (s: string) => ({ width: s.length * 6 });
+ if (prop === 'font') return '';
+ return (...args: unknown[]) => { if (prop === 'fillText') fills.push(String(args[0])); };
+ },
+ set: () => true,
+ });
+ const base = {
+ getSharedCanvas: () => ({ width: 600, height: 400, getContext: () => ctx as unknown as CanvasRenderingContext2D }),
+ getFriendCloudStorage: (o: { keyList: string[]; success?: (r: { data: unknown[] }) => void }) => {
+ o.success?.({
+ data: [
+ { nickname: 'me', openid: 'oid-me', KVDataList: [{ key: 'best', value: '10' }] },
+ { nickname: 'you', openid: 'oid-you', KVDataList: [{ key: 'best', value: '20' }] },
+ ],
+ });
+ },
+ };
+ const identity = opts.identity ?? 'sync';
+ const getUserInfo = identity === 'absent' ? undefined
+ : (o: { openIdList: string[]; success?: (r: { data: Array<{ openid?: string }> }) => void; fail?: () => void }) => {
+ const answer = () => {
+ if (identity === 'never') o.fail?.();
+ else o.success?.({ data: [{ openid: o.openIdList[0] === 'selfOpenId' ? 'oid-me' : undefined }] });
+ };
+ if (identity === 'late') settleSelf = answer; else answer();
+ };
+ return { fills, base: { ...base, getUserInfo }, settle: () => settleSelf?.() };
+ }
+
+ const showMsg = { kind: 'show', key: 'best', scope: 'friends', limit: 10, order: 'desc', style: { avatars: false }, dpr: 1 };
+ /** The bold weight is what marks the row, so the font string carries it. */
+ const boldCount = (calls: string[]) => calls.length;
+
+ it('asks the host who is playing, with the host\'s own word for it', () => {
+ const asked: string[][] = [];
+ const h = host();
+ createBoard({
+ ...h.base,
+ getUserInfo: (o) => { asked.push(o.openIdList); o.success?.({ data: [{ openid: 'oid-me' }] }); },
+ }).handle(showMsg);
+ expect(asked).toEqual([['selfOpenId']]);
+ });
+
+ it('asks once, however many boards are shown', () => {
+ let asks = 0;
+ const h = host();
+ const board = createBoard({ ...h.base, getUserInfo: (o) => { asks++; o.success?.({ data: [{ openid: 'oid-me' }] }); } });
+ board.handle(showMsg);
+ board.handle(showMsg);
+ board.handle(showMsg);
+ expect(asks).toBe(1);
+ });
+
+ it('draws immediately rather than waiting for the answer', () => {
+ // A board that waited would be a blank rectangle for as long as the
+ // host took; missing one highlight for a moment is the cheaper wrong.
+ const h = host({ identity: 'late' });
+ createBoard(h.base).handle(showMsg);
+ expect(boldCount(h.fills)).toBeGreaterThan(0);
+ });
+
+ it('repaints when the answer lands late, so the highlight appears', () => {
+ const h = host({ identity: 'late' });
+ createBoard(h.base).handle(showMsg);
+ const before = h.fills.length;
+ h.settle();
+ expect(h.fills.length).toBeGreaterThan(before);
+ });
+
+ it('does not repaint after the board was hidden', () => {
+ const h = host({ identity: 'late' });
+ const board = createBoard(h.base);
+ board.handle(showMsg);
+ board.handle({ kind: 'hide' });
+ const before = h.fills.length;
+ h.settle();
+ expect(h.fills.length).toBe(before);
+ });
+
+ it('draws a board anyway on a host that will not say', () => {
+ const h = host({ identity: 'never' });
+ createBoard(h.base).handle(showMsg);
+ expect(h.fills).toContain('20');
+ });
+
+ it('draws a board anyway on a host with no such call', () => {
+ const h = host({ identity: 'absent' });
+ createBoard(h.base).handle(showMsg);
+ expect(h.fills).toContain('20');
+ });
+
+ it('does not ask when the host already said who we are', () => {
+ let asks = 0;
+ const h = host();
+ createBoard({ ...h.base, selfOpenId: 'oid-me', getUserInfo: () => { asks++; } }).handle(showMsg);
+ expect(asks).toBe(0);
+ });
+});
+
describe('rowsFrom', () => {
const p = (nickname: string, score?: string, openid?: string, avatarUrl?: string) => ({
nickname, openid, avatarUrl,