@celljs/ta-play 0.0.0-stage → 4.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md ADDED
@@ -0,0 +1,12 @@
1
+ # Cell - Ta Play
2
+
3
+ A pi package that comes with Ta (on by default; turn it off in Settings → Extensions of the web client): playable replies. When something is better played than read, Ta answers with a little game made for the one who plays: played in the reply, or with the members of a group chat. Design: [docs/design/ta-play.md](../../docs/design/ta-play.md).
4
+
5
+ - **A game in a reply**: under Ta's service each turn's system prompt has a section `<ta-play>`: for practice, review, a concept to try, or a game the user asks for, the model writes a `ta-play` block (one whole HTML document) made from the person's level, past mistakes and interests. While it is written the card says how far it is; then a cover, and Play runs it in the reply (full screen on a phone), with Again and Full screen.
6
+ - **One round for one person**: a game calls `ta.finish({score, total, summary, mistakes})` when a round ends; the card shows it and "Next round, from this one", which sends it to Ta for the next round. A game that throws shows why and "Have Ta fix it".
7
+ - **Together**: Play together sends the game to a group chat (a class is a group chat): it goes into the room's shared state `play:game` and a line is said in the chat. Members see it in the room's app Games and run it only when they tap Join; the game shares `ta.state` / `ta.set` (the room's state, keys `play:<game>:<key>`) and `ta.send` / `ta.on('message')` (the room's messages); who started it is the host. They, the owner and the admins can end it, which clears its state.
8
+ - **Apart**: a game runs in an iframe with `sandbox="allow-scripts"` and a CSP at its head (`default-src 'none'`, `connect-src 'none'`): no origin, no network, no reach into Ta's page or storage; it talks to the page by `window.ta` alone. The page hears only its own frame; writes and messages are 20 a second at most, keys 64 characters, values 16 KB, 200 keys a game, 48 KB for a game sent to a room.
9
+ - **What is kept**: `ta.save(value)` goes to the package's storage, for the 50 games played last only. `localStorage` in a game is kept in memory.
10
+ - **Elsewhere**: external agents (ta-agents) get a line and a file of it; replies sent to WeChat and WeCom bots do not draw games.
11
+
12
+ Format and limits: `web-src/play-protocol.ts`, `web-src/play-doc.ts`; the prompt: `web-src/play-prompt.ts`.
package/README.md CHANGED
@@ -1,3 +1,12 @@
1
- # Temporary Holding Version
1
+ # Cell - Ta Play
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ta 自带的 pi 包(默认开启,可在 Web 客户端的 设置 → 扩展 关闭):能玩的回复。适合玩着学、玩着看的内容,Ta 直接回复一个为这个人定做的小游戏,在回复里就能玩,也能发到群里大家一起玩。设计见 [docs/design/ta-play.md](../../docs/design/ta-play.md)。
4
+
5
+ - **回复里的游戏**:在 Ta 服务下,每一轮的系统提示里多一段 `<ta-play>`:练习、复习、要动手试的概念、用户想玩的时候,写一个 `ta-play` 代码块(一份完整的 HTML),按这个人的水平、错过的题和兴趣来做。写的过程中卡片显示"正在做游戏… 已写 N 行";写完显示封面,点开始在回复里玩(手机上全屏),可以重来、全屏。
6
+ - **一人一局**:游戏结束时调 `ta.finish({score, total, summary, mistakes})`,卡片显示本局成绩和"按这局出下一局",点了就把成绩和错处发给 Ta,Ta 据此出下一局。游戏出错时卡片显示原因和"让 Ta 修好"。
7
+ - **一起玩**:卡片上的"一起玩"把游戏发到一个群聊(班级群也是群聊):游戏存进群的共享状态 `play:game`,群里说一句"发起了小游戏"。群成员在群的应用"小游戏"里看到它,点"加入"才运行;游戏用 `ta.state` / `ta.set`(群的共享状态,键为 `play:<游戏>:<键>`)和 `ta.send` / `ta.on('message')`(群消息)同步,发起的人是主持(`host`)。发起人、群主和管理员可以结束游戏,结束时清掉它的状态。
8
+ - **隔离**:游戏在 `sandbox="allow-scripts"` 的 iframe 里运行,文档开头带 CSP(`default-src 'none'`、`connect-src 'none'`):没有来源、不能联网、不能读 Ta 的页面和存储,只能通过 `window.ta` 和页面互发消息。页面只听自己那个 iframe 的消息,写状态和发消息每秒最多 20 次,键 64 字符、值 16 KB 以内,一个游戏最多 200 个键,发到群的游戏 48 KB 以内。
9
+ - **存的东西**:`ta.save(value)` 存在本包的存储里,只留最近玩过的 50 个游戏,不会越存越多。`localStorage` 在游戏里是内存版,关掉就没了。
10
+ - **别处**:外部 Agent(ta-agents)拿到的是这段写法的一行摘要和一个文件;发到微信、企业微信机器人的回复不画游戏。
11
+
12
+ 格式与限制见 `web-src/play-protocol.ts`、`web-src/play-doc.ts`,提示词见 `web-src/play-prompt.ts`。
@@ -0,0 +1,138 @@
1
+ // ../ta-protocol/esm/common/ta-extension-host.js
2
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
3
+ var TA_HOST_EVENT = "ta:host";
4
+ var TaHostUtil;
5
+ (function(TaHostUtil2) {
6
+ TaHostUtil2.WAIT_MS = 1000;
7
+ function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
8
+ return new Promise((resolve) => {
9
+ let heard = false;
10
+ let answered = false;
11
+ const timer = setTimeout(() => resolve(undefined), waitMs);
12
+ const request = {
13
+ name,
14
+ heard: () => {
15
+ heard = true;
16
+ },
17
+ resolve: (answer) => {
18
+ answered = true;
19
+ clearTimeout(timer);
20
+ resolve(answer);
21
+ }
22
+ };
23
+ events.emit(TA_HOST_EVENT, request);
24
+ if (!heard && !answered) {
25
+ clearTimeout(timer);
26
+ resolve(undefined);
27
+ }
28
+ });
29
+ }
30
+ TaHostUtil2.reach = reach;
31
+ function marked(systemPrompt, mark) {
32
+ return role(systemPrompt).includes(mark);
33
+ }
34
+ TaHostUtil2.marked = marked;
35
+ function role(systemPrompt) {
36
+ if (!systemPrompt) {
37
+ return "";
38
+ }
39
+ const open = `<addendum>
40
+ `;
41
+ const start = systemPrompt.indexOf(open);
42
+ const context = systemPrompt.indexOf(`<project_context>
43
+ `);
44
+ if (start < 0 || context >= 0 && context < start) {
45
+ return "";
46
+ }
47
+ const end = systemPrompt.indexOf(`
48
+ </addendum>`, start);
49
+ return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
50
+ }
51
+ TaHostUtil2.role = role;
52
+ })(TaHostUtil || (TaHostUtil = {}));
53
+ var TA_DOUBLE_LOOK = {
54
+ name: "@celljs/ta-web",
55
+ key: "assistant.species",
56
+ given: ["trex", "triceratops", "stegosaurus", "brachiosaurus", "velociraptor", "ankylosaurus", "pteranodon", "parasaurolophus"]
57
+ };
58
+ var TaDoubleLookUtil;
59
+ (function(TaDoubleLookUtil2) {
60
+ function given(id) {
61
+ let hash = 2166136261;
62
+ for (let i = 0;i < id.length; i++) {
63
+ hash = Math.imul(hash ^ id.charCodeAt(i), 16777619);
64
+ }
65
+ return TA_DOUBLE_LOOK.given[(hash >>> 0) % TA_DOUBLE_LOOK.given.length];
66
+ }
67
+ TaDoubleLookUtil2.given = given;
68
+ })(TaDoubleLookUtil || (TaDoubleLookUtil = {}));
69
+ var TA_ASK_ENTRY = "ta-ask";
70
+ var TaAskUtil;
71
+ (function(TaAskUtil2) {
72
+ const LENGTH = 120;
73
+ function entry(question) {
74
+ const line = question.replace(/\s+/g, " ").trim();
75
+ return { question: line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line };
76
+ }
77
+ TaAskUtil2.entry = entry;
78
+ function asking(entries) {
79
+ var _a;
80
+ for (let i = entries.length - 1;i >= 0; i--) {
81
+ const entry2 = entries[i];
82
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
83
+ return;
84
+ }
85
+ if (entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY) {
86
+ return read(entry2);
87
+ }
88
+ }
89
+ return;
90
+ }
91
+ TaAskUtil2.asking = asking;
92
+ function next(asked, entry2) {
93
+ var _a;
94
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
95
+ return;
96
+ }
97
+ return entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY ? read(entry2) : asked;
98
+ }
99
+ TaAskUtil2.next = next;
100
+ function read(found) {
101
+ var _a;
102
+ const question = (_a = found.data) === null || _a === undefined ? undefined : _a.question;
103
+ if (typeof question !== "string" || !question.trim()) {
104
+ return;
105
+ }
106
+ const at = found.timestamp ? Date.parse(found.timestamp) : Number.NaN;
107
+ return { question: entry(question).question, at: Number.isNaN(at) ? 0 : at };
108
+ }
109
+ })(TaAskUtil || (TaAskUtil = {}));
110
+
111
+ // web-src/play-protocol.ts
112
+ var NAME = "@celljs/ta-play";
113
+ var LANGUAGE = "ta-play";
114
+
115
+ // web-src/play-prompt.ts
116
+ var PLAY_PROMPT = `When something is better played than read (practice, review, a concept to try out, a puzzle, a game the user asks for, a round with friends or a class), answer with a little game made for this person: a fenced block of language ${LANGUAGE} holding one whole HTML document, which Ta plays in the reply in a frame of its own (full screen on a phone) and can send to a group chat to play together.
117
+ Make it for them, from what you know of them (their level, the mistakes they made before, what they like, their language), not a generic game: one clear goal, a round of 1 to 3 minutes, feedback at once on each move (why a wrong answer is wrong, and the right one), harder as they do well, a reward they see (stars, a combo, a best score). What it teaches must be right.
118
+ The document: inline <style> and <script> only. It reaches nothing (no network, CDN, web fonts, files, frames or storage): draw with CSS, SVG or canvas, sound with Web Audio. Touch first (pointer events, big targets, no hover, no keyboard needed), filling the frame (100vw by 100vh; the frame's width over its height is <meta name="ta-aspect" content="3/4">, 4/5 without), legible on a phone, light or dark as prefers-color-scheme says; its <title> names it. Under 40 KB, whole and working: no placeholder, nothing left to fill in.
119
+ window.ta is there before the game's scripts: await ta.ready (or ta.on('ready', fn)); ta.me {id, name}; ta.players [{id, name, online, host, self}]; ta.solo; ta.saved, what it kept with ta.save(value) (a best score; localStorage is not kept); ta.finish({score, total, summary, mistakes: [{topic, note}]}) when a round ends: the user may send it to you, and you make the next round from it (harder where they did well, what they missed again in another form).
120
+ A game for several (a class, friends): read the skill ta-play first, which has a whole example. It says <meta name="ta-players" content="2-8">; its players are the members of the group chat it is sent to. ta.state is the state they share: ta.set(key, value) (JSON; the last write wins, so each player writes keys of their own, such as 'score:' + ta.me.id, and the host the rest: the round, the question, the order), ta.on('state', (key, value, by) => …) for the writes of the others; ta.send(data, to?) with ta.on('message', (data, from) => …) for moves that need not stay; ta.on('players', list => …). The host (who sent it, host in ta.players) starts the rounds, the others wait for it, one who joins late reads ta.state; played alone it still works, with one player.
121
+ After the block, a line at most: what it is and how to play.`;
122
+
123
+ // web-src/extension.ts
124
+ function activate(pi) {
125
+ let served;
126
+ const underServe = () => served ??= TaHostUtil.reach(pi.events, NAME).then((answer) => answer !== undefined);
127
+ pi.on("session_start", () => {
128
+ underServe();
129
+ });
130
+ pi.on("before_agent_start", async (event) => {
131
+ if (await underServe()) {
132
+ event.systemPromptOptions.sections = { ...event.systemPromptOptions.sections, [LANGUAGE]: PLAY_PROMPT };
133
+ }
134
+ });
135
+ }
136
+ export {
137
+ activate as default
138
+ };
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@celljs/ta-play",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.31.0",
4
+ "description": "A pi package for Ta: games in replies, made for the one who plays, played alone or together in a group chat",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "homepage": "https://github.com/cellbang/ta",
9
+ "bugs": {
10
+ "url": "https://github.com/cellbang/ta/issues"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/cellbang/cell.git"
15
+ },
16
+ "license": "MIT",
17
+ "files": [
18
+ "web",
19
+ "extension",
20
+ "skills",
21
+ "!**/*.map"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsc -b && bun build web-src/index.tsx --format esm --target browser --outfile web/index.js && bun build web-src/extension.ts --format esm --target node --outfile extension/index.mjs",
25
+ "clean": "rm -rf lib web extension *.tsbuildinfo",
26
+ "test": "bun test ./lib",
27
+ "watch": "tsc -b -w --preserveWatchOutput"
28
+ },
29
+ "devDependencies": {
30
+ "@celljs/ta-protocol": "4.31.0",
31
+ "@celljs/ta-web": "4.31.0",
32
+ "@types/react": "^19.3.0"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "pi": {
38
+ "title": {
39
+ "en": "Playable replies",
40
+ "zh-CN": "能玩的回复",
41
+ "zh-TW": "能玩的回覆",
42
+ "ja-JP": "遊べる返信"
43
+ },
44
+ "summary": {
45
+ "en": "When something is better played than read, Ta answers with a little game made for you, from what it knows of you: played in the reply, or with friends and classmates in a group chat.",
46
+ "zh-CN": "适合玩着学、玩着看的内容,Ta 直接回复一个按你定做的小游戏:在回复里就能玩,也能发到群里和朋友、同学一起玩。",
47
+ "zh-TW": "適合邊玩邊學、邊玩邊看的內容,Ta 直接回覆一個為你量身做的小遊戲:在回覆裡就能玩,也能發到群裡和朋友、同學一起玩。",
48
+ "ja-JP": "読むより遊んだほうが分かることには、Ta があなた向けの小さなゲームで返信します。返信の中で遊べて、グループチャットで友だちやクラスメートとも一緒に遊べます。"
49
+ },
50
+ "icon": "Gamepad2",
51
+ "web": [
52
+ "./web/index.js"
53
+ ],
54
+ "extensions": [
55
+ "./extension/index.mjs"
56
+ ],
57
+ "skills": [
58
+ "./skills"
59
+ ],
60
+ "sections": [
61
+ "ta-play"
62
+ ]
63
+ }
64
+ }
@@ -0,0 +1,29 @@
1
+ ---
2
+ name: ta-play
3
+ description: How to write a game of a reply (a ta-play block) that several play together in a group chat, a class or friends: who drives the rounds, what each writes, joining late, a timer all share, games that help everyone learn. Read it before writing a ta-play game for several.
4
+ ---
5
+
6
+ # Games for several in Ta
7
+
8
+ A `ta-play` block is one HTML document, played in a frame that reaches nothing; `window.ta` is all it has (the section `<ta-play>` of the system prompt says its fields). Sent to a group chat with Play together, it is played by the members there, each on their own Ta: the same document runs on every one, and they agree only through `ta.state` and `ta.send`. `examples/class-quest.html` beside this file is a whole one that works: read it before writing one, and follow its shape.
9
+
10
+ ## Who writes what
11
+
12
+ - **The host drives.** Who sent it is `host` in `ta.players` (`ta.me.host`); played alone, `ta.solo` and the one player is host. Only the host writes what all follow: the round (`ta.set('round', {i, at: Date.now()})`), the questions if they are drawn at random, the teams, the order of turns, the end. The others wait for it: "等 … 开始".
13
+ - **Each writes only their own keys**, named by their id: `'answer:' + ta.me.id`, `'stars:' + ta.me.id`. The last write of a key wins, so two players never write one key; a total is the sum the page makes of everyone's keys.
14
+ - **`ta.send(data, to?)`** for what need not stay (a move to the host, a reaction); `ta.on('message', (data, from) => …)`. What one who joins late must see goes in the state.
15
+ - **State is the truth.** Draw from `ta.state` on `ta.ready` and on every `ta.on('state', key => …)`: one who joins late or loads again is where the others are, with no history to replay. What a player answered stays in their keys, so their screen is the same after a reload.
16
+ - **One clock.** The host writes when a round began (`at`); everyone counts down from it, so all see the same time left. The host moves on when the time is up or every online player answered (`ta.players` with `online`), never waiting for one who left.
17
+ - **Your own writes are not echoed**: after `ta.set` draw yourself; `ta.on('state')` brings the others' writes.
18
+
19
+ ## Games that help a class learn
20
+
21
+ - **Everyone answers every question**, then sees at once whether they were right and why. A race where only the fastest scores leaves the slow ones out; speed may add a little, never decide alone.
22
+ - **A goal of the whole class**: stars of all filling one bar, a treasure opened together, a monster all hit. Each one's effort helps everyone, and nobody is last.
23
+ - **Show the count, not a ranking**: "8 / 12 answered", the class total. The page shows each one's score to the host alone (Results under the game), never a list of who came last.
24
+ - Kinds that work: everyone answers (the example), a relay (turns in an order the host wrote, the others watch), teams (the host splits `ta.players`, each team's total), pairs (the host pairs them, each pair its keys), draw and guess (the drawer `ta.send`s strokes, guesses go to the drawer).
25
+ - **End each player's round with `ta.finish`** (their score, total, mistakes): the host sees everyone's in the card it sent and can ask Ta for the next round of the whole class, what many missed coming back in another form.
26
+
27
+ ## Keep it small
28
+
29
+ Under 40 KB, a few hundred lines; questions in an array at the top, made for this class (its level, what it missed before). Touch first, big buttons, `prefers-color-scheme` for dark. 20 writes a second at most a player: write on a move, never in a loop.
@@ -0,0 +1,169 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <title>分数闯关 · 全班一起</title>
5
+ <meta name="ta-players" content="1-50">
6
+ <meta name="ta-aspect" content="3/4">
7
+ <style>
8
+ :root { --bg: #fff8ec; --card: #fff; --ink: #1f2a37; --muted: #64748b; --ok: #16a34a; --no: #dc2626; --gold: #f59e0b; }
9
+ @media (prefers-color-scheme: dark) { :root { --bg: #17181c; --card: #24262c; --ink: #f1f5f9; --muted: #94a3b8; } }
10
+ * { box-sizing: border-box; }
11
+ body { margin: 0; height: 100vh; display: flex; flex-direction: column; background: var(--bg); color: var(--ink); font: 16px/1.5 -apple-system, system-ui, sans-serif; }
12
+ header { display: flex; align-items: center; gap: 10px; padding: 12px 16px 6px; font-weight: 600; }
13
+ header .grow { flex: 1; }
14
+ .goal { margin: 0 16px; height: 10px; border-radius: 5px; background: rgba(127,127,127,.18); overflow: hidden; }
15
+ .goal > i { display: block; height: 100%; width: 0; background: linear-gradient(90deg, #f59e0b, #22c55e); transition: width .4s; }
16
+ .goal-text { margin: 4px 16px 0; font-size: 13px; color: var(--muted); }
17
+ main { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; padding: 0 18px; text-align: center; }
18
+ .q { font-size: 26px; font-weight: 700; }
19
+ .opts { display: grid; gap: 10px; width: 100%; max-width: 360px; }
20
+ button { font: inherit; font-size: 20px; font-weight: 600; padding: 14px; border: 0; border-radius: 14px; background: var(--card); color: var(--ink); box-shadow: 0 2px 0 rgba(0,0,0,.12); }
21
+ button:active { transform: translateY(1px); }
22
+ button.ok { background: #d1fae5; color: #065f46; } button.no { background: #fee2e2; color: #7f1d1d; }
23
+ button.go { background: var(--ink); color: var(--bg); padding: 14px 32px; }
24
+ .why { min-height: 48px; font-size: 15px; color: var(--muted); }
25
+ .who { font-size: 14px; color: var(--muted); }
26
+ .timer { font-variant-numeric: tabular-nums; color: var(--muted); }
27
+ </style>
28
+ </head>
29
+ <body>
30
+ <header><span class="grow" id="round">准备</span><span class="timer" id="timer"></span><span id="mine">★ 0</span></header>
31
+ <div class="goal"><i id="bar"></i></div>
32
+ <div class="goal-text" id="goal"></div>
33
+ <main id="main"></main>
34
+ <script>
35
+ // Questions made for this class: what they missed last time comes back in another form.
36
+ const Q = [
37
+ { q: '1/2 + 1/4 = ?', o: ['3/4', '2/6', '1/3'], a: 0, why: '先通分:1/2 = 2/4,2/4 + 1/4 = 3/4', t: '异分母加法' },
38
+ { q: '2/3 和 3/5 哪个大?', o: ['2/3', '3/5', '一样大'], a: 0, why: '通分比较:10/15 > 9/15', t: '比较大小' },
39
+ { q: '0.25 = ?', o: ['1/5', '1/4', '2/5'], a: 1, why: '0.25 = 25/100 = 1/4', t: '小数化分数' },
40
+ ];
41
+ const SECONDS = 15;
42
+ const GOAL = 2; // stars the class needs per player to open the treasure
43
+ const $ = id => document.getElementById(id);
44
+ let me, answered = {}, mine = 0, wrong = [], tick;
45
+
46
+ const host = () => ta.solo || ta.me.host;
47
+ const players = () => ta.players.filter(p => p.online);
48
+ // Each player writes only their own keys; the host alone writes the round.
49
+ const stars = () => ta.players.reduce((sum, p) => sum + (ta.state['stars:' + p.id] || 0), 0);
50
+
51
+ function goal() {
52
+ const need = GOAL * Math.max(1, ta.players.length);
53
+ $('bar').style.width = Math.min(100, (100 * stars()) / need) + '%';
54
+ $('goal').textContent = stars() >= need ? '全班一起打开了宝箱!' : '全班星星 ' + stars() + ' / ' + need + ' · 一起打开宝箱';
55
+ }
56
+
57
+ let seen = -1;
58
+ function show() {
59
+ clearInterval(tick);
60
+ const round = ta.state.round;
61
+ if (!round) return waiting();
62
+ // A question gone by unanswered is one to practise too.
63
+ const now = round.end ? Q.length : round.i;
64
+ for (let i = Math.max(0, seen); i < now; i++) {
65
+ if (seen >= 0 && !answered[i]) {
66
+ answered[i] = { k: -1, why: '' };
67
+ wrong.push({ topic: Q[i].t, note: '没来得及答' });
68
+ }
69
+ }
70
+ seen = Math.max(seen, now);
71
+ keep();
72
+ if (round.end) return end();
73
+ const x = Q[round.i];
74
+ $('round').textContent = '第 ' + (round.i + 1) + ' / ' + Q.length + ' 题';
75
+ const done = answered[round.i];
76
+ $('main').innerHTML = '<div class="q">' + x.q + '</div><div class="opts">' +
77
+ x.o.map((o, k) => '<button data-k="' + k + '" class="' + (done ? (k === x.a ? 'ok' : k === done.k ? 'no' : '') : '') + '">' + o + '</button>').join('') +
78
+ '</div><div class="why" id="why">' + (done ? done.why : '') + '</div><div class="who" id="who"></div>';
79
+ document.querySelectorAll('.opts button').forEach(b => (b.onclick = () => pick(round.i, +b.dataset.k)));
80
+ who();
81
+ // The host's clock, so that everyone sees the same time left, joined late or not.
82
+ tick = setInterval(() => {
83
+ const left = Math.max(0, Math.ceil((round.at + SECONDS * 1000 - Date.now()) / 1000));
84
+ $('timer').textContent = left + 's';
85
+ if (host() && (left === 0 || everyone(round.i))) next(round.i);
86
+ }, 250);
87
+ }
88
+
89
+ function everyone(i) {
90
+ return players().every(p => (ta.state['answer:' + p.id] || {}).i === i);
91
+ }
92
+
93
+ function who() {
94
+ const round = ta.state.round;
95
+ if (!round || ta.solo || !$('who')) return;
96
+ const n = players().filter(p => (ta.state['answer:' + p.id] || {}).i === round.i).length;
97
+ $('who').textContent = n + ' / ' + players().length + ' 人已作答';
98
+ }
99
+
100
+ function pick(i, k) {
101
+ if (answered[i]) return;
102
+ const x = Q[i];
103
+ const right = k === x.a;
104
+ answered[i] = { k, why: (right ? '答对了!' : '再想想:') + x.why };
105
+ if (right) mine++;
106
+ else wrong.push({ topic: x.t, note: x.why });
107
+ $('mine').textContent = '★ ' + mine;
108
+ ta.set('answer:' + ta.me.id, { i, k });
109
+ ta.set('stars:' + ta.me.id, mine);
110
+ keep();
111
+ show();
112
+ goal();
113
+ }
114
+
115
+ // What I answered and missed, in my own key: the same after a reload or on another device.
116
+ function keep() {
117
+ ta.set('mine:' + ta.me.id, { answered, wrong, seen });
118
+ }
119
+
120
+ function next(i) {
121
+ if ((ta.state.round || {}).i !== i || ta.state.round.end) return;
122
+ ta.set('round', i + 1 < Q.length ? { i: i + 1, at: Date.now() } : { end: true });
123
+ show();
124
+ }
125
+
126
+ function waiting() {
127
+ $('round').textContent = '准备';
128
+ $('timer').textContent = '';
129
+ $('main').innerHTML = host()
130
+ ? '<div class="q">分数闯关</div><div class="who">' + players().length + ' 人在线 · 每题 ' + SECONDS + ' 秒,人人都答</div><button class="go" id="go">开始</button>'
131
+ : '<div class="q">等 ' + ((ta.players.find(p => p.host) || {}).name || '发起人') + ' 开始</div>';
132
+ if (host()) $('go').onclick = () => { ta.set('round', { i: 0, at: Date.now() }); show(); };
133
+ }
134
+
135
+ let finished = false;
136
+ function end() {
137
+ $('round').textContent = '结束';
138
+ $('timer').textContent = '';
139
+ const best = Math.max(mine, (ta.saved && ta.saved.best) || 0);
140
+ $('main').innerHTML = '<div class="q">' + mine + ' / ' + Q.length + '</div><div class="why">' +
141
+ (wrong.length ? '要再练:' + wrong.map(w => w.topic).join('、') : '全对!') + '</div><div class="who">最好成绩 ' + best + '</div>';
142
+ if (!finished) {
143
+ finished = true;
144
+ ta.save({ best });
145
+ ta.finish({ score: mine, total: Q.length, summary: wrong.length ? undefined : '全对', mistakes: wrong });
146
+ }
147
+ }
148
+
149
+ ta.on('state', key => {
150
+ if (key === 'round') show();
151
+ else { who(); goal(); }
152
+ });
153
+ ta.on('players', () => { who(); goal(); });
154
+ ta.ready.then(() => {
155
+ mine = ta.state['stars:' + ta.me.id] || 0;
156
+ // Loaded again: what I answered and missed is in my keys.
157
+ const kept = ta.state['mine:' + ta.me.id];
158
+ if (kept) {
159
+ answered = kept.answered || {};
160
+ wrong = kept.wrong || [];
161
+ seen = typeof kept.seen === 'number' ? kept.seen : -1;
162
+ }
163
+ $('mine').textContent = '★ ' + mine;
164
+ goal();
165
+ show();
166
+ });
167
+ </script>
168
+ </body>
169
+ </html>