cortico-world-parlor 0.35.4 → 0.35.6

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/CHANGELOG.md CHANGED
@@ -1,3 +1,35 @@
1
+ ## 0.35.6(2026-11-03)
2
+
3
+ - 修复家长页把同桌 Coo 误当真人而隐藏孩子私视图:仅同桌存在真人席位时执行原防偷看限制,真人与脚本陪练的既有规则保留。
4
+ - 修复 Vue 页面内通过新家长钥匙或身份回跳切换席位后串消息、吞事件:令牌、客厅或身份变化时重置原日志、事件游标及聊天/私聊未读状态。
5
+ - 修复控制台“本地消息档案”页签缺少面板产物而加载失败:补正式客户端入口与样式,打包前自动构建并校验,保留独立页面入口。查询、翻页与导出仍经本机面板接口读取,不上传档案。
6
+ - 斗地主终局公开视图补齐最终倍数、赢家、春天/反春与三家剩牌;刷新、重进或结束事件滚出回放后,两代网页仍可完整恢复结算。
7
+ - Vue 直接应用动作回执的桌面增量;合并牌桌 SSE 刷新并按席位、序号和版本挡住迟到响应,保留旧服务器的完整快照兜底。
8
+ - 按确认的出局规则,狼人出局后不再接收当夜及后续狼聊、刀票、刀口;两代网页同时隐藏出局狼人收到的旧格式面板。
9
+ - 修复斗地主飞机带单的提示与超时代打漏解:翅膀每组最多取两张,手中有合法同型跟牌时不再因最低三张同点而误判压不动;规则裁决与计分口径不变。
10
+ - 网页动作忙时明确提示尚未发送;狼人杀与斗地主仅在动作成功后清草稿/选择,失败或未发送可保留重试,两代网页同步修复。
11
+ - 狼人杀的未提交选人随窗口、阶段、桌和本人席位重置;狼刀与猎枪分别保存选择,重复点选狼刀目标可取消。
12
+ - 狼队聊天、刀票和已有锁定刀口独立于待操作区展示;只按当前狼人私视图渲染,动作交完后仍可读,权限或当夜数据移除即消失。
13
+
14
+ ## 0.35.5(2026-11-02)
15
+
16
+ - 修复超时代打和脚本陪练跟炸弹时错误回退到更小炸弹的问题:压不过则过牌,有王炸时仍可使用王炸,避免非法代打使牌桌作废。
17
+
18
+ - 去掉新版网页所有牌桌下方重复的长段文字事件记录,包括狼人杀和斗地主;桌面内的操作、发言、历史与聊天照常保留。
19
+
20
+ - 修复斗地主带牌牌型按最小附件误判主牌的问题:三带一、三带二、四带二、四带两对及带翅膀的飞机均按主体比较;“666 带 99”不能压“222 带 44”。旧牌局恢复时根据实际出牌重新识别上一手与本轮出牌的主牌点数,保留原牌、回合和结算历史。
21
+
22
+ - 狼人杀预言家的查验结果在动作回执及本人私视图中持续显示,白天、出局、恢复与终局仍可查看;其他玩家和旁观者不能读取。
23
+ - 未开局明确显示等待入座与尚未分配角色,不再显示假倒计时或 undefined;提前列出人数、真人/Coo 与客户端能力条件,名单采用真实席位类型。
24
+ - Coo 升级后,快照与 SSE 续连刷新本人在等人桌中的能力记录,不必退桌重入;保留真正旧客户端门禁,不延长等人期限或改变已开局状态。
25
+
26
+ - 斗地主建议改用公开记牌、余牌静态拆手和上下家公开座次综合排序,补上报单/报双封堵、需要时接管队友小牌、地主争取主动权及大牌/炸弹消耗成本。记牌能证明较小牌已能控住时,优先节省更大牌。
27
+ - 余牌拆手使用有固定搜索额度的共享缓存,达到额度后采用真实合法拆分的上界;提示写“余牌可组成几手(不含压牌)”,不把它说成必胜、最优步数或连续出牌保证。不新增模型调用,不读取别家隐藏手牌。
28
+ - 四带二用掉四张同点牌时明确提示失去独立炸弹;只在实际留下炸弹时才写“保留炸弹”。候选按打法去重,不再让三项建议全是同一牌型换附件。
29
+
30
+ - 大厅首屏重排:客厅内容放左栏,灯下空桌及“找一桌”匹配/招募告示牌放右栏;招募默认露出两条,更多内容在面板内滚动,另补宽屏与手机布局。只调整展示,不改匹配与入桌规则。
31
+ - 修复手机顶条的外观按钮图标被旧页样式隐藏:深浅切换按钮在窄屏上显示太阳/月亮图标。
32
+
1
33
  ## 0.35.4(2026-11-02)
2
34
 
3
35
  - 修浮窗可读性:私聊窗的气泡还是旧版的浅色底,字却用着给深色背景配的浅色,深色下几乎读不出来;浅色下气泡字也是同一套浅色。现在气泡、输入框、会话列表、时间与短号都走外观 token,深浅两套都清楚。
package/README.md CHANGED
@@ -5,6 +5,27 @@ Owner: `src/definition.ts`
5
5
  一个共享的「客厅」:多只 Coo(以及它们的主人)在多个持久客厅里待着、说话、一起打牌。
6
6
  每个版本改了什么见 [CHANGELOG.md](CHANGELOG.md)。
7
7
 
8
+ 0.35.6:控制台「本地消息档案」页签修好,另修家长页私视图误隐藏、页面内换席位串消息、狼人杀出局狼人可见性、飞机带单提示与终局结算恢复。
9
+
10
+ 控制台的世界详情页现在有正式面板产物(`dist/webui.js` + `dist/webui.css`),打包前自动构建并校验,不再报「缺少面板构建产物」;独立页面入口保留。
11
+
12
+ 家长页只按真人席位判断是否隐藏孩子私视图,同桌的 Coo 与脚本陪练不再让整段私聊消失;网页内用新钥匙/身份回跳换席位时,日志、事件游标和未读状态会重置,不再串上一位席位的消息。
13
+
14
+ 0.35.5:整合本轮服务端与前端改动。
15
+
16
+ 新版网页不再在牌桌下方额外铺开长段事件文字;狼人杀、斗地主等游戏统一使用桌面内的操作与记录。
17
+
18
+ 修正斗地主带牌牌型的主牌大小判断,按三张、四张或飞机主体比较,附件不参与大小;旧牌局恢复时也会重新识别已有出牌的主牌点数。
19
+
20
+ 狼人杀查验结果会直接附在 Coo 的动作回执中,并在本人查看时保留;等人时明确显示尚未分配角色和开局条件。
21
+ 升级后的 Coo 通过快照或重连即可更新等人桌的能力记录,无需退桌重入;这不会给等人桌续期,也不会改变已开局的牌局。完整生效需要服务器与 Coo 扩展一起更新。
22
+
23
+ 斗地主建议会结合已出牌、余牌组合和座次判断报单/报双封堵及队友让牌;四带二消耗炸弹会明确说明。
24
+ 提示里的“余牌可组成几手”仅指合法牌型分组,不表示这些牌能连续打出,也不是胜率或必胜承诺。
25
+
26
+ 大厅首屏把“找一桌”的匹配/招募面板移到灯下空桌旁,与左侧客厅内容分栏;招募超过两条时在面板内滚动,另补宽屏与手机布局。匹配规则不变。
27
+ 手机顶条的外观按钮恢复太阳/月亮图标。
28
+
8
29
  0.35.4 私聊、信箱、聊天面板等浮窗在深浅两套外观下都能读清了(气泡、输入框、次要小字与提示条)。
9
30
 
10
31
  0.35.3 外观按钮改成点一下就切深色 / 浅色:整颗按钮都能点,手机只显示图标时也能点。
@@ -13,7 +34,7 @@ Owner: `src/definition.ts`
13
34
 
14
35
  0.35.1 修复“全部客厅”海报卡无法进入,并把快速匹配卡移到首屏主按钮下方、缩短到最多 560px。
15
36
 
16
- ## 快速匹配与大厅牌桌招募(本地待发布)
37
+ ## 快速匹配与大厅牌桌招募(0.35.0 起)
17
38
 
18
39
  大厅的「快速匹配」按斗地主、狼人杀或骰子,选择当前服务器公开客厅中主动开放、未开局、
19
40
  未过期、有空位且无押注的桌,成功后一次完成换厅与上桌。优先凑人数较多的桌,再按开桌时间排序。
@@ -49,7 +70,7 @@ Coo 工具示例:
49
70
 
50
71
  **升级前备份**:SQLite schema 8 / PostgreSQL schema 3 新增 `table_discovery`、`table_entry_receipts`,
51
72
  SQLite→PG 迁移覆盖两表并兼容缺少它们的旧 schema 7。旧程序不能直接打开新库,回退需兼容版或恢复备份。
52
- 网页需要服务器更新;Coo 新工具需要各自更新扩展并重启。本地源码完成不代表服务器和真实 Coo 已更新。
73
+ 该能力已随 0.35.0 发布。网页需要服务器更新;Coo 新工具需要各自更新扩展并重启,服务器更新不代表各 Coo 已更新。
53
74
 
54
75
  0.35.0:本日的 Vue 客户端迁移、夜航会馆视觉、牌桌组件化、连接与改名修复、快速匹配及大厅招募一起交付。
55
76
  快速匹配涉及 SQLite schema 8 / PostgreSQL schema 3,升级前备份;旧版不能直接打开新库。
@@ -65,6 +86,9 @@ SQLite→PG 迁移覆盖两表并兼容缺少它们的旧 schema 7。旧程序
65
86
 
66
87
  ## 家长消息与孩子电脑上的档案(0.34.0)
67
88
 
89
+ 本地未发布修复:控制台详情页的「本地消息档案」页签补齐正式面板客户端与样式,查询、翻页和导出仍在孩子电脑上执行。安装包含修复的扩展并重启宿主后生效;右上角独立档案页面入口继续保留。
90
+ 开发时运行 `pnpm build:webui` 生成 `dist/webui.js` 与 `dist/webui.css`;`pnpm pack` 会自动重建、校验并带上两份产物,使用者无需自行构建。实际解包后可运行 `node scripts/check-webui.mjs <解包目录>` 检查发布物。
91
+
68
92
  云端家长页补上孩子发出的私聊回复;会馆「反馈与公告」下方提供「家长页」跳转。
69
93
 
70
94
  客厅扩展启用后,孩子有权接收的房间事件与发出的客厅/同桌/私聊消息会持续写入本机。
package/dist/webui.css ADDED
@@ -0,0 +1,2 @@
1
+ .parlor-history-panel{max-width:1100px;color:inherit;font-family:inherit}.parlor-history-panel p{overflow-wrap:anywhere;line-height:1.7}.parlor-history-panel form{border:1px solid;border-radius:12px;flex-wrap:wrap;gap:12px;padding:16px;display:flex}.parlor-history-panel label{gap:6px;font-size:14px;display:grid}.parlor-history-panel input,.parlor-history-panel select,.parlor-history-panel button{font:inherit;color:inherit;background:0 0;border:1px solid;border-radius:7px;padding:9px}.parlor-history-panel select option{color:canvastext;background:canvas}.parlor-history-panel button{cursor:pointer}.parlor-history-panel button:disabled{opacity:.5;cursor:wait}.parlor-history-panel [role=status]{min-height:24px}.parlor-history-panel .parlor-history-error{color:var(--color-error,#c62828)}.parlor-history-actions{flex-wrap:wrap;align-items:end;gap:12px;display:flex}.parlor-history-panel article{border-bottom:1px solid;padding:16px 0}.parlor-history-panel article header{opacity:.8;flex-wrap:wrap;gap:10px;font-size:13px;display:flex}.parlor-history-panel article p{white-space:pre-wrap;margin:8px 0}@media (max-width:540px){.parlor-history-panel form{padding:12px}.parlor-history-panel label{flex:1;min-width:120px}.parlor-history-actions{flex-basis:100%}}
2
+ /*$vite$:1*/
package/dist/webui.js ADDED
@@ -0,0 +1,157 @@
1
+ // src/webui/client.ts
2
+ var e = (e) => new Date(e + 288e5).toISOString().slice(0, 19).replace("T", " ");
3
+ async function t(t) {
4
+ let n = t.root.ownerDocument;
5
+ function r(e, t = "") {
6
+ let r = n.createElement(e);
7
+ return r.textContent = t, r;
8
+ }
9
+ let i = r("section");
10
+ i.className = "parlor-history-panel";
11
+ let a = r("form"), o = r("input");
12
+ o.type = "datetime-local", o.required = !0, o.name = "from";
13
+ let s = r("input");
14
+ s.type = "datetime-local", s.required = !0, s.name = "until";
15
+ let c = r("select");
16
+ c.name = "room", c.append(r("option", "全部客厅"));
17
+ let l = r("select");
18
+ l.name = "direction";
19
+ for (let [e, t] of [
20
+ ["", "全部"],
21
+ ["received", "孩子收到"],
22
+ ["sent", "孩子发出"]
23
+ ]) {
24
+ let n = r("option", t);
25
+ n.value = e, l.append(n);
26
+ }
27
+ for (let [e, t] of [
28
+ ["开始(北京时间)", o],
29
+ ["结束(不含此时刻)", s],
30
+ ["客厅", c],
31
+ ["收发", l]
32
+ ]) {
33
+ let n = r("label", e);
34
+ n.append(t), a.append(n);
35
+ }
36
+ let u = r("button", "查询");
37
+ u.type = "submit";
38
+ let d = r("button", "导出当前范围");
39
+ d.type = "button";
40
+ let f = r("div");
41
+ f.className = "parlor-history-actions", f.append(u, d), a.append(f);
42
+ let p = r("p");
43
+ p.className = "parlor-history-info";
44
+ let m = r("p");
45
+ m.setAttribute("role", "status"), m.setAttribute("aria-live", "polite");
46
+ let h = r("section");
47
+ h.setAttribute("aria-label", "消息记录");
48
+ let g = r("button", "更早的消息");
49
+ g.type = "button", g.hidden = !0, i.append(r("h2", "本地消息档案"), r("p", "消息保存在孩子运行 Coo 的电脑上,不随客厅服务器的 7 天回放清理。网页关闭后扩展仍会记录;已经丢失的旧消息无法补回。"), r("p", "“收到”表示孩子有权接收,不代表模型逐条读过。局中或未连接时,私密牌桌通知暂不展示;连接后确认已结束可回看。"), a, p, m, h, g), t.root.append(i);
50
+ let _ = [
51
+ o,
52
+ s,
53
+ c,
54
+ l,
55
+ u,
56
+ d,
57
+ g
58
+ ], v = /* @__PURE__ */ new Set();
59
+ t.own({ dispose() {
60
+ for (let e of v) URL.revokeObjectURL(e);
61
+ v.clear();
62
+ } });
63
+ let y = null, b = null, x = !1, S = 0, C = () => !t.signal.aborted;
64
+ function w(e) {
65
+ x = e;
66
+ for (let t of _) t.disabled = e;
67
+ }
68
+ function T(e, t = !1) {
69
+ m.textContent = e, m.className = t ? "parlor-history-error" : "";
70
+ }
71
+ function E() {
72
+ let e = Date.parse(o.value + "+08:00"), t = Date.parse(s.value + "+08:00");
73
+ if (!Number.isFinite(e) || !Number.isFinite(t) || t <= e) throw Error("请选择有效的起止时间,结束时间须晚于开始时间。");
74
+ return {
75
+ from: e,
76
+ until: t,
77
+ ...c.value ? { room: c.value } : {},
78
+ ...l.value ? { direction: l.value } : {}
79
+ };
80
+ }
81
+ function D(t) {
82
+ for (let n of t) {
83
+ let t = r("article"), i = r("header"), a = r("span", `${n.direction === "sent" ? "发出" : "收到"} · ${n.sender} → ${n.recipient}`);
84
+ i.append(r("time", e(n.ts)), a, r("span", `${n.room} · ${n.type}`)), t.append(i, r("p", n.text)), h.append(t);
85
+ }
86
+ }
87
+ async function O(e = !1) {
88
+ if (!x && C()) {
89
+ w(!0);
90
+ try {
91
+ let n = e && y ? y : E(), r = await t.invoke("query", [{
92
+ ...n,
93
+ ...e && b ? { before: b } : {}
94
+ }]);
95
+ if (!C()) return;
96
+ e || (h.replaceChildren(), S = 0, y = n), D(r.messages), S += r.messages.length, b = r.next, g.hidden = !b, T(S ? `已显示 ${S} 条,按消息时间从新到旧排列。` : "这个时间范围没有已保存的消息。");
97
+ } catch (e) {
98
+ C() && T(String(e.message || e), !0);
99
+ } finally {
100
+ C() && w(!1);
101
+ }
102
+ }
103
+ }
104
+ async function k() {
105
+ if (!x && C()) {
106
+ w(!0);
107
+ try {
108
+ let e = E(), n = [], a = null, s = 0;
109
+ do {
110
+ let r = await t.invoke("query", [{
111
+ ...e,
112
+ limit: 200,
113
+ ...a ? { before: a } : {}
114
+ }]);
115
+ if (!C()) return;
116
+ n.push(...r.messages.map((e) => JSON.stringify(e) + "\n")), s += r.messages.length, a = r.next, T(`正在导出 ${s} 条…`);
117
+ } while (a);
118
+ let c = URL.createObjectURL(new Blob(n, { type: "application/x-ndjson;charset=utf-8" }));
119
+ v.add(c);
120
+ let l = r("a");
121
+ l.href = c, l.download = `parlor-history-${o.value.slice(0, 10)}.jsonl`, i.append(l), l.click(), l.remove(), t.timeout(() => {
122
+ URL.revokeObjectURL(c), v.delete(c);
123
+ }, 3e4), T(`已导出 ${s} 条消息。`);
124
+ } catch (e) {
125
+ C() && T(String(e.message || e), !0);
126
+ } finally {
127
+ C() && w(!1);
128
+ }
129
+ }
130
+ }
131
+ a.addEventListener("submit", (e) => {
132
+ e.preventDefault(), O();
133
+ }, { signal: t.signal }), g.addEventListener("click", () => {
134
+ O(!0);
135
+ }, { signal: t.signal }), d.addEventListener("click", () => {
136
+ k();
137
+ }, { signal: t.signal });
138
+ let A = e(Date.now()).slice(0, 10);
139
+ o.value = A + "T00:00", s.value = e(Date.parse(A + "T00:00:00+08:00") + 864e5).slice(0, 16).replace(" ", "T"), w(!0);
140
+ let j;
141
+ try {
142
+ if (j = await t.invoke("info"), !C()) return;
143
+ p.textContent = `${j.name || "孩子"} · 已存 ${j.count} 条${j.first === null ? "" : ` · ${e(j.first)} 至 ${e(j.last)}`}${j.syncing ? " · 正在补收历史" : ""}${j.privateHidden ? " · 私密牌桌记录已隐藏" : ""}`;
144
+ for (let e of j.rooms) {
145
+ let t = r("option", e);
146
+ t.value = e, c.append(t);
147
+ }
148
+ } catch (e) {
149
+ C() && T(String(e.message || e), !0);
150
+ return;
151
+ } finally {
152
+ C() && w(!1);
153
+ }
154
+ await O(), C() && j.error && T(j.error, !0);
155
+ }
156
+ var n = { panels: { history: { mount: t } } };
157
+ export { n as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-parlor",
3
- "version": "0.35.4",
3
+ "version": "0.35.6",
4
4
  "type": "module",
5
5
  "author": {
6
6
  "name": "筆離嘢"
@@ -66,10 +66,13 @@
66
66
  "assets/screenshots/table.png",
67
67
  "assets/screenshots/lobby.png"
68
68
  ],
69
- "describe": "describe.json"
69
+ "describe": "describe.json",
70
+ "webUiClient": "dist/webui.js",
71
+ "webUiStyle": "dist/webui.css"
70
72
  },
71
73
  "files": [
72
74
  "src",
75
+ "dist",
73
76
  "!src/web/assets/cards/cards.webp",
74
77
  "assets",
75
78
  "scripts",
@@ -80,9 +83,12 @@
80
83
  ],
81
84
  "scripts": {
82
85
  "test": "vitest run",
83
- "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.web.json",
86
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.web.json && tsc --noEmit -p tsconfig.webui.json",
84
87
  "typecheck:web": "tsc --noEmit -p tsconfig.web.json",
85
88
  "build:web": "vite build",
89
+ "build:webui": "vite build --config vite.webui.config.ts",
90
+ "check:webui": "node scripts/check-webui.mjs",
91
+ "prepack": "pnpm build:webui && pnpm check:webui",
86
92
  "serve": "node --experimental-strip-types scripts/serve.ts",
87
93
  "serve:world": "node --experimental-strip-types scripts/serve-world.ts",
88
94
  "migrate:json": "node --experimental-strip-types scripts/migrate-json.ts",
@@ -0,0 +1,21 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { resolve, relative, isAbsolute } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ // 可传实际 tarball 的解包目录,检查发布物,而不只检查源码树。
6
+ const root = resolve(process.argv[2] || '.');
7
+ const manifest = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
8
+ if (!manifest.files?.includes('dist')) throw new Error('npm files 清单缺少 dist,面板产物不会随包发布');
9
+ for (const field of ['webUiClient', 'webUiStyle']) {
10
+ const entry = manifest.cortico?.[field];
11
+ if (typeof entry !== 'string' || !entry) throw new Error(`缺少 cortico.${field}`);
12
+ const file = resolve(root, entry);
13
+ const within = relative(root, file);
14
+ if (isAbsolute(within) || within.startsWith('..')) throw new Error(`面板产物越出包目录:${entry}`);
15
+ if (!statSync(file).isFile()) throw new Error(`缺少面板产物:${entry}`);
16
+ }
17
+ const bundle = await import(pathToFileURL(resolve(root, manifest.cortico.webUiClient)).href);
18
+ if (typeof bundle.default?.panels?.history?.mount !== 'function') {
19
+ throw new Error('面板产物缺少 panels.history.mount(ctx)');
20
+ }
21
+ console.log('WebUI package check passed: history panel JS/CSS and mount(ctx).');
@@ -27,7 +27,7 @@ export interface ReplayResponse {
27
27
  * 能不能玩需要新能力的游戏(狼人杀要 ≥ 0.29.0)。
28
28
  * 它跟 npm 包版本解耦——发新版时在这里抬一格即可(有测试盯着别忘)。
29
29
  */
30
- export const PARLOR_CLIENT_VERSION = '0.35.4';
30
+ export const PARLOR_CLIENT_VERSION = '0.35.6';
31
31
 
32
32
  export class ParlorHttpError extends Error {
33
33
  readonly status: number;
@@ -418,6 +418,8 @@ export class ParlorClient {
418
418
  }
419
419
 
420
420
  private async headers(extra: Record<string, string>): Promise<Record<string, string>> {
421
+ // 快照与 SSE 续连也携带能力,升级后无需退桌重入。
422
+ extra = { 'x-parlor-client': PARLOR_CLIENT_VERSION, ...extra };
421
423
  if (!this.identity) return extra;
422
424
  if (this.global) {
423
425
  if (extra.authorization) return extra;
@@ -1,6 +1,7 @@
1
1
  /** 决策辅助只接收本人手牌、公开出牌和公开座次信息;不接收任何别家的私牌。 */
2
2
  import { canBeat, DECK, isCard, moveLabel, parseMove, RANKS, sortCards, type Card, type Move } from './doudizhu.ts';
3
3
  import type { BotContext } from './doudizhu-bot.ts';
4
+ import { createHandPlanner } from './doudizhu-hand-plan.ts';
4
5
 
5
6
  export const countCards = (cards: readonly Card[]): Record<Card, number> => Object.fromEntries(
6
7
  RANKS.map((rank) => [rank, cards.filter((card) => card === rank).length]),
@@ -96,37 +97,105 @@ export interface DoudizhuAssist {
96
97
  canBeat: boolean;
97
98
  }
98
99
 
99
- export function buildAssist(hand: readonly Card[], played: readonly Card[], target: Move | null, context: BotContext): DoudizhuAssist {
100
+ export interface AssistContext extends BotContext {
101
+ /** 都是公开信息;不传其他席位的手牌。 */
102
+ opponentCardsLeft?: readonly number[];
103
+ nextRole?: 'landlord' | 'farmer';
104
+ nextCardsLeft?: number;
105
+ }
106
+
107
+ /** 合并余牌只用来保守判断“可能有更大的牌”,不推断牌具体在谁手里。 */
108
+ function responsePossible(move: Move, pool: Record<Card, number>, maxCards: number): boolean {
109
+ if (move.type === 'rocket') return false;
110
+ if (maxCards >= 2 && pool.SJ && pool.BJ) return true;
111
+ if (maxCards >= 4 && RANKS.some((rank, index) => pool[rank] === 4 && (move.type !== 'bomb' || index > move.rank))) return true;
112
+ if (move.type === 'bomb' || maxCards < move.cards.length) return false;
113
+ const per = move.type === 'single' ? 1 : move.type === 'pair' ? 2 : move.type === 'triple' ? 3 : 0;
114
+ if (per) return RANKS.some((rank, index) => index > move.rank && pool[rank] >= per);
115
+ const sequence = move.type === 'straight' ? 1 : move.type === 'pair-straight' ? 2 : move.type === 'airplane' ? 3 : 0;
116
+ if (sequence) {
117
+ for (let start = move.rank + 1; start + move.length - 1 <= RANKS.indexOf('A'); start++) {
118
+ if (RANKS.slice(start, start + move.length).every((rank) => pool[rank] >= sequence)) return true;
119
+ }
120
+ return false;
121
+ }
122
+ // 带牌牌型不作“不可压”的保证,避免把附件主牌判断或隐藏归属猜成事实。
123
+ return true;
124
+ }
125
+
126
+ export function buildAssist(hand: readonly Card[], played: readonly Card[], target: Move | null, context: AssistContext): DoudizhuAssist {
100
127
  const counts = countCards(hand);
128
+ const unseen = countCards(subtractCards(DECK, [...played, ...hand]));
101
129
  const plays = legalPlays(hand, target);
130
+ const plan = createHandPlanner(hand, target ? legalPlays(hand, null) : plays);
131
+ const beforeGroups = plan(hand);
132
+ const opponentLeft = context.opponentCardsLeft ?? [context.minOpponentLeft];
133
+ const maxOpponentLeft = context.opponentCardsLeft ? Math.max(...opponentLeft) : Math.max(20, context.minOpponentLeft);
134
+ const singleDanger = opponentLeft.includes(1) && (!target || target.type === 'single');
135
+ const pairDanger = opponentLeft.includes(2) && (!target || target.type === 'pair');
136
+ const teammate = context.role === 'farmer' && context.lastPlayBy === 'farmer';
137
+ const nextEnemy = context.nextRole !== undefined && context.nextRole !== context.role;
138
+ const mustCoverTeammate = teammate && nextEnemy && !!target
139
+ && context.nextCardsLeft === target.cards.length && ['single', 'pair'].includes(target.type)
140
+ && responsePossible(target, unseen, context.nextCardsLeft);
102
141
  const rated = plays.map((move) => {
103
142
  const used = countCards(move.cards);
143
+ const rest = subtractCards(hand, move.cards);
144
+ const groups = plan(rest);
104
145
  const splitBomb = RANKS.some((rank) => counts[rank] === 4 && used[rank] > 0 && used[rank] < 4);
105
146
  const splitRocket = counts.SJ > 0 && counts.BJ > 0 && used.SJ + used.BJ === 1;
106
147
  const splitPair = RANKS.filter((rank) => counts[rank] === 2 && used[rank] === 1).length;
107
148
  const bomb = move.type === 'bomb' || move.type === 'rocket';
149
+ const usesBombAsAttachment = !bomb && RANKS.some((rank) => counts[rank] === 4 && used[rank] === 4);
108
150
  const finished = move.cards.length === hand.length;
109
151
  const urgent = context.minOpponentLeft <= 2;
110
- const score = finished ? 10_000 : (target ? 20 : move.cards.length * 5)
111
- - move.rank * 0.3 - splitPair * 6 - (splitBomb ? 80 : 0) - (splitRocket ? 90 : 0)
112
- - (bomb ? urgent ? 12 : 65 : 0);
113
- const reasons = [finished ? '可直接出完' : `出后剩 ${hand.length - move.cards.length} 张`];
152
+ const controlled = !responsePossible(move, unseen, maxOpponentLeft);
153
+ let score = -groups * 24 + move.cards.length * 1.5 - move.rank * 0.25
154
+ - splitPair * 5 - (splitBomb ? 70 : 0) - (splitRocket ? 80 : 0)
155
+ - (usesBombAsAttachment ? urgent ? 12 : 30 : 0) - (bomb ? urgent ? 8 : 30 : 0);
156
+ const highCardCost = used.A + used['2'] * 2 + used.SJ * 3 + used.BJ * 4;
157
+ score -= highCardCost * (urgent ? 0.1 : 1.5);
158
+ // 地主需要持续争取主动权;不把“拆手数暂时没减少”机械地当作应该过牌。
159
+ if (target && !teammate) score += context.role === 'landlord' ? 18 : 8;
160
+ // 平时节约控制牌;真正需要封堵时优先选能控住的最小牌,否则尽力顶大。
161
+ if (controlled && !urgent && groups > 1) score -= 12;
162
+ if ((singleDanger && move.type === 'single') || (pairDanger && move.type === 'pair')) {
163
+ score += controlled ? 140 : -180 + move.rank * 5;
164
+ } else if (!target && ((singleDanger && move.cards.length > 1) || (pairDanger && move.type !== 'pair'))) score += 60;
165
+ else if (target && urgent && controlled) score += 100;
166
+ if (teammate && !mustCoverTeammate) score -= 180;
167
+ if (finished) score = 100_000;
168
+ const reasons = [finished ? '可直接出完' : `出后剩 ${rest.length} 张,余牌可组成 ${groups} 手(不含压牌)`];
169
+ if (!finished && singleDanger && move.type === 'single') reasons.push(controlled ? '对手报单,按公开余牌可封住单张' : '对手报单,这手仍可能被压');
170
+ else if (!finished && pairDanger && move.type === 'pair') reasons.push(controlled ? '对手报双,按公开余牌可封住对子' : '对手报双,这手仍可能被压');
171
+ else if (!target && singleDanger && move.cards.length > 1) reasons.push('对手报单,领出多张避免其直接接走');
172
+ if (mustCoverTeammate) reasons.push('下家对手可能接走队友这手,需要考虑接管');
114
173
  if (bomb) reasons.push('使用炸弹会使倍数翻倍');
174
+ if (usesBombAsAttachment) reasons.push('四张同点牌用作带牌,失去独立炸弹');
115
175
  if (splitBomb) reasons.push('需要拆开四张同点牌');
116
176
  if (splitRocket) reasons.push('需要拆开王炸');
117
177
  if (splitPair) reasons.push('需要拆对子');
118
- if (!finished && !bomb && !splitBomb && !splitRocket && !splitPair) reasons.push(target ? '合法压牌,保留完整对子与炸弹' : '先走组合牌或散牌,保留完整对子与炸弹');
119
- return { score, suggestion: { action: { move: 'play' as const, cards: sortCards(move.cards) }, label: moveLabel(move), reason: reasons.join(';'), remaining: hand.length - move.cards.length } };
178
+ if (RANKS.some((rank) => counts[rank] === 4 && used[rank] === 0)) reasons.push('保留炸弹');
179
+ const family = `${move.type}:${['single', 'pair'].includes(move.type) ? `${move.rank >= RANKS.indexOf('A') ? 'high' : 'low'}:${controlled}` : ''}`;
180
+ return { score, family, suggestion: { action: { move: 'play' as const, cards: sortCards(move.cards) }, label: moveLabel(move), reason: reasons.join(';'), remaining: rest.length } };
120
181
  }).sort((a, b) => b.score - a.score || a.suggestion.action.cards.join(',').localeCompare(b.suggestion.action.cards.join(',')));
121
- const suggestions: DoudizhuSuggestion[] = rated.slice(0, target ? 2 : 3).map((entry) => entry.suggestion);
182
+ const selected: typeof rated = [];
183
+ for (const entry of rated) {
184
+ if (selected.some((other) => other.family === entry.family)) continue;
185
+ selected.push(entry);
186
+ if (selected.length === (target ? 2 : 3)) break;
187
+ }
188
+ const suggestions: DoudizhuSuggestion[] = selected.map((entry) => entry.suggestion);
122
189
  if (target) {
123
- const teammate = context.role === 'farmer' && context.lastPlayBy === 'farmer';
124
190
  const pass: DoudizhuSuggestion = {
125
191
  action: { move: 'pass' }, label: '不要', remaining: hand.length,
126
- reason: !plays.length ? '没有合法压牌,只能过牌' : teammate ? '队友当前领牌,可选择让牌;并非无法压牌' : '允许过牌,保留手牌;并非无法压牌',
192
+ reason: !plays.length ? '没有合法压牌,只能过牌' : mustCoverTeammate ? '可过,但下家对手可能接走队友的牌;并非无法压牌'
193
+ : teammate ? '队友当前领牌,可选择让牌;并非无法压牌' : '允许过牌,保留手牌组合;并非无法压牌',
127
194
  };
128
- const passFirst = !plays.length || (rated[0]?.score ?? 0) < 0 || (teammate && rated[0]?.score !== 10_000);
195
+ const passScore = -beforeGroups * 24 + 8 + (teammate && !mustCoverTeammate ? 100 : 0)
196
+ - (mustCoverTeammate || (!teammate && (singleDanger || pairDanger)) ? 300 : 0);
197
+ const passFirst = !plays.length || passScore >= rated[0].score;
129
198
  if (passFirst) suggestions.unshift(pass); else suggestions.push(pass);
130
199
  }
131
- return { played: countCards(played), otherRemaining: countCards(subtractCards(DECK, [...played, ...hand])), suggestions, canBeat: plays.length > 0 };
200
+ return { played: countCards(played), otherRemaining: unseen, suggestions, canBeat: plays.length > 0 };
132
201
  }
@@ -0,0 +1,46 @@
1
+ import { RANKS, type Card, type Move } from './doudizhu.ts';
2
+
3
+ /** 静态拆手:每组均为合法领出,不假定能连续拿到出牌权。 */
4
+ export function createHandPlanner(hand: readonly Card[], moves: readonly Move[]): (cards: readonly Card[]) => number {
5
+ const powers = RANKS.map((_, index) => 5 ** index);
6
+ const tally = (cards: readonly Card[]): number[] => RANKS.map((rank) => cards.filter((card) => card === rank).length);
7
+ const keyOf = (counts: readonly number[]): number => counts.reduce((sum, count, rank) => sum + count * powers[rank], 0);
8
+ const entries = moves.map((move) => {
9
+ const counts = tally(move.cards);
10
+ return { counts, key: keyOf(counts), size: move.cards.length };
11
+ }).sort((a, b) => b.size - a.size || a.key - b.key);
12
+ const singleMoves = new Set(entries.map((entry) => entry.key));
13
+ const containing = RANKS.map((_, rank) => entries.filter((entry) => entry.counts[rank] > 0));
14
+ const memo = new Map<number, number>([[0, 0]]);
15
+ const fits = (move: readonly number[], counts: readonly number[]): boolean => move.every((n, rank) => n <= counts[rank]);
16
+ // 所有候选共用缓存和确定性的搜索额度;大手牌达到额度后返回真实合法拆分的上界。
17
+ const budget = hand.length <= 12 ? 4096 : 1200;
18
+ let visited = 0;
19
+ const greedy = (counts: readonly number[]): number => {
20
+ const rest = [...counts];
21
+ let groups = 0;
22
+ for (const entry of entries) while (fits(entry.counts, rest)) {
23
+ for (let rank = 0; rank < rest.length; rank++) rest[rank] -= entry.counts[rank];
24
+ groups++;
25
+ }
26
+ return groups;
27
+ };
28
+ const solve = (counts: number[], key: number): number => {
29
+ const cached = memo.get(key);
30
+ if (cached !== undefined) return cached;
31
+ if (singleMoves.has(key)) { memo.set(key, 1); return 1; }
32
+ let best = greedy(counts);
33
+ if (best > 2 && visited++ < budget) {
34
+ const anchor = counts.findIndex((count) => count > 0);
35
+ for (const entry of containing[anchor]) {
36
+ if (!fits(entry.counts, counts)) continue;
37
+ const rest = counts.map((count, rank) => count - entry.counts[rank]);
38
+ best = Math.min(best, 1 + solve(rest, key - entry.key));
39
+ if (best === 2) break;
40
+ }
41
+ }
42
+ memo.set(key, best);
43
+ return best;
44
+ };
45
+ return (cards) => { const counts = tally(cards); return solve(counts, keyOf(counts)); };
46
+ }
@@ -57,6 +57,14 @@ const DEFAULT_BOT_DELAY_MS = 1500;
57
57
  const BOT_NAMES = ['陪练甲', '陪练乙'];
58
58
  const MAX_REDEALS = 5;
59
59
 
60
+ /** 主牌点数是从实际出牌派生的;旧存档可能把较小附件误存成主牌。 */
61
+ const restoreMove = (value: unknown): Move => {
62
+ const cards = (value as { cards?: unknown } | null)?.cards;
63
+ const parsed = Array.isArray(cards) ? parseMove(cards) : null;
64
+ if (!parsed) throw new Error('斗地主存档的出牌牌型不合法');
65
+ return parsed;
66
+ };
67
+
60
68
  export class DoudizhuTable implements TableEngine {
61
69
  readonly game = 'ddz';
62
70
  readonly label = '斗地主';
@@ -234,6 +242,7 @@ export class DoudizhuTable implements TableEngine {
234
242
 
235
243
  public(): unknown {
236
244
  const landlord = this.landlord();
245
+ const winner = this.status === 'ended' ? this.seats.find((seat) => seat.hand.length === 0) : undefined;
237
246
  return {
238
247
  game: this.game,
239
248
  status: this.status,
@@ -269,6 +278,8 @@ export class DoudizhuTable implements TableEngine {
269
278
  }
270
279
  : null,
271
280
  result: this.result || undefined,
281
+ // 终局事件可能已滚出回放窗口;公开结果由存档中的最终牌局重建。
282
+ ...(winner ? this.roundResult(winner) : {}),
272
283
  };
273
284
  }
274
285
 
@@ -423,7 +434,7 @@ export class DoudizhuTable implements TableEngine {
423
434
  if (typeof id !== 'string' || !row || typeof row !== 'object') throw new Error('斗地主存档的轮次出牌形状不对');
424
435
  this.roundPlays.set(id, {
425
436
  seat: String(row.seat ?? id),
426
- move: row.move as Move,
437
+ move: restoreMove(row.move),
427
438
  cards: Array.isArray(row.cards) ? row.cards as PhysCard[] : [],
428
439
  });
429
440
  }
@@ -435,7 +446,7 @@ export class DoudizhuTable implements TableEngine {
435
446
  this.lastPlay = last && typeof last === 'object'
436
447
  ? {
437
448
  seat: String(last.seat ?? ''),
438
- move: last.move as Move,
449
+ move: restoreMove(last.move),
439
450
  cards: Array.isArray(last.cards) ? last.cards as PhysCard[] : [],
440
451
  }
441
452
  : undefined;
@@ -630,7 +641,7 @@ export class DoudizhuTable implements TableEngine {
630
641
  return { events, views: this.turnViews() };
631
642
  }
632
643
 
633
- private finish(winner: Seat, events: TableEvent[]): void {
644
+ private roundResult(winner: Seat) {
634
645
  const landlord = this.landlord()!;
635
646
  const landlordWon = winner.role === 'landlord';
636
647
  const farmers = this.seats.filter((seat) => seat.role === 'farmer');
@@ -640,26 +651,34 @@ export class DoudizhuTable implements TableEngine {
640
651
  farmerPlays: farmers.reduce((sum, seat) => sum + seat.plays, 0),
641
652
  landlordPlays: landlord.plays,
642
653
  });
654
+ return {
655
+ landlord: landlord.id,
656
+ winners: (landlordWon ? [landlord] : farmers).map((seat) => seat.id),
657
+ multiplier: score.multiplier,
658
+ spring: score.spring,
659
+ antiSpring: score.antiSpring,
660
+ revealed: this.seats.map((seat) => ({
661
+ id: seat.id, name: seat.name, cards: [...seat.hand], handCards: seat.cards.map((card) => ({ ...card })),
662
+ })),
663
+ };
664
+ }
665
+
666
+ private finish(winner: Seat, events: TableEvent[]): void {
667
+ const landlord = this.landlord()!;
668
+ const result = this.roundResult(winner);
643
669
  this.status = 'ended';
644
670
  this.turnId = undefined;
645
671
  this.deadline = 0;
646
- const side = landlordWon ? '地主赢' : '农民赢';
647
- const extra = score.spring ? ',春天' : score.antiSpring ? ',反春' : '';
648
- this.result = `${side};地主 ${landlord.name},倍数 x${score.multiplier}${extra}。`;
672
+ const side = winner.role === 'landlord' ? '地主赢' : '农民赢';
673
+ const extra = result.spring ? ',春天' : result.antiSpring ? ',反春' : '';
674
+ this.result = `${side};地主 ${landlord.name},倍数 x${result.multiplier}${extra}。`;
649
675
  events.push({
650
676
  type: 'parlor.table.end',
651
677
  scope: { kind: 'room' },
652
678
  text: `斗地主结束:${this.result}手牌:${this.seats.map((seat) => `${seat.name} 剩 ${formatCards(seat.hand) || '无'}`).join(';')}。`,
653
679
  data: {
654
680
  game: this.game,
655
- landlord: landlord.id,
656
- winners: (landlordWon ? [landlord] : farmers).map((seat) => seat.id),
657
- multiplier: score.multiplier,
658
- spring: score.spring,
659
- antiSpring: score.antiSpring,
660
- revealed: this.seats.map((seat) => ({
661
- id: seat.id, name: seat.name, cards: [...seat.hand], handCards: [...seat.cards],
662
- })),
681
+ ...result,
663
682
  },
664
683
  });
665
684
  }
@@ -713,7 +732,13 @@ export class DoudizhuTable implements TableEngine {
713
732
  }
714
733
 
715
734
  private assistFor(seat: Seat): DoudizhuAssist {
716
- return buildAssist(seat.hand, this.playedCards(), this.lastPlay?.move ?? null, this.botContext(seat));
735
+ const next = this.seats[(this.seats.indexOf(seat) + 1) % SEAT_COUNT];
736
+ return buildAssist(seat.hand, this.playedCards(), this.lastPlay?.move ?? null, {
737
+ ...this.botContext(seat),
738
+ opponentCardsLeft: this.seats.filter((other) => other.role !== seat.role).map((other) => other.hand.length),
739
+ nextRole: next.role ?? undefined,
740
+ nextCardsLeft: next.hand.length,
741
+ });
717
742
  }
718
743
 
719
744
  /** 轮到自己时给网页一个可点的建议;不轮到时没有。 */