10 Commits
Author SHA1 Message Date
Diuse f2da9bce65 fixed # 重构梦三项目结构 2026-09-30 10:23:58 +08:00
Diuse 3fdaf6d218 fixed # 修补缺失资源,修正已知BUG 2026-09-30 00:33:30 +08:00
Diuse 98a55dd3d6 fixed # 更新资源文件
fixed # 修复部分手机适配问题
2026-09-29 18:15:38 +08:00
Diuse dd562ae627 fixed # 修复手机端地图滑动异常的问题
fixed # 重构更新框架,支持选择是否下载梦三模式
fixed # 补充部分意图的资源图片与逻辑
2026-09-29 17:44:21 +08:00
Diuse c9c09582c1 新增更新通道选择 2026-09-29 15:07:35 +08:00
Diuse a368dfae48 merge 2026-09-29 13:04:13 +08:00
Diuse 2e552cf17d 改动整体底层系统 2026-09-29 00:29:00 +08:00
Diuse ced1b28cc2 同步更新STS2 词缀 2026-09-28 21:49:47 +08:00
Diuse e3913f8969 merge 2026-09-28 20:59:56 +08:00
Diuse 8045e3c63f 整合 2026-09-28 20:58:29 +08:00
97 changed files with 7355 additions and 758 deletions
+16 -6
View File
@@ -92,10 +92,13 @@ jobs:
) as archive:
for name in manifest["files"]:
archive.write(root / name, folder + name)
archive.write(
root / "dist/manifest.json",
folder + "manifest.json"
)
for descriptor in manifest.get("modules", {}).values():
component = json.loads(
(root / descriptor["manifest"]).read_text(encoding="utf-8")
)
for name in component["files"]:
archive.write(root / name, folder + name)
archive.write(root / "dist/manifest.json", folder + "manifest.json")
'@ | python - $stage $package
if ($LASTEXITCODE -ne 0) { throw '打包失败' }
@@ -135,7 +138,14 @@ jobs:
-Body $body
$assetApi = "$api/$($release.id)/assets"
foreach ($file in @($manifestPath, $package)) {
$moduleManifests = @(
Get-ChildItem (Join-Path $stage 'dist/modules') `
-Filter '*.json' -ErrorAction SilentlyContinue
)
$releaseFiles = @($manifestPath)
$releaseFiles += $moduleManifests
$releaseFiles += $package
foreach ($file in $releaseFiles) {
curl.exe --fail --silent --show-error `
-H "Authorization: token $env:GITEA_TOKEN" `
-F "attachment=@$file" `
@@ -151,4 +161,4 @@ jobs:
-ContentType 'application/json' `
-Body '{"draft":false}' | Out-Null
Write-Host "发布完成:$tag"
Write-Host "发布完成:$tag"
+16 -4
View File
@@ -90,10 +90,19 @@ jobs:
Copy-Item -LiteralPath $manifestPath `
-Destination (Join-Path $env:GITHUB_WORKSPACE `
'dist/manifest.json') -Force
$moduleManifestDir = Join-Path $source 'dist/modules'
if (Test-Path $moduleManifestDir) {
New-Item -ItemType Directory -Force `
(Join-Path $env:GITHUB_WORKSPACE 'dist/modules') | Out-Null
Copy-Item -Path (Join-Path $moduleManifestDir '*.json') `
-Destination (Join-Path $env:GITHUB_WORKSPACE 'dist/modules') `
-Force
}
git config user.name 'github-actions[bot]'
git config user.email `
'41898282+github-actions[bot]@users.noreply.github.com'
git add dist/manifest.json
git add dist/modules
if ($LASTEXITCODE -ne 0) { throw '暂存清单失败' }
git commit -m "Prepare manifest for $tag"
if ($LASTEXITCODE -ne 0) { throw '提交清单失败' }
@@ -143,10 +152,13 @@ jobs:
) as archive:
for name in manifest["files"]:
archive.write(root / name, folder + name)
archive.write(
root / "dist/manifest.json",
folder + "manifest.json"
)
for descriptor in manifest.get("modules", {}).values():
component = json.loads(
(root / descriptor["manifest"]).read_text(encoding="utf-8")
)
for name in component["files"]:
archive.write(root / name, folder + name)
archive.write(root / "dist/manifest.json", folder + "manifest.json")
'@ | python - $stage $package
if ($LASTEXITCODE -ne 0) { throw '打包失败' }
+13 -1
View File
@@ -1,4 +1,16 @@
log.txt
findings.md
progress.md
task_plan.md
dist/manifest.json
tools/__pycache__/
tools/test_update.mjs
tools/test_update.mjs
tools/test_intent.mjs
/mengsan/.planning/
/mengsan/verification
/mengsan/assets/sts2/
/Slay the Spire 2
+25 -9
View File
@@ -49,12 +49,10 @@ shuYing.initFunction = () => {
};
shuYing.getOnlineVersionText = () => `最新版本:${lib.config.shuYing_online_version || "检测中..."}`;
shuYing.updateOnlineVersionMenu = (version) => {
if (!version) return;
shuYing.updateOnlineVersionMenu = (version, status = "检测中...") => {
if (version) game.saveConfig("shuYing_online_version", version);
game.saveConfig("shuYing_online_version", version);
const text = `最新版本:${version}`;
const text = `最新版本:${version || status}`;
if (lib.extensionMenu.extension_术樱包?.online_version) {
lib.extensionMenu.extension_术樱包.online_version.name = text;
}
@@ -113,8 +111,11 @@ shuYing.mergeCharacterPack = function (target, source, sourceName = "附加模
};
shuYing.getVersion = (callback) => {
const requestId = (shuYing.versionRequestId || 0) + 1;
shuYing.versionRequestId = requestId;
return updater.getOnlineVersion()
.then(version => {
if (requestId != shuYing.versionRequestId) return null;
shuYing.updateOnlineVersionMenu(version?.online_version);
if (typeof callback == "function") {
callback(version);
@@ -122,7 +123,9 @@ shuYing.getVersion = (callback) => {
return version;
})
.catch(error => {
if (requestId != shuYing.versionRequestId) return null;
console.error("术樱包获取在线版本失败:", error);
shuYing.updateOnlineVersionMenu(null, "获取失败");
return null;
});
}
@@ -247,10 +250,23 @@ shuYing.precontent = async () => {
shuYing.initCSS();
shuYing.initFunction();
shuYing.initConfig();
// const initMengsan = await shuYing.loadModule("./mengsan/mode.js", "梦三模式", true);
// if (typeof initMengsan == "function") {
// await initMengsan();
// }
const mengsanState = lib.config.shuYing_mengsan_installed_version;
let hasMengsan = !!mengsanState && mengsanState != "disabled";
if (!mengsanState && typeof game.checkFile != "function") {
hasMengsan = true;
}
else if (!mengsanState && typeof game.checkFile == "function") {
hasMengsan = await new Promise(resolve => {
game.checkFile("extension/术樱包/mengsan/register.js",
result => resolve(result == 1), () => resolve(false));
});
}
if (hasMengsan) {
const registerMengsan = await shuYing.loadModule(
"./mengsan/register.js", "梦三模式", true
);
if (typeof registerMengsan == "function") registerMengsan();
}
initShuYingMenu({ lib, game, ui, shuYing, updater });
shuYing.getVersion();
await shuYing.initCharacter();
+17
View File
@@ -0,0 +1,17 @@
# 梦三模式目录
`register.js` 是扩展加载入口,`mode.js` 负责组装模式、注册技能并连接各领域模块,`config.js` 提供模式配置。发布器和外部扩展应继续从 `register.js` 加载,避免依赖内部文件路径。
| 目录 | 职责 |
| --- | --- |
| `battle/` | 战斗会话、回合、结算、费用与通用战斗效果 |
| `monsters/` | 怪物阶级、牌堆默认值和各怪物意图选择 |
| `cards/` | 卡牌定义、词缀、生成和个人牌堆 |
| `progression/` | 征程状态、存档、剧情选择和奖励逻辑 |
| `content/` | 章节、遭遇、剧本、角色与内容注册表 |
| `ui/` | 地图、对话、意图、奖励、图鉴及样式 |
| `assets/intent/` | 意图图标 |
| `assets/portraits/` | 角色立绘 |
| `docs/` | 战斗和关卡配置说明 |
新增功能优先放入所属领域;界面代码放在 `ui/`,怪物行动逻辑放在 `monsters/`。跨领域引用使用相对路径,避免新增一个涵盖所有功能的扁平 `runtime/` 目录。模块资源文件随 `tools/generate_manifest.py` 自动收录,发布入口仍为 `mengsan/register.js`。
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

+180
View File
@@ -0,0 +1,180 @@
const copy = value => JSON.parse(JSON.stringify(value));
const camps = new Set(["ally", "enemy", "neutral"]);
export const campPresets = Object.freeze({ ally: { enabled: true }, enemy: { enabled: true }, neutral: { enabled: false } });
const events = new Set(["battleStart", "roundStart", "turnStart", "turnEnd", "state"]);
const checks = new Set(["hp", "hand", "alive", "linked", "turnedOver", "camp"]);
const numeric = value => Number.isInteger(value) && value >= 0 && value <= 99;
const assert = (condition, message) => { if (!condition) throw new Error("梦三关卡配置:" + message); };
export function validateBattlePlan(plan) {
assert(plan && Array.isArray(plan.units) && Array.isArray(plan.rules), "units/rules 必须为数组");
assert(plan.units.length > 0 && plan.units.length <= 7 && plan.rules.length <= 32, "初始单位或规则数量越界");
const ids = new Set(["player"]), ruleIds = new Set();
const unit = spec => {
assert(spec && typeof spec.id === "string" && /^[\w.-]+$/.test(spec.id) && !ids.has(spec.id), "单位 ID 无效或重复");
ids.add(spec.id);
assert(ids.size <= 8, "单场累计最多 8 个席位(含主角及后续援军)");
assert(typeof spec.character === "string" && spec.character.length > 0 && camps.has(spec.camp), "武将或阵营无效");
assert(spec.camp !== "neutral", "中立预设尚未启用");
assert(spec.tier == null || ["normal", "elite", "boss"].includes(spec.tier), "怪物阶级无效");
assert(spec.deck == null || (Array.isArray(spec.deck) && spec.deck.length > 0 && spec.deck.every(entry =>
typeof entry === "string" && Boolean(entry) || entry && typeof entry.name === "string" && Boolean(entry.name) &&
(entry.suit == null || ["spade", "heart", "club", "diamond"].includes(entry.suit)) &&
(entry.number == null || Number.isInteger(entry.number) && entry.number >= 1 && entry.number <= 13))), "怪物专属牌堆无效");
for (const key of ["hand", "hp", "maxHp"]) if (spec[key] != null) assert(numeric(spec[key]), key + " 越界");
if (spec.hp != null) assert(spec.hp > 0, "初始体力必须大于 0");
if (spec.maxHp != null) assert(spec.maxHp > 0 && (spec.hp == null || spec.hp <= spec.maxHp), "初始体力上限无效");
assert(spec.inheritSkills == null || typeof spec.inheritSkills === "boolean", "inheritSkills 必须为布尔值");
assert(spec.after == null || typeof spec.after === "string", "after 必须是单位 ID");
assert(spec.equipment == null || (Array.isArray(spec.equipment) && spec.equipment.length <= 5), "equipment 无效");
for (const card of spec.equipment || []) {
assert(card && typeof card.name === "string" && card.name.length > 0, "初始装备名称无效");
assert(["spade", "heart", "club", "diamond"].includes(card.suit), "初始装备花色无效");
assert(Number.isInteger(card.number) && card.number >= 1 && card.number <= 13, "初始装备点数无效");
}
assert(spec.skills == null || (Array.isArray(spec.skills) && spec.skills.every(s => typeof s === "string")), "skills 无效");
};
plan.units.forEach(unit);
for (const rule of plan.rules) {
assert(rule && typeof rule.id === "string" && !ruleIds.has(rule.id), "规则 ID 重复或无效"); ruleIds.add(rule.id);
assert(rule.when && events.has(rule.when.event || "state"), "触发时机无效");
assert(rule.blocksVictory == null || typeof rule.blocksVictory === "boolean", "blocksVictory 必须为布尔值");
assert(rule.when.round == null || (numeric(rule.when.round) && rule.when.round > 0), "轮数无效");
assert(rule.when.actorTurns == null || (rule.when.event === "turnEnd" && rule.when.actor && numeric(rule.when.actorTurns) && rule.when.actorTurns > 0), "actorTurns 仅用于指定角色的回合结束");
assert(rule.when.turn == null || (numeric(rule.when.turn) && rule.when.turn > 0), "回合数无效");
assert(Array.isArray(rule.effects) && rule.effects.length > 0 && rule.effects.length <= 16, "效果列表无效");
for (const effect of rule.effects) {
assert(["spawn", "draw", "recover", "maxHp", "skill", "camp", "dialogue", "discardEquipment"].includes(effect.type), "未知效果");
if (effect.type === "spawn") unit(effect.unit);
else if (effect.type === "dialogue") {
assert(Array.isArray(effect.lines) && effect.lines.every(line => line && ["character", "narrator", "sound", "choice"].includes(line.type) && typeof line.text === "string" && line.text.trim() && (line.type !== "character" || typeof line.character === "string") && (line.type !== "choice" || (/^story\.[\w.]+$/.test(line.flag || "") && Array.isArray(line.choices) && line.choices.length >= 1 && (line.defaultChoice == null || line.choices.some(choice => choice.id === line.defaultChoice))))), "dialogue 台词无效");
}
else {
assert(typeof effect.target === "string", "效果缺少目标 ID");
if (["draw", "recover", "maxHp"].includes(effect.type)) assert(numeric(effect.amount) && effect.amount > 0, "效果数值无效");
if (effect.type === "discardEquipment") assert(typeof effect.name === "string" && effect.name.length > 0, "弃置装备名称无效");
if (effect.type === "skill") assert(typeof effect.skill === "string" && effect.skill.length > 0, "技能 ID 无效");
if (effect.type === "camp") assert(["ally", "enemy"].includes(effect.camp) && effect.target !== "player", "阵营无效或试图改变主角阵营");
}
}
}
for (const rule of plan.rules) {
assert(rule.when.actor == null || ids.has(rule.when.actor), "行动角色 ID 无效");
assert(rule.when.all == null || (Array.isArray(rule.when.all) && rule.when.all.length <= 16), "条件列表无效");
for (const condition of rule.when.all || []) {
assert(ids.has(condition.unit) && checks.has(condition.field), "条件单位或字段无效");
if (["hp", "hand"].includes(condition.field)) assert(["eq", "gte", "lte"].includes(condition.op) && numeric(condition.value), "数值比较无效");
else if (condition.field === "camp") assert(camps.has(condition.value), "阵营条件无效");
else assert(typeof condition.value === "boolean", "状态条件必须为布尔值");
}
for (const effect of rule.effects) if (!["spawn", "dialogue"].includes(effect.type)) assert(ids.has(effect.target), "效果目标不存在");
}
for (const spec of [...plan.units, ...plan.rules.flatMap(r => r.effects.filter(e => e.type === "spawn").map(e => e.unit))]) {
assert(spec.after == null || (ids.has(spec.after) && spec.after !== spec.id), "after 席位目标无效");
}
return plan;
}
export function grantSupport(run, rewardId, spec) {
const supports = run.player.supports ||= [];
const battles = spec.battles ?? -1;
assert(battles === -1 || (Number.isInteger(battles) && battles > 0 && battles <= 99), "支援持续场数无效");
// One support per source; repeated permanent items do not clone the same helper.
const existing = supports.find(s => s.rewardId === rewardId);
if (existing) { existing.battles = existing.battles === -1 || battles === -1 ? -1 : Math.min(99, existing.battles + battles); return; }
const number = (run.supportSequence || 0) + 1;
run.supportSequence = number;
supports.push({ id: `support_${number}`, rewardId, category: spec.category || "item", unit: copy(spec.unit), battles });
}
export function buildBattlePlan(encounter, run) {
const plan = copy(encounter.battlePlan || {
units: [{ id: "enemy_1", character: encounter.enemy, camp: "enemy", tier: encounter.tier || "normal", hand: 4 }], rules: [],
});
plan.rules ||= [];
// Consumed only in the battle's run snapshot; the existing settlement commits it atomically.
for (const support of run.player.supports || []) {
if (support.battles === 0) continue;
assert(support.battles === -1 || (Number.isInteger(support.battles) && support.battles > 0), "支援持续场数无效");
plan.units.push({ ...copy(support.unit), id: support.id });
}
validateBattlePlan(plan);
return plan;
}
export function consumeSupports(run) {
run.player.supports = (run.player.supports || []).map(s => ({ ...s, battles: s.battles > 0 ? s.battles - 1 : s.battles })).filter(s => s.battles !== 0);
}
export function createBattleDirector(plan, adapters) {
validateBattlePlan(plan);
const units = new Map(), fired = new Set(), completedTurns = new Map(), seenPhases = new WeakSet();
let round = 0, turn = 0, actor = null, ready = false, running = false, disposed = false;
const compare = (actual, op, value) => op === "gte" ? actual >= value : op === "lte" ? actual <= value : actual === value;
function matches(when, event) {
if ((when.event || "state") !== event) return false;
if (when.round != null && round < when.round) return false;
if (when.turn != null && turn < when.turn) return false;
if (when.actorTurns != null && (completedTurns.get(actor) || 0) < when.actorTurns) return false;
if (when.actor != null && units.get(when.actor) !== actor) return false;
return (when.all || []).every(condition => {
const player = units.get(condition.unit);
if (!player) return false;
const state = adapters.state(player);
return compare(state[condition.field], condition.op || "eq", condition.value);
});
}
async function evaluate(event = "state") {
if (!ready || disposed || running) return;
running = true;
try {
// Every rule runs once per battle; marking before effects prevents recursive triggers.
for (let pass = 0; pass <= plan.rules.length; pass++) {
let changed = false;
for (const rule of plan.rules) {
if (disposed || !adapters.active()) return;
if (fired.has(rule.id) || !matches(rule.when, event)) continue;
fired.add(rule.id); changed = true;
for (const effect of rule.effects) {
if (disposed || !adapters.active()) return;
if (effect.type === "dialogue") await adapters.dialogue(effect.lines);
else if (effect.type === "spawn") {
const anchor = effect.unit.after == null ? null : units.get(effect.unit.after);
if (effect.unit.after != null && !anchor) throw new Error("支援席位目标尚未登场:" + effect.unit.after);
units.set(effect.unit.id, await adapters.spawn(effect.unit, anchor));
}
else {
const target = units.get(effect.target);
if (target && adapters.state(target).alive) await adapters.effect(target, effect);
}
}
adapters.log(rule.name || rule.id);
}
if (!changed) break;
}
} finally { running = false; }
}
return {
bind(id, player) { if (units.has(id)) throw new Error("Duplicate battle unit: " + id); units.set(id, player); },
async start() { ready = true; await evaluate("battleStart"); await evaluate("state"); },
async beforeTurn(player) {
turn++; actor = player;
if (player === units.get("player")) { round++; await evaluate("roundStart"); }
await evaluate("turnStart"); await evaluate("state");
},
async afterTurn(player, phase) {
if (!ready || disposed || !adapters.active()) return;
if (phase && seenPhases.has(phase)) return;
if (phase) seenPhases.add(phase);
actor = player;
completedTurns.set(player, (completedTurns.get(player) || 0) + 1);
await evaluate("turnEnd"); await evaluate("state");
},
evaluate,
get ready() { return ready; },
get busy() { return running; },
get pendingEnemies() { return plan.rules.some(rule => rule.blocksVictory && !fired.has(rule.id) && rule.effects.some(e => (e.type === "spawn" && e.unit.camp === "enemy") || (e.type === "camp" && e.camp === "enemy"))); },
get defeatedEnemies() { return [...units.values()].filter(p => { const s = adapters.state(p); return s.camp === "enemy" && !s.alive; }).length; },
dispose() { disposed = true; units.clear(); },
};
}
+103
View File
@@ -0,0 +1,103 @@
// Candidate external coordinator. Finish callbacks return a boolean, NEVER a drain promise.
const copy = value => JSON.parse(JSON.stringify(value));
export function createBattleFlow({settlement, chooseReward, showMap, showEnding, quiesce, releaseSkills = async () => {}, presentVictory = async () => {}}) {
let state = "map", active = null, work = null, job = null, error = null;
async function drive() {
try {
state = "draining";
await active.session.drain();
// Allow mode-start/parent frames and foreign pauses to unwind; never resume them.
await quiesce();
if (!job.pending) job.pending = await settlement.prepare(job.input);
if (job.pending.outcome === "victory" && !job.victoryPresented) {
await presentVictory(copy(job.pending));
job.victoryPresented = true;
}
if (job.pending.state !== "chosen") {
state = "choosing";
if (!job.hasChoice) {
job.choiceId = job.pending.outcome === "defeat" || !job.pending.choices.length ? null : await chooseReward(copy(job.pending.choices), { boss: job.pending.boss });
if (job.pending.outcome !== "defeat" && job.pending.choices.length && job.choiceId !== null && !job.pending.choices.some(c => c.id === job.choiceId)) throw new Error("Invalid reward selection");
job.hasChoice = true;
}
job.pending = await settlement.choose(job.input.run.runId, job.pending.id, job.choiceId);
}
if (!job.committed) {
state = "committing";
job.committed = await settlement.commit(job.input.run.runId, job.pending.id);
}
if (!job.skillsReleased) {
state = "releasingSkills";
await releaseSkills();
job.skillsReleased = true;
await quiesce();
}
state = "cleaning";
await active.session.dispose(); // Failed cleanup retry does NOT replay a committed reward.
await quiesce();
if (!job.delivered) {
state = "presenting";
if (job.committed.route === "map") job.nextNode = await showMap(copy(job.committed.run));
else await showEnding(job.committed.route, copy(job.committed.run));
job.delivered = true;
}
state = job.committed.route === "map" ? "map" : "ended";
return {...copy(job.committed), nextNode:copy(job.nextNode ?? null)};
} catch (cause) {
error = cause; state = "retryable"; throw cause;
}
}
function launch() {
error = null; state = "draining";
work = Promise.resolve().then(drive);
// The engine callback is fire-and-forget; keep failure observable without unhandled rejection.
work.catch(() => {});
}
return Object.freeze({
get state() { return state; },
get error() { return error; },
async enterBattle({session, run, node, encounter, start}) {
if (state !== "map") throw new Error("Map handoff not ready");
if (run.battleFlow?.pending) throw new Error("Resume pending settlement before battle");
const saved = settlement.readRun();
if (!saved || saved.runId !== run.runId || saved.revision !== run.revision) throw new Error("Stale battle input");
state = "starting";
try {
await quiesce();
active = {session, run, node:copy(node), encounter:copy(encounter)};job = null;work = null;
// start MUST schedule only; it must not await the battle root's completion.
state = "battle"; start();
} catch (cause) { state = "blocked"; error = cause; throw cause; }
},
requestFinish({session, hp, outcome = "victory", defeatedEnemies = 1}) {
if (state !== "battle" || session !== active.session) return false;
if (!["victory", "defeat"].includes(outcome)) throw new Error("Unknown outcome");
if (!Number.isInteger(defeatedEnemies) || defeatedEnemies < 0) throw new Error("Invalid defeated enemy count");
job = {input:{run:copy(active.run),node:copy(active.node),encounter:{...copy(active.encounter),defeatedEnemies},hp,outcome}};
state = "stopping";
active.session.requestStop();
launch();
return true; // No game.pause/resume: stop loop, let current body unwind, then open rewards.
},
resumePending({session}) {
if (state !== "map") throw new Error("Cannot resume during another operation");
const run = settlement.readRun(), item = run?.battleFlow?.pending;
if (!item) throw new Error("No durable pending settlement");
active = {session};
job = {input:{run}, pending:copy(item)};
state = "stopping"; session.requestStop(); launch(); return work;
},
retry() {
if (state !== "retryable") throw new Error("No failed settlement to retry");
launch(); return work;
},
wait() { if (!work) throw new Error("No settlement requested"); return work; },
});
}
// Run outside engine events. No busy poll, no global queue clearing, no pause ownership guessing.
export async function quiesceEngine({eventManager, pauseManager}, nextTask = () => new Promise(resolve => setTimeout(resolve, 0))) {
await nextTask();
await pauseManager.waitPause();
if (eventManager.eventStack.length || eventManager.tempEvent) throw new Error("Engine event stack is not idle");
}
+87
View File
@@ -0,0 +1,87 @@
// Track only the turn created by this battle's cooperative loop.
const battleTurns = new WeakMap();
const turnStages = new Set(["phase", "phaseZhunbei", "phaseJudge", "phaseDraw", "phaseUse", "phaseDiscard", "phaseJieshu"]);
export function stopBattleTurn(session, eventManager) {
const turn = battleTurns.get(session);
if (!turn) return;
const belongsToTurn = event => {
const seen = new Set();
while (event && !seen.has(event)) {
if (event === turn) return true;
seen.add(event);
event = event.parent;
}
return false;
};
// Finish phase controllers, not the card/damage/death events currently resolving.
// Those events must unwind before the session can safely dispose players.
for (const event of eventManager.eventStack.slice().reverse()) {
if (turnStages.has(event.name) && belongsToTurn(event)) event.finish();
}
turn.finish();
}
// Candidate derived from local engine phaseLoop; no global replacement.
export async function runPhaseLoop(event, player, session, { game, lib, _status, get, beforeTurn = async () => {} }) {
let num = 1;
let current = player;
while (session.active && !event.finished && current.getSeatNum() === 0) {
current.setSeatNum(num);
current = current.next;
num++;
}
while (session.active && !event.finished) {
if (game.players.includes(event.player)) {
await beforeTurn(event.player);
if (!session.active || event.finished) return;
lib.onphase.forEach((i) => i());
if (!session.active || event.finished) return;
const phase = event.player.phase();
battleTurns.set(session, phase);
try {
event.next.remove(phase);
let isRoundEnd = false;
if (lib.onround.every((i) => i(phase, event.player))) {
isRoundEnd = _status.roundSkipped;
if (_status.isRoundFilter) {
isRoundEnd = _status.isRoundFilter(phase, event.player);
} else if (_status.seatNumSettled) {
const seatNum = event.player.getSeatNum();
if (seatNum != 0) {
if (get.itemtype(_status.lastPhasedPlayer) != "player" || seatNum < _status.lastPhasedPlayer.getSeatNum()) {
isRoundEnd = true;
}
}
} else if (event.player == _status.roundStart) {
isRoundEnd = true;
}
if (isRoundEnd && _status.globalHistory.some((i) => i.isRound)) {
game.log();
await event.trigger("roundEnd");
}
}
if (!session.active || event.finished) { phase.finish(); return; }
event.next.push(phase);
await phase;
} finally {
if (battleTurns.get(session) === phase) battleTurns.delete(session);
}
}
if (!session.active || event.finished) return;
await event.trigger("phaseOver");
if (!session.active || event.finished) return;
const findNext = (current2) => {
const players = game.players.slice(0).concat(game.dead).sort((a, b) => parseInt(a.dataset.position) - parseInt(b.dataset.position));
const position = parseInt(current2.dataset.position);
for (const player2 of players) {
if (parseInt(player2.dataset.position) > position) {
return player2;
}
}
return players[0];
};
event.player = findNext(event.player);
if (!event.player) return;
}
}
+55
View File
@@ -0,0 +1,55 @@
// Exclusive battle resources. Never clear arbitrary global queues or arbitrary timers.
export function createBattleResources(session, {game, ui, _status}) {
const cards = new Set(), nodes = new Map(), fields = [];
const containers = () => [ui.arena, ui.control, ui.sidebar, ui.cardPile, ui.discardPile, ui.ordering, ui.special].filter(Boolean);
const children = () => new Map(containers().map(parent => [parent, new Set(parent.childNodes)]));
const before = children();
const uiKeys = ["me","handcards1Container","handcards2Container","handcards1","handcards2"];
const uiBefore = new Map(uiKeys.map(key => [key,Object.getOwnPropertyDescriptor(ui,key)]));
function field(object, key, value) {
const descriptor = Object.getOwnPropertyDescriptor(object, key);
object[key] = value;
fields.push({object,key,value,descriptor});
return value;
}
// Install before root.start so global history cannot retain the finished battle tree.
field(_status, "globalHistory", [{cardMove:[],custom:[],useCard:[],changeHp:[],everything:[]}]);
field(_status, "cardtag", Object.fromEntries(Object.keys(_status.cardtag || {}).map(key => [key,[]])));
const counters = {phaseNumber:game.phaseNumber, roundNumber:game.roundNumber};
game.phaseNumber = 0; game.roundNumber = 0;
session.ownResource({}, () => {
for (const card of cards) card.remove();
for (const [node,parent] of nodes) if (node.parentNode === parent) node.remove();
for (const {object,key,value,descriptor} of fields.reverse()) {
if (object[key] !== value) continue; // A replacement owned by another subsystem survives.
if (descriptor) Object.defineProperty(object,key,descriptor); else delete object[key];
}
game.phaseNumber = counters.phaseNumber; game.roundNumber = counters.roundNumber;
});
return Object.freeze({
field,
card(card) { cards.add(card); return card; },
capturePreparedArena() {
for (const key of uiKeys) {
const descriptor = uiBefore.get(key);
if (ui[key] !== descriptor?.value) fields.push({object:ui,key,value:ui[key],descriptor});
}
// Call synchronously after prepareArena, with onfree already drained.
for (const parent of containers()) {
const prior = before.get(parent) || new Set();
for (const node of parent.childNodes) if (!prior.has(node)) {
if ([ui.cardPile,ui.discardPile,ui.ordering,ui.special].includes(parent)) cards.add(node);
else nodes.set(node,parent);
}
}
},
bindPlayers(players) {
const owned = new Set(players);
session.ownResource({}, () => {
for (const key of ["currentPhase","lastPhasedPlayer","roundStart"]) {
if (owned.has(_status[key])) delete _status[key];
}
});
},
});
}
+106
View File
@@ -0,0 +1,106 @@
// Candidate only. No engine globals, event prototype patches, or save writes.
const owners = new WeakMap();
export function createBattleSession(id) {
if (typeof id !== "string" || !id.trim()) throw new TypeError("Session ID required");
const token = Object.freeze({ id });
let state = "running", disposePromise = null;
const pending = new Set(), events = new Set(), resources = new Map(), errors = [];
const waiters = new Set();
const notify = () => { for (const wake of waiters) wake(); waiters.clear(); };
const ensureRunning = () => { if (state !== "running") throw new Error("Session is stopping"); };
const claim = object => {
if (!object || (typeof object !== "object" && typeof object !== "function")) throw new TypeError("Object required");
const owner = owners.get(object);
if (owner && owner !== token) throw new Error("Foreign session resource");
owners.set(object, token);
};
// Observe a native completion promise; never assimilate GameEvent.then(), which can start queues.
const observe = promise => {
if (!(promise instanceof Promise)) throw new TypeError("Native completion Promise required");
pending.add(promise);
promise.then(() => { pending.delete(promise); notify(); }, error => {
errors.push(error); pending.delete(promise); notify();
});
return promise;
};
const api = {
id,
get state() { return state; },
get active() { return state === "running"; },
get pendingCount() { return pending.size; },
guard(callback) {
if (typeof callback !== "function") throw new TypeError("Callback required");
return (...args) => state === "running" ? callback(...args) : undefined;
},
runTask(factory) {
ensureRunning();
if (typeof factory !== "function") throw new TypeError("Task factory required");
// Reserve before invoking user code so a stop request inside it cannot race drain().
return observe(Promise.resolve().then(() => state === "running" ? factory(api) : undefined));
},
ownEvent(event, completion) {
ensureRunning();
if (typeof event?.finish !== "function" || !(completion instanceof Promise)) throw new TypeError("Event and native completion required");
claim(event);
if (events.has(event)) throw new Error("Event already registered");
events.add(event); observe(completion);
return event;
},
ownResource(resource, release) {
ensureRunning();
if (typeof release !== "function") throw new TypeError("Release function required");
claim(resource);
if (resources.has(resource)) throw new Error("Resource already registered");
resources.set(resource, release);
return resource;
},
requestStop() {
if (state !== "running") return false;
state = "stopping";
// Only explicitly registered events. Do not erase global next/after or guess ownership.
for (const event of events) {
try { event.finish(); } catch (error) { errors.push(error); }
}
notify();
return true;
},
async drain() {
if (state === "running") throw new Error("requestStop required before drain");
// Must be awaited by an external coordinator, not from a task tracked by this session.
while (pending.size) await new Promise(resolve => waiters.add(resolve));
if (errors.length) throw new AggregateError(errors, "Battle tasks failed; cleanup blocked");
if (state === "stopping") state = "drained";
},
dispose() {
if (state === "disposed") return Promise.resolve();
if (disposePromise) return disposePromise;
if (state !== "drained") return Promise.reject(new Error("Drain must complete before disposal"));
state = "disposing";
disposePromise = (async () => {
// Reverse acquisition order; stop at first failure to preserve dependent resources.
for (const [resource, release] of [...resources].reverse()) {
await release(resource);
resources.delete(resource); owners.delete(resource);
}
for (const event of events) owners.delete(event);
events.clear(); state = "disposed";
})().catch(error => { state = "drained"; throw error; }).finally(() => { disposePromise = null; });
return disposePromise;
},
};
return Object.freeze(api);
}
// A reused ID must never cause old-session cleanup to delete the new player's entry.
export function ownPlayerIndex(session, player, playerMap) {
const id = player.playerid;
if (!id || playerMap[id] !== player) throw new Error("Player must be registered first");
return session.ownResource(player, () => { if (playerMap[id] === player) delete playerMap[id]; });
}
// Engine pause booleans are not ownership tokens. Accept a lease from a coordinator instead.
export function ownPauseLease(session, lease) {
if (typeof lease?.release !== "function") throw new TypeError("Pause lease required");
return session.ownResource(lease, () => lease.release());
}
+104
View File
@@ -0,0 +1,104 @@
// Candidate settlement adapter. Dependencies are the current mode/state reward functions.
const copy = value => JSON.parse(JSON.stringify(value));
const idFor = (run, node) => JSON.stringify([run.runId, run.actIndex, node.id]);
export function createBattleSettlement({store, config, getRandomRewardChoices, applyReward, completeNode, enterNextAct, now = Date.now}) {
const readRun = () => store.read()[config.saveKey];
function current(storage, runId) {
const run = storage[config.saveKey];
if (!run || run.runId !== runId) throw new Error("Stale run: settlement refused");
run.battleFlow ||= { receipts: [], pending: null };
return run;
}
function pending(storage, runId, id) {
const run = current(storage, runId), item = run.battleFlow.pending;
if (!item || item.id !== id) throw new Error("Settlement checkpoint mismatch");
return {run, item};
}
return Object.freeze({
readRun,
// Persist fixed candidates before opening choice UI. No mutation of the live run.
async prepare({run: snapshot, node, encounter, hp, outcome = "victory"}) {
if (!["victory", "defeat"].includes(outcome)) throw new Error("Unknown battle outcome");
if (outcome === "victory" && (!Number.isFinite(hp) || (!encounter.skipRandomReward && (!Number.isSafeInteger(encounter.gold) || encounter.gold < 0)))) throw new Error("Invalid battle result");
const id = idFor(snapshot, node);
return store.update(storage => {
const run = current(storage, snapshot.runId);
if (run.battleFlow.receipts.includes(id)) throw new Error("Battle already settled");
if (run.battleFlow.pending) {
if (run.battleFlow.pending.id !== id) throw new Error("Another settlement is pending");
return run.battleFlow.pending;
}
if (run.actIndex !== snapshot.actIndex || run.revision !== snapshot.revision ||
run.map?.nodes.find(n => n.id === node.id)?.completed !== false) {
throw new Error("Stale node or revision");
}
// Battle may have changed RNG/card state since the last checkpoint.
const base = copy(snapshot); delete base.battleFlow;
if (outcome === "victory") {
base.player.hp = Math.max(1, Math.min(hp, base.player.maxHp ?? hp));
base.statistics.defeatedEnemies += encounter.defeatedEnemies ?? 1;
}
const rewards = outcome === "victory" && !encounter.skipRandomReward ? getRandomRewardChoices(base, encounter.rewardPool).filter(c => c.name) : [];
if (outcome === "victory" && !encounter.skipRandomReward && !rewards.length) throw new Error("Empty battle reward pool");
// Persist the configured amount as a candidate, never as automatic victory income.
const choices = outcome === "victory" && !encounter.skipRandomReward
? [{id:"mengsan.reward.gold.shuying", kind:"gold", name:"金币", amount:encounter.gold}, ...rewards] : [];
run.battleFlow.pending = {id, state:"awaitingChoice", nodeId:node.id, base, choices:copy(choices), fixedRewards:copy(encounter.fixedRewards || []), victoryDialogue:copy(encounter.victoryDialogue || []), boss:!!encounter.boss, outcome};
return run.battleFlow.pending;
});
},
async choose(runId, id, choiceId) {
return store.update(storage => {
const {item} = pending(storage, runId, id);
if (item.state === "chosen") {
if (item.choiceId !== choiceId) throw new Error("Choice already locked");
return item;
}
const result = copy(item.base);
let route = "defeat";
if (item.outcome === "victory") {
const choice = item.choices.find(c => c.id === choiceId);
if (item.choices.length && choiceId !== null) {
if (!choice) throw new Error("Reward is not a fixed candidate");
if (choice.kind === "gold") {
if (!Number.isSafeInteger(choice.amount) || choice.amount < 0) throw new Error("Invalid pending gold reward");
result.player.gold += choice.amount;
result.statistics.goldEarned += choice.amount;
} else applyReward(result, choice.effectId || choice.id);
} else if (choiceId !== null) throw new Error("Unexpected reward selection");
for (const rewardId of item.fixedRewards || []) applyReward(result, rewardId);
if (!completeNode(result, item.nodeId)) throw new Error("Node completion failed");
route = item.boss && !enterNextAct(result) ? "victory" : "map";
} else result.status = "failed";
// Save the exact result (including random card ID/target) before final commit.
item.state = "chosen"; item.choiceId = choiceId; item.result = result;
item.route = route; item.completedAt = now();
return item;
});
},
async commit(runId, id) {
return store.update(storage => {
const saved = storage[config.saveKey];
const prior = storage[config.profileKey]?.completedRuns?.find(r => r.runId === runId && r.settlementId === id);
if (!saved && prior) return {route:prior.outcome, run:null, duplicate:true};
if (saved?.runId === runId && saved.battleFlow?.receipts?.includes(id)) return {route:"map", run:saved, duplicate:true};
const {run, item} = pending(storage, runId, id);
if (item.state !== "chosen") throw new Error("Durable chosen result required");
const result = copy(item.result);
result.battleFlow = {receipts:[...run.battleFlow.receipts, id], pending:null};
if (item.route === "map") storage[config.saveKey] = result;
else {
const profile = storage[config.profileKey] ||= {wins:0, completedRuns:[]};
profile.completedRuns ||= [];
if (!profile.completedRuns.some(r => r.runId === runId)) {
if (item.route === "victory") profile.wins = (profile.wins || 0) + 1;
profile.completedRuns.push({runId, settlementId:id, outcome:item.route, character:result.player.character,
completedNodes:result.statistics.completedNodes, goldEarned:result.statistics.goldEarned, completedAt:item.completedAt});
}
delete storage[config.saveKey]; // Same transaction as profile; never a second clear write.
}
return {route:item.route, run:result, duplicate:false};
});
},
});
}
+33
View File
@@ -0,0 +1,33 @@
// 梦三独有的出牌经济,不修改 noname 的全局牌定义。
import { _status } from "../../../../noname.js";
export const PLAYER_ENERGY = 3;
export const PLAYER_HAND_LIMIT = 3;
export const SHA_DAMAGE = 4;
const COSTS = Object.freeze({ sha: 1, tao: 1, jiu: 1, shan: 0, wuxie: 0,
juedou: 2, nanman: 2, wanjian: 2, taoyuan: 2 });
export const cardCost = card => COSTS[card?.name] ?? 1;
export const isActiveCardUse = (event, player) => {
if (!event || !player) return false;
const seen = new Set();
let inPhaseUse = false;
for (let current = event; current && !seen.has(current); current = current.parent) {
seen.add(current);
if (current.name === "dying" || current.name === "chooseToRespond") return false;
if (current.name === "chooseToUse" && (current.respondTo || String(current.type || "").startsWith("respond"))) return false;
if (current.name === "phaseUse" && current.player === player) inPhaseUse = true;
}
// 某些扩展创建的主动 useCard 事件不保留 phaseUse 父链。
return inPhaseUse || (event.name === "useCard" && event.player === player &&
_status.currentPhase === player);
};
export const canPayCard = (player, card) => (player?.storage?.mengsanEnergy_shuying ?? Infinity) >= cardCost(card);
export const payCard = (player, card) => {
if (!canPayCard(player, card)) return false;
player.storage.mengsanEnergy_shuying -= cardCost(card);
return true;
};
+38
View File
@@ -0,0 +1,38 @@
import {
attackHitCount,
outgoingAttackDamage,
} from "./intent-damage.js";
const pendingDeathBlows = new WeakSet();
export function isDeathBlowIntent(intent) {
return intent?.intentType === "death_blow";
}
export function hasPendingDeathBlow(source) {
return pendingDeathBlows.has(source);
}
export async function beginDeathBlow(source, target, intent) {
if (!isDeathBlowIntent(intent)) {
throw new TypeError("濒死一击需要 death_blow 意图类型");
}
if (attackHitCount(intent) !== 1) {
throw new RangeError("濒死一击只能造成一次伤害");
}
const damage = outgoingAttackDamage(intent, source);
if (!source?.isAlive() || !target?.isAlive()) return false;
const hit = target.damage(damage, source);
hit.mengsanAttack_shuying = true;
await hit;
if (source.isAlive()) pendingDeathBlows.add(source);
return true;
}
export async function finishDeathBlow(source) {
if (!hasPendingDeathBlow(source)) return false;
pendingDeathBlows.delete(source);
if (source.isAlive()) await source.die();
return true;
}
+83
View File
@@ -0,0 +1,83 @@
// Candidate only: attach to fresh, session-owned roots BEFORE scheduling them.
const attached = new WeakSet();
export function observeFreshEvent(session, event) {
if (!event || typeof event.start !== "function" || !event.manager?.eventStack ||
event.finished || event.manager.eventStack.includes(event) ||
event.parent?.childEvents?.includes(event) || attached.has(event)) {
throw new Error("Fresh, unobserved engine event required");
}
const descriptor = Object.getOwnPropertyDescriptor(event, "start");
if (descriptor && !descriptor.configurable) throw new Error("Event start is not configurable");
const original = event.start;
let resolve, reject;
const completion = new Promise((yes, no) => { resolve = yes; reject = no; });
session.ownEvent(event, completion);
let observed = false;
function start(...args) {
let result;
try { result = Reflect.apply(original, this, args); }
catch (error) { reject(error); throw error; }
if (!observed) {
observed = true;
if (!(result instanceof Promise)) {
reject(new TypeError("Native engine start promise required"));
} else {
result.then(() => {
if (event.manager.eventStack.includes(event) || event.manager.tempEvent === event) {
reject(new Error("Event still active after start completion"));
} else resolve();
}, reject);
}
}
return result; // Never assimilate event.then(), never proactively start a queue.
}
Object.defineProperty(event, "start", { configurable: true, writable: true, value: start });
attached.add(event);
session.ownResource({}, () => {
if (event.start === start) {
if (descriptor) Object.defineProperty(event, "start", descriptor);
else delete event.start;
}
attached.delete(event);
});
return completion;
}
// Independent delay entry: releasing it never calls global resume/pause2/over.resolve.
export function acquirePauseLease(session, pauseManager) {
if (!session.active || typeof pauseManager?.setDelay !== "function") throw new Error("Active session and pause manager required");
let unlock;
const gate = new Promise(resolve => { unlock = resolve; });
const settled = pauseManager.setDelay(gate);
let released = false;
const lease = Object.freeze({
release() { if (!released) { released = true; unlock(); } return settled; },
get released() { return released; },
});
session.ownResource(lease, () => lease.release());
return lease;
}
// Call outside tracked event/task bodies. Own pauses must be lifted before drain.
export async function stopAndDrain(session, leases = []) {
session.requestStop();
await Promise.all(leases.map(lease => lease.release()));
await session.drain();
}
// Only remove this exact node from the parent recorded at acquisition.
export function ownNode(session, node) {
const parent = node.parentNode;
if (!parent) throw new Error("Attached node required");
return session.ownResource(node, () => {
if (node.parentNode === parent) parent.removeChild(node);
});
}
export function ownListener(session, target, type, listener, options) {
const guarded = session.guard(listener);
const capture = typeof options === "boolean" ? options : !!options?.capture;
const token = {};
session.ownResource(token, () => target.removeEventListener(type, guarded, capture));
target.addEventListener(type, guarded, options);
return guarded;
}
+28
View File
@@ -0,0 +1,28 @@
export function attackHitCount(intent) {
const hits = intent.hits ?? 1;
if (!Number.isInteger(hits) || hits < 1) {
throw new RangeError("攻击段数必须是正整数");
}
return hits;
}
export function outgoingAttackDamage(intent, source) {
if (!Number.isInteger(intent.damage) || intent.damage < 0) {
throw new RangeError("预测伤害必须是非负整数");
}
const storedStrength = source?.storage?.mengsanStrength_shuying;
const strength = Number.isInteger(storedStrength) ? storedStrength : 0;
let damage = Math.max(0, intent.damage + strength);
if (source?.storage?.mengsanWeak_shuying > 0) {
damage = Math.floor(damage * 0.75);
}
return damage;
}
export function previewAttackDamage(intent, source, target) {
let damage = outgoingAttackDamage(intent, source);
if (target?.storage?.mengsanVulnerable_shuying > 0) {
damage = Math.ceil(damage * 1.5);
}
return damage;
}
+147
View File
@@ -0,0 +1,147 @@
// Candidate-only engine-derived release. Never replaces Player.prototype or lib.skill.
// Restricted: additional/fixed/superCharlotte skills require a separate audited adapter.
export async function removeBattleSkill(player, skill, {lib,game,get,_status}, wholePlayer = false) {
const names = Array.isArray(skill) ? skill.slice() : [skill];
for (const name of names) {
if (lib.skill[name]?.fixed || lib.skill[name]?.superCharlotte) throw new Error("Unsupported protected skill: " + name);
}
if (!wholePlayer && Object.values(player.additionalSkills || {}).some(list => list?.length)) throw new Error("Additional skill release adapter required");
const remove = async function removeSkill(skill) {
if (!skill) {
return;
}
_status.event.clearStepCache();
if (Array.isArray(skill)) {
for (var i = 0; i < skill.length; i++) {
await removeSkill.call(this, skill[i]);
}
} else {
if (skill === "counttrigger") {
this.stat[this.stat.length - 1].triggerSkill = {};
return;
} else {
var info = lib.skill[skill];
if (info?.fixed && arguments[1] !== true) {
return skill;
}
this.unmarkSkill(skill);
game.broadcastAll(
function(player, skill2) {
player.skills.remove(skill2);
player.hiddenSkills.remove(skill2);
player.invisibleSkills.remove(skill2);
delete player.tempSkills[skill2];
for (var i2 in player.additionalSkills) {
player.additionalSkills[i2].remove(skill2);
}
},
this,
skill
);
this.checkConflict(skill);
if (info) {
if (info.onremove) {
if (typeof info.onremove == "function") {
await info.onremove(this, skill);
} else if (typeof info.onremove == "string") {
if (info.onremove == "storage") {
delete this.storage[skill];
} else {
var cards = this.storage[skill];
if (get.itemtype(cards) == "card") {
cards = [cards];
}
if (get.itemtype(cards) == "cards") {
if (this.onremove == "discard") {
this.$throw(cards);
}
if (this.onremove == "discard" || this.onremove == "lose") {
game.cardsDiscard(cards);
delete this.storage[skill];
}
}
}
} else if (Array.isArray(info.onremove)) {
for (var i = 0; i < info.onremove.length; i++) {
delete this.storage[info.onremove[i]];
}
} else if (info.onremove === true) {
delete this.storage[skill];
}
}
this.removeSkillTrigger(skill);
if (!wholePlayer && !info.keepSkill) {
this.removeAdditionalSkills(skill);
}
}
this.enableSkill(skill + "_awake");
game.callHook("removeSkillCheck", [skill, this]);
}
}
return skill;
};
return remove.call(player, skill);
}
// Must be called after gameplay root drained, outside all engine event bodies.
export async function runSkillTeardown(releases, {lib,_status}) {
if (_status.eventManager.eventStack.length || _status.eventManager.tempEvent) throw new Error("Gameplay must drain before skill release");
if (!Array.isArray(releases) || releases.some(fn => typeof fn !== "function")) throw new TypeError("Explicit release callbacks required");
const previous = _status.eventManager.rootEvent;
const root = new lib.element.GameEvent("mengsanSkillTeardown", false, _status.eventManager);
let releaseError;
root.setContent(async () => {
try {
for (const release of releases) {
await release();
await root.waitNext();
}
} catch (error) {
releaseError = error;
// Let the engine drain any queued work and pop this root normally.
}
});
// Natural start completion includes next/after and native stack pop. Failure stays fail-closed.
await root.start();
if (_status.eventManager.eventStack.includes(root)) throw new Error("Teardown event still active");
if (_status.eventManager.rootEvent === root) _status.eventManager.rootEvent = previous;
if (releaseError) throw releaseError;
}
// Whole-player disposal differs from removing one source during gameplay: every source is ending.
// Each callback runs at most once; failed/partially executed teardown is NOT replayed blindly.
export function createPlayerTeardown(players, env) {
const captured = players.slice();
let operation;
const names = player => [...new Set([
...(player.skills || []), ...(player.hiddenSkills || []), ...(player.invisibleSkills || []),
...Object.keys(player.tempSkills || {}),
...Object.values(player.additionalSkills || {}).flatMap(list => typeof list === "string" ? [list] : list || []),
])];
return () => {
if (operation) return operation;
operation = (async () => {
// Preflight ALL players before modifying any skill.
for (const player of captured) for (const name of names(player)) {
if (env.lib.skill[name]?.fixed || env.lib.skill[name]?.superCharlotte) throw new Error("Protected skill requires adapter: " + name);
if (Object.values(player.additionalSkills || {}).some(value => !Array.isArray(value))) throw new Error("Unsupported additional skill source shape");
}
await runSkillTeardown(captured.map(player => async () => {
const released = new Set();
while (names(player).length) {
if (released.size >= 128) throw new Error("Skill teardown exceeded bounded expansion");
const name = names(player)[0];
if (released.has(name)) throw new Error("Released skill was re-added: " + name);
await removeBattleSkill(player, name, env, true);
released.add(name);
// Children can add skills. Drain them before taking the next inventory.
await env._status.event.waitNext();
}
for (const [key,list] of Object.entries(player.additionalSkills || {})) {
if (Array.isArray(list) && !list.length) delete player.additionalSkills[key];
}
}), env);
})();
return operation;
};
}
+45
View File
@@ -0,0 +1,45 @@
const stunned = new WeakMap();
export const STUN_INTENT = Object.freeze({ intentType: "stun" });
export function isStunIntent(intent) {
return intent?.intentType === "stun";
}
export function isStunned(player) {
return stunned.has(player);
}
export function applyStun(player, intent, options = {}) {
if (stunned.has(player)) return false;
const { resume = "advance", recover } = options;
if (resume !== "advance" && resume !== "retry") {
throw new RangeError("击晕恢复方式无效");
}
if (typeof recover !== "function") {
throw new TypeError("击晕需要恢复回调");
}
if (!player?.isAlive()) return false;
stunned.set(player, { intent, resume, recover, skipped: false });
return true;
}
export function skipStunnedAction(player, phaseUse) {
const state = stunned.get(player);
if (!state || state.skipped) return false;
phaseUse.cancel();
state.skipped = true;
return true;
}
export async function finishStunnedTurn(player) {
const state = stunned.get(player);
if (!state?.skipped) return false;
stunned.delete(player);
if (player.isAlive()) await state.recover(state.resume, state.intent);
return true;
}
export function clearStun(player) {
return stunned.delete(player);
}
+10
View File
@@ -0,0 +1,10 @@
// Shared mode-owned affix registry; adding a new entry also exposes it in GM.
export const AFFIX_INFO = Object.freeze({
void: Object.freeze({ name: "虚无", description: "弃牌阶段开始时移除此牌,退出此次战斗;即使同时具有保留也会移除。" }),
retain: Object.freeze({ name: "保留", description: "弃牌阶段开始时,此牌不计入手牌上限;若同时具有虚无,仍会被移除。" }),
unplayable: Object.freeze({ name: "不能被打出", description: "此牌不能使用或打出,但可以被弃置。" }),
ingenious: Object.freeze({ name: "奇巧", description: "不因弃牌阶段进入弃牌堆时,若可以使用,则使用此牌。" }),
eternal: Object.freeze({ name: "永恒", description: "此牌不能从你的牌组移除或变化。" }),
innate: Object.freeze({ name: "固有", description: "战斗开始时移至手牌;若已在手牌中则不移动。" }),
exhaust: Object.freeze({ name: "消耗", description: "使用或打出后移出此次战斗,并可在消耗牌堆查看;消耗牌堆不参与洗牌。" }),
});
+46
View File
@@ -0,0 +1,46 @@
import { cardDefinitions, canAcquireCard } from "./card-definitions.js";
const suits = ["spade", "heart", "club", "diamond"];
// 仅创建可序列化的牌组数据;战斗中的实体牌仍由 game.createCard 创建。
export function createCardData(spec, { character, enemy = false, registry = cardDefinitions } = {}) {
if (!spec || typeof spec !== "object" || !Object.hasOwn(registry, spec.name)) {
throw new Error(`梦三牌未注册:${spec?.name}`);
}
if (!enemy && !canAcquireCard(character, spec.name, registry)) {
throw new Error(`武将 ${character || "未知"} 无法获得牌:${spec.name}`);
}
if (typeof spec.id !== "string" || !spec.id || !suits.includes(spec.suit) ||
!Number.isInteger(spec.number) || spec.number < 1 || spec.number > 13 ||
(spec.nature != null && typeof spec.nature !== "string") ||
!Number.isInteger(spec.upgrade ?? 0) || (spec.upgrade ?? 0) < 0 ||
!Array.isArray(spec.affixes ?? []) || !(spec.affixes ?? []).every(value => typeof value === "string")) {
throw new Error(`梦三牌数据无效:${spec.name}`);
}
return {
id: spec.id, suit: spec.suit, number: spec.number, name: spec.name,
nature: spec.nature ?? null, affixes: (spec.affixes ?? []).slice(), upgrade: spec.upgrade ?? 0,
};
}
export function createRandomCardData(run, name, { random, now = Date.now, upgrade = 0, affixes = [] } = {}) {
if (!run?.player || !Array.isArray(run.player.deck) || typeof random !== "function") throw new Error("梦三随机牌参数无效");
// 先检查资格,再消耗随机数;失败的获得操作不改变后续奖励序列。
if (!canAcquireCard(run.player.character, name)) throw new Error(`武将 ${run.player.character} 无法获得牌:${name}`);
const stamp = now();
let id;
do { id = `mengsan_card_${stamp}_${Math.floor(random() * 1e6)}`; }
while (run.player.deck.some(card => card.id === id));
return createCardData({
id, suit: suits[Math.floor(random() * suits.length)], number: 1 + Math.floor(random() * 13),
name, nature: null, upgrade, affixes,
}, { character: run.player.character });
}
export function addCardToDeck(run, spec) {
const card = createCardData(spec, { character: run?.player?.character });
if (!Array.isArray(run?.player?.deck)) throw new Error("梦三牌组无效");
if (run.player.deck.some(existing => existing.id === card.id)) throw new Error(`梦三牌 ID 重复:${card.id}`);
run.player.deck.push(card);
return card;
}
+35
View File
@@ -0,0 +1,35 @@
// 梦三永久牌组的可获得牌注册表。这里登记牌名与归属,不复制引擎中的效果定义。
// 新增武将专属牌时填写 owner 为该武将 ID;通用牌填写 owner: null。
const definitions = [
{ name: "sha", category: "damage", owner: null },
{ name: "shan", category: "utility", owner: null },
{ name: "tao", category: "recovery", owner: null },
{ name: "jiu", category: "recovery", owner: null },
{ name: "guohe", category: "utility", owner: null },
{ name: "wuzhong", category: "utility", owner: null },
{ name: "juedou", category: "damage", owner: null },
{ name: "bagua", category: "utility", owner: null },
// 当前仅刘备专属首关的固定奖励会永久获得【的卢】。
{ name: "dilu", category: "utility", owner: "mengsan_liubei_shuying" },
];
export function createCardRegistry(entries) {
const registry = Object.create(null);
for (const entry of entries) {
if (!entry || typeof entry.name !== "string" || !/^[a-z][a-z0-9_]*$/.test(entry.name) ||
!["damage", "recovery", "utility"].includes(entry.category) ||
!(entry.owner === null || typeof entry.owner === "string" && entry.owner.length > 0) ||
Object.hasOwn(registry, entry.name)) {
throw new Error(`梦三牌定义无效或重复:${entry?.name}`);
}
registry[entry.name] = Object.freeze({ name: entry.name, category: entry.category, owner: entry.owner });
}
return Object.freeze(registry);
}
export const cardDefinitions = createCardRegistry(definitions);
export function canAcquireCard(character, name, registry = cardDefinitions) {
const definition = Object.hasOwn(registry, name) ? registry[name] : null;
return !!definition && (definition.owner === null || definition.owner === character);
}
+81
View File
@@ -0,0 +1,81 @@
// 梦三的模式牌定义:复制标准/军争的实体牌定义,不改动原牌包。
// 保留原牌名,以兼容原有牌的响应、装备技能及转化牌引用。
import standard from "../../../../card/standard.js";
import extra from "../../../../card/extra.js";
import { _status } from "../../../../noname.js";
import { cardCost, canPayCard, isActiveCardUse, SHA_DAMAGE } from "../battle/combat-rules.js";
const packs = [standard, extra];
const names = [...new Set(packs.flatMap(pack => pack.list.map(entry => entry[2])))];
const sourceCard = name => standard.card[name] || extra.card[name];
const sourceText = name => extra.translate[`${name}_info`] || standard.translate[`${name}_info`];
export function createMengsanCards() {
const card = {};
const translate = {};
for (const name of names) {
const source = sourceCard(name);
if (!source) throw new Error(`梦三牌定义缺失:${name}`);
const copy = { ...source, mengsanCost_shuying: cardCost({ name }) };
// 卡牌本身校验费用;响应和濒死救援不属于主动出牌。
if (source.enable || source.type === "equip" || source.type === "delay") {
copy.enable = function (used, player, event) {
if (isActiveCardUse(event || _status.event, player) && !canPayCard(player, used)) return false;
return typeof source.enable === "function" ? source.enable.call(this, used, player, event) : source.enable ?? true;
};
}
const prompt = source.cardPrompt;
const costLabel = name === "shan" || name === "wuxie"
? "响应不消耗费用" : `主动使用消耗${copy.mengsanCost_shuying}费用`;
copy.cardPrompt = function (used) {
const detail = typeof prompt === "function" ? prompt.call(this, used) : prompt;
return `梦三:${costLabel}。${detail || sourceText(name) || ""}`;
};
const nativeText = sourceText(name);
if (nativeText) translate[`${name}_info`] = `梦三:${costLabel}。${nativeText}`;
card[name] = copy;
}
// 【杀】的基础伤害由牌内容决定,而不是事后追加伤害的角色技能。
const nativeSha = sourceCard("sha");
card.sha.baseDamage = SHA_DAMAGE;
card.sha.content = async function (event, trigger, player) {
if (typeof event.baseDamage !== "number") event.baseDamage = SHA_DAMAGE;
return nativeSha.content.call(this, event, trigger, player);
};
card.sha.usable = Infinity;
card.sha.cardPrompt = () => `梦三:主动使用消耗1费用;目标须使用【闪】,否则受到${SHA_DAMAGE}点伤害。`;
translate.sha_info = `梦三:主动使用消耗1费用。出牌阶段,对攻击范围内的一名角色使用;其须使用【闪】,否则受到${SHA_DAMAGE}点伤害。每回合使用次数不限。`;
// 【桃】的回复量也由梦三牌本体提供;救援仍不消耗费用。
card.tao.content = async function (event) { await event.target.recover(8); };
translate.tao_info = "梦三:主动使用消耗1费用,回复8点生命;濒死救援不消耗费用,同样回复8点生命。";
card.taoyuan.content = async function (event) { await event.target.recover(8); };
translate.taoyuan_info = "梦三:主动使用消耗2费用。所有角色各回复8点生命。";
card.taoyuan.cardPrompt = () => translate.taoyuan_info;
for (const name of ["nanman", "wanjian", "juedou"]) {
const nativeContent = sourceCard(name).content;
card[name].baseDamage = SHA_DAMAGE;
card[name].content = async function (event, trigger, player) {
if (typeof event.baseDamage !== "number") event.baseDamage = SHA_DAMAGE;
return nativeContent.call(this, event, trigger, player);
};
const detail = {
nanman: "所有其他角色须打出【杀】,否则受到4点伤害。",
wanjian: "所有其他角色须打出【闪】,否则受到4点伤害。",
juedou: "目标与你轮流打出【杀】;未能打出的一方受到4点伤害。",
}[name];
translate[`${name}_info`] = `梦三:主动使用消耗${cardCost({ name })}费用。${detail}`;
card[name].cardPrompt = () => translate[`${name}_info`];
}
// 火攻通过当前牌事件的 baseDamage 传入 damage("fire")。
card.huogong.baseDamage = SHA_DAMAGE;
translate.huogong_info = "梦三:主动使用消耗1费用。令一名有手牌的角色展示一张手牌;若你弃置同花色牌,对其造成4点火焰伤害。";
card.huogong.cardPrompt = () => translate.huogong_info;
// 闪电属于延时锦囊,其命中伤害在 effect 中显式写死为3,需要独立覆写。
card.shandian.effect = async function (event, trigger, player, result) {
if (result.bool === false) await player.damage(12, "thunder", "nosource");
else player.addJudgeNext(event.card);
};
translate.shandian_info = "梦三:主动使用消耗1费用。若判定为黑桃2~9,目标受到12点雷电伤害;否则移至下家的判定区。";
card.shandian.cardPrompt = () => translate.shandian_info;
return { card, translate, names };
}
+206
View File
@@ -0,0 +1,206 @@
// Mode-owned piles use real Card nodes so native searches/gain/insert operations agree.
// DIY must access ui piles inside the acting player's engine event, never cache global nodes.
import { cardCost } from "../battle/combat-rules.js";
import { AFFIX_INFO } from "./affixes.js";
export function installPersonalPiles(session, owner, battle, run, resources, env) {
const { game, ui, get, _status, document, MutationObserver, shuffle } = env;
for (const key of ["cardPile", "discardPile"]) {
const descriptor = Object.getOwnPropertyDescriptor(ui, key);
if (!descriptor || !descriptor.configurable || (!Object.hasOwn(descriptor, "value") && typeof descriptor.get !== "function")) throw new Error("Unsupported pile property: " + key);
}
const draw = document.createElement("div"), discard = document.createElement("div");
// Detached nodes: engine get.position recognises these IDs; no duplicate document IDs.
draw.id = "cardPile"; discard.id = "discardPile";
const owned = new Set(), restores = [], costBadges = new Map();
const strict = env.strict !== false;
let released = false, forcedOwner = false;
const personal = () => {
if (released) return false;
if (forcedOwner) return true;
const seen = new Set();
for (let event = _status.event; event && !seen.has(event); event = event.parent) {
seen.add(event);
if (event.player) return event.player === owner;
}
return false; // Never infer ownership from whose turn it is.
};
const refresh = () => { if (!released) env.refresh(); };
function showCost(card) {
if (!env.showCosts || !card?.name) return;
const cost = String(cardCost(card));
card.dataset.mengsanCost = cost;
let badge = costBadges.get(card);
if (!badge) {
badge = Array.from(card.children || []).find(child => child.classList?.contains("mengsan-hand-cost-shuying"));
if (!badge) {
badge = document.createElement("span");
badge.className = "mengsan-hand-cost-shuying";
badge.setAttribute("aria-hidden", "true");
card.appendChild(badge);
}
costBadges.set(card, badge);
}
// 十周年 UI scans thrown-card children via innerText when adding “刘备使用”.
// Keep this child text-free so its numeric cost cannot match that scan.
badge.textContent = "";
badge.dataset.mengsanCost = cost;
}
function adopt(card, data) {
if (owned.has(card)) return;
owned.add(card); resources.card(card);
card.storage ||= {};
card.storage.mengsanOwnerId_shuying = owner.playerid;
if (data) {
card.storage.mengsanCard_shuying = JSON.parse(JSON.stringify(data));
// Retired affixes from old saves must not acquire new battle behaviour.
card.storage.mengsanCard_shuying.affixes = (card.storage.mengsanCard_shuying.affixes || []).filter(key => key !== "annihilate");
}
if (data) showCost(card);
// Existing foreign/generated cards retain their original destruction semantics.
if (!data) return;
card.destroyLog = false;
card.destroyed = (current, position) => {
if (released || !["discardPile", "equip", "judge"].includes(position)) return false;
if (current.storage.mengsanCard_shuying.affixes.includes("exhaust") && current.storage.mengsanConsumed_shuying) {
if (current.storage.mengsanExhausted_shuying) return true;
current.storage.mengsanExhausted_shuying = true;
battle.exhaustPile.push(snapshot(current));
refresh();
return true;
}
return false; // Actual discarded cards remain available to native skills.
};
for (const key of card.storage.mengsanCard_shuying.affixes) card.addGaintag(AFFIX_INFO[key]?.name || key);
if (data.upgrade) card.addGaintag(`强化+${data.upgrade}`);
}
function snapshot(card) {
const data = card.storage?.mengsanCard_shuying || {};
return { ...data, name: card.name, suit: card.suit, number: card.number,
nature: card.nature || null, affixes: data.affixes?.slice() || [], upgrade: data.upgrade || 0 };
}
for (const data of battle.drawPile) {
const card = game.createCard(data.name, data.suit, data.number, data.nature);
adopt(card, data); draw.appendChild(card);
}
// Native and 十周年 UI both move real card nodes into these hand containers.
// Decorate newly gained cards without patching either UI's card factory or layout.
const handZones = [owner.node?.handcards1, owner.node?.handcards2].filter(Boolean);
const handObserver = new MutationObserver(mutations => {
if (released) return;
for (const mutation of mutations) for (const card of mutation.addedNodes) {
if (card.classList?.contains("card")) showCost(card);
}
});
for (const zone of handZones) {
for (const card of zone.childNodes) if (card.classList?.contains("card")) showCost(card);
handObserver.observe(zone, { childList: true });
}
session.ownResource(handObserver, () => {
handObserver.disconnect();
for (const [card, badge] of costBadges) {
if (badge.parentNode === card) badge.remove();
delete card.dataset.mengsanCost;
}
costBadges.clear();
});
const publicDiscard = ui.discardPile;
for (const [key, node] of [["cardPile", draw], ["discardPile", discard]]) {
const descriptor = Object.getOwnPropertyDescriptor(ui, key);
let publicNode = descriptor.value;
const read = () => personal() ? node : (descriptor.get ? descriptor.get.call(ui) : publicNode);
Object.defineProperty(ui, key, { configurable: true, enumerable: descriptor.enumerable,
get: read, set(value) { if (descriptor.set) descriptor.set.call(ui, value); else publicNode = value; } });
restores.push(() => {
if (Object.getOwnPropertyDescriptor(ui, key)?.get === read) Object.defineProperty(ui, key, descriptor.get ? descriptor : { ...descriptor, value: publicNode });
});
}
for (const [key, node] of [["drawPile", draw], ["discardPile", discard]]) {
Object.defineProperty(battle, key, { configurable: true, enumerable: true,
get: () => Array.from(node.childNodes, snapshot) });
}
const observer = new MutationObserver(() => {
if (released) return;
// A card from our deck can be discarded during an enemy-owned event.
for (const card of Array.from(publicDiscard.childNodes)) if (owned.has(card)) discard.appendChild(card);
for (const node of [draw, discard]) for (const card of node.childNodes) adopt(card);
refresh();
});
for (const node of [draw, discard, publicDiscard]) observer.observe(node, { childList: true });
function wash() {
const cards = [...draw.childNodes, ...discard.childNodes];
if (!cards.length) return false;
shuffle(run, cards);
for (const card of cards) { card.fix?.(); draw.appendChild(card); }
refresh();
return true;
}
function take(number = 1, putBack = false, bottom = false) {
if (!Number.isFinite(number) || number <= 0) return [];
number = Math.ceil(number);
if (draw.childNodes.length + discard.childNodes.length < number) {
if (strict) { game.mengsanFailRun_shuying("个人牌堆与弃牌堆不足,挑战失败"); return []; }
number = draw.childNodes.length + discard.childNodes.length;
}
const cards = [];
while (cards.length < number) {
if (!draw.childNodes.length) wash();
const card = draw.removeChild(bottom ? draw.lastChild : draw.firstChild); card.original = "c"; cards.push(card);
}
if (putBack) for (let i = cards.length - 1; i >= 0; i--) {
if (bottom) draw.appendChild(cards[i]); else draw.insertBefore(cards[i], draw.firstChild);
}
refresh(); return cards;
}
function wrap(object, key, replacement) {
const descriptor = Object.getOwnPropertyDescriptor(object, key), original = object[key];
const wrapped = function (...args) { return personal() ? replacement(...args) : original.apply(this, args); };
object[key] = wrapped;
restores.push(() => { if (object[key] === wrapped) { if (descriptor) Object.defineProperty(object, key, descriptor); else delete object[key]; } });
}
wrap(get, "cards", (number, putBack) => take(typeof number === "number" ? number : 1, putBack));
wrap(get, "bottomCards", (number, putBack) => take(typeof number === "number" ? number : 1, putBack, true));
wrap(game, "washCard", wash);
session.ownResource(draw, () => {
if (released) return;
observer.disconnect(); released = true;
for (const restore of restores.reverse()) restore();
for (const card of owned) card.remove();
owned.clear(); draw.remove(); discard.remove();
});
return {
take,
addAffix(card, key) {
if (released || !Object.hasOwn(AFFIX_INFO, key) || !owned.has(card) || !owner.getCards("h").includes(card)) return false;
const affixes = card.storage?.mengsanCard_shuying?.affixes;
if (!Array.isArray(affixes) || affixes.includes(key)) return false;
affixes.push(key);
card.addGaintag(AFFIX_INFO[key].name);
refresh();
return true;
},
// Engine/mod opening draws must not stack with the mode's four-card opening hand.
resetOpeningHand() {
for (const card of owner.getCards("h")) {
if (owned.has(card)) draw.insertBefore(card, draw.firstChild);
else card.remove();
}
refresh();
},
trimOpeningHand(limit = 4) {
for (const card of owner.getCards("h").filter(card => !card.storage?.mengsanCard_shuying?.affixes?.includes("innate")).slice(limit)) {
if (owned.has(card)) draw.insertBefore(card, draw.firstChild);
else card.remove();
}
refresh();
},
drawInnate() {
const cards = Array.from(draw.childNodes).filter(card => card.storage?.mengsanCard_shuying?.affixes?.includes("innate") && !owner.getCards("h").includes(card));
if (cards.length) owner.directgain(cards);
refresh();
return cards;
},
withOwner(callback) { const before = forcedOwner; forcedOwner = true; try { return callback(); } finally { forcedOwner = before; } },
};
}
+33
View File
@@ -0,0 +1,33 @@
import { createCardData } from "./card-data.js";
// Mode-owned starting decks. Existing saves always retain their actual player.deck.
export const defaultDeck = Object.freeze([
["spade", 7, "sha"], ["heart", 10, "sha"],
["club", 4, "sha"], ["diamond", 6, "sha"],
["heart", 2, "shan"], ["diamond", 7, "shan"], ["club", 2, "shan"],
["heart", 3, "tao"], ["spade", 3, "guohe"], ["heart", 7, "wuzhong"],
["spade", 2, "bagua"], ["club", 6, "sha"],
].map(Object.freeze));
// Character ID -> [suit, number, card name, optional nature, optional affixes].
// Example: edit these twelve entries to change only this private Liu Bei's new-run deck.
export const characterDecks = {
mengsan_liubei_shuying: [
["spade", 7, "sha"], ["heart", 10, "sha"], ["club", 4, "sha"], ["diamond", 6, "sha"],
["heart", 2, "shan"], ["diamond", 7, "shan"], ["club", 2, "shan"],
["heart", 3, "tao"], ["heart", 7, "wuzhong"], ["spade", 1, "juedou"],
["spade", 2, "bagua"], ["club", 6, "sha"],
],
};
export function getStartingDeck(character) {
const override = Object.hasOwn(characterDecks, character) ? characterDecks[character] : null;
return Array.isArray(override) && override.length ? override : defaultDeck;
}
export function createStartingDeck(character, prefix = `mengsan_card_${Date.now()}`) {
return getStartingDeck(character).map((entry, index) => createCardData({
id: `${prefix}_${index}`, suit: entry[0], number: entry[1], name: entry[2],
nature: entry[3] || null, affixes: entry[4] ? entry[4].slice() : [], upgrade: 0,
}, { character }));
}
+12 -51
View File
@@ -1,68 +1,29 @@
import { defaultDeck } from "./cards/starting-deck.js";
import contentRegistry from "./content/registry.js";
const mengsanConfig = {
modeId: "mengsan_shuying",
saveKey: "mengsan_run_shuying",
profileKey: "mengsan_profile_shuying",
schemaVersion: 1,
mapLayoutVersion: 3,
mapLayoutVersion: 8,
routeCount: 4,
characters: ["re_zhaoyun", "sunquan", "re_huangyueying", "re_zhangfei"],
acts: [
{
id: "act1",
name: "第一关·初梦",
floorNodes: [1, 4, 4, 4, 1],
minFloorNodes: [1, 3, 3, 3, 1],
nodeWeights: { battle: 65, event: 15, rest: 10, shop: 10 },
enemies: ["re_xiahoudun", "re_zhangliao", "re_xuzhu"],
boss: "re_lvbu",
baseGold: 20,
},
{
id: "act2",
name: "第二关·迷梦",
floorNodes: [1, 4, 4, 4, 4, 1],
minFloorNodes: [1, 3, 2, 3, 3, 1],
nodeWeights: { battle: 55, elite: 15, event: 12, rest: 9, shop: 9 },
enemies: ["re_ganning", "re_zhangfei", "re_huangzhong", "re_weiyan"],
eliteEnemies: ["re_guanyu", "dianwei"],
boss: "shen_guanyu",
baseGold: 30,
},
{
id: "act3",
name: "第三关·终梦",
floorNodes: [1, 4, 4, 4, 4, 4, 1],
minFloorNodes: [1, 3, 2, 3, 2, 3, 1],
nodeWeights: { battle: 45, elite: 20, event: 15, rest: 10, shop: 10 },
enemies: ["re_simayi", "re_sunben", "dongzhuo", "re_yuanshao"],
eliteEnemies: ["shen_zhaoyun", "shen_simayi"],
boss: "shen_caocao",
baseGold: 40,
},
],
startingDeck: [
["spade", 7, "sha"],
["heart", 10, "sha"],
["club", 4, "sha"],
["diamond", 6, "sha"],
["heart", 2, "shan"],
["diamond", 7, "shan"],
["club", 2, "shan"],
["heart", 3, "tao"],
["spade", 3, "guohe"],
["heart", 7, "wuzhong"],
["spade", 2, "bagua"],
["club", 6, "sha", null, ["annihilate"]],
],
characters: ["mengsan_liubei_shuying"],
acts: contentRegistry.acts,
startingDeck: defaultDeck,
nodeNames: {
battle: "战斗",
elite: "精英",
event: "事件",
story: "剧情战斗",
story: "剧情",
chest: "宝箱",
rest: "休息",
shop: "商店",
boss: "Boss",
},
nodeContents: contentRegistry.nodeContents,
rewardPools: contentRegistry.rewardPools,
rewards: contentRegistry.rewards,
};
export default mengsanConfig;
+14
View File
@@ -0,0 +1,14 @@
import liubeiOpening, { openingRewards } from "./stories/liubei-opening.js";
import actMap from "./map.js";
import { rewardPools } from "./rewards.js";
import forestAmbush from "./stories/forest-ambush.js";
export default {
map: actMap,
nodeContents: {
[forestAmbush.id]: forestAmbush,
[liubeiOpening.id]: liubeiOpening,
},
rewardPools,
rewards: openingRewards,
};
+29
View File
@@ -0,0 +1,29 @@
const act1Map = {
id: "act1",
name: "第一关·初梦",
floorNodes: [
1, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 1,
],
minFloorNodes: [
1, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 1,
],
nodeWeights: { battle: 65, event: 15, rest: 10, shop: 10 },
requiredFloors: { 2: "battle", 10: "chest", 16: "rest" },
chestRewardPool: "act1.pool.chest",
fixedNodes: [
{
floor: 0,
position: "start",
type: "battle",
contentId: "act1.battle.liubeiOpening",
},
],
enemies: ["mengsan_flyconid_shuying", "mengsan_raider_trio_shuying"],
eliteEnemies: ["re_xiahoudun", "re_zhangliao", "re_xuzhu"],
boss: "re_lvbu",
baseGold: 20,
};
export default act1Map;
+32
View File
@@ -0,0 +1,32 @@
// 灰机 Wiki:五名劫掠者中随机抽取三名,且同场不重复。
export const RAIDER_TRIO_ENCOUNTER = "mengsan_raider_trio_shuying";
export const RAIDER_MEMBERS = Object.freeze([
Object.freeze({ character: "mengsan_raider_brute_shuying", minHp: 30, maxHp: 33 }),
Object.freeze({ character: "mengsan_raider_assassin_shuying", minHp: 18, maxHp: 23 }),
Object.freeze({ character: "mengsan_raider_axe_shuying", minHp: 20, maxHp: 22 }),
Object.freeze({ character: "mengsan_raider_crossbow_shuying", minHp: 18, maxHp: 21 }),
Object.freeze({ character: "mengsan_raider_tracker_shuying", minHp: 21, maxHp: 25 }),
]);
export function createRaiderTrioBattlePlan(random) {
if (typeof random !== "function") throw new TypeError("劫掠者团伙需要随机数生成器");
const members = RAIDER_MEMBERS.slice();
const pick = count => {
const value = random();
if (!Number.isFinite(value) || value < 0 || value >= 1) throw new RangeError("随机数必须在 [0,1) 内");
return Math.floor(value * count);
};
for (let index = members.length - 1; index > 0; index--) {
const other = pick(index + 1);
[members[index], members[other]] = [members[other], members[index]];
}
return {
units: members.slice(0, 3).map((member, index) => {
const hp = member.minHp + pick(member.maxHp - member.minHp + 1);
return { id: `raider_${index + 1}`, character: member.character,
camp: "enemy", tier: "normal", hp, maxHp: hp, hand: 4 };
}),
rules: [],
};
}
+21
View File
@@ -0,0 +1,21 @@
export const rewardPools = {
"act1.pool.chest": [
"shared.reward.item.handCharm",
"shared.reward.maxHp",
"shared.reward.support.scout",
],
"act1.pool.story.scoutGift": [
"shared.reward.support.scout",
"shared.reward.card.sha",
"shared.reward.card.tao",
"shared.reward.card.upgrade",
"shared.reward.item.handCharm",
],
"act1.pool.story.ambushLoot": [
"shared.reward.card.sha",
"shared.reward.card.tao",
"shared.reward.card.upgrade",
"shared.reward.heal",
"shared.reward.item.handCharm",
],
};
@@ -0,0 +1,112 @@
const forestAmbush = {
id: "act1.story.forestAmbush",
kind: "dialogue",
name: "林中伏兵",
mapName: "林中伏兵",
description: "你在密林中遇到一名负伤的斥候。他声称前方有伏兵,并请求你决定下一步行动。",
dialogue: [
{
type: "narrator",
text: "暮色压进密林,归巢的鸟雀忽然一齐噤声。",
},
{
type: "sound",
speaker: "林间异响",
text: "沙沙……咔嚓!",
speed: 45,
},
{
type: "character",
character: "re_zhangliao",
speaker: "负伤斥候",
text: "且慢!前方埋伏着一队精兵。我侥幸逃出,已无力再探。",
},
{
type: "character",
character: "$player",
speaker: "$player",
text: "先把你知道的情形说清楚,我再决定如何行动。",
},
],
choices: [
{
id: "listen_and_leave",
name: "听完警告后离开",
description: "结束对话,不发生战斗,也不获得奖励。",
outcome: {
result: "你记下了斥候的警告,绕开了危险区域。",
dialogue: [
{ type: "narrator", text: "你记下警告,沿着一条隐蔽的小径绕开了危险区域。" },
],
flags: {
"story.act1.heardAmbushWarning": true,
"story.act1.ambushResult": "left",
},
},
},
{
id: "help_scout",
name: "帮助斥候处理伤势",
description: "不进入战斗,从随机出现的三个谢礼中选择一个。",
outcome: {
result: "斥候恢复了行动能力,并拿出随身物资作为谢礼。",
dialogue: [
{
type: "character",
character: "re_zhangliao",
speaker: "负伤斥候",
text: "多谢相助。这些随身物资,请务必收下。",
},
],
rewardPool: "act1.pool.story.scoutGift",
rewardTitle: "斥候的谢礼(三选一)",
flags: {
"story.act1.helpedScout": true,
"story.act1.ambushResult": "helped",
},
},
},
{
id: "hunt_ambushers",
name: "主动追击伏兵",
description: "迎战两名伏兵,第 3 轮还有敌军增援;胜利后获得金币并选择战利品。",
outcome: {
result: "你循着林间留下的痕迹追了上去。",
dialogue: [
{ type: "character", character: "$player", speaker: "$player", text: "与其绕路,不如趁他们尚未察觉,先发制人。" },
{ type: "sound", text: "刀剑出鞘之声划破寂静。" },
],
battle: {
enemies: ["re_xiahoudun", "re_zhangliao", "re_xuzhu"],
gold: 30,
// Two initial enemies; a third-round reinforcement demonstrates the rule system.
battlePlan: {
units: [
{ id: "captain", character: "re_xiahoudun", camp: "enemy", hand: 4 },
{ id: "guard", character: "re_xuzhu", camp: "enemy", hand: 2 },
],
rules: [
{ id: "enemy_reinforcement", name: "伏兵增援", blocksVictory: true, when: { event: "roundStart", round: 3 },
effects: [{ type: "spawn", unit: { id: "reinforcement", character: "re_zhangliao", camp: "enemy", hand: 3 } }] },
{ id: "captain_rally", name: "困兽犹斗", when: { event: "state", all: [
{ unit: "captain", field: "alive", value: true }, { unit: "captain", field: "hp", op: "lte", value: 2 },
] }, effects: [{ type: "draw", target: "captain", amount: 2 }] },
{ id: "player_supply", name: "临阵补给", when: { event: "state", all: [
{ unit: "player", field: "hand", op: "lte", value: 1 },
] }, effects: [{ type: "draw", target: "player", amount: 2 }] },
],
},
rewardPool: "act1.pool.story.ambushLoot",
rewardTitle: "伏兵战利品(三选一)",
description: "击败伏兵后,从随机出现的三个奖励中选择一个。",
},
flags: {
"story.act1.huntedAmbushers": true,
"story.act1.ambushResult": "fought",
},
},
},
],
};
export default forestAmbush;
@@ -0,0 +1,72 @@
export const openingDialogue = [
{ type: "narrator", text: "你是21世纪的一名普通牛马。" },
{ type: "narrator", text: "某天你晚上9点照常下班,刚出公司大门,就撞大运了。" },
{ type: "narrator", text: "等你睁开眼发现自己竟已身在三国,成为桃园结义后的刘备了。" },
{ type: "character", character: "$player", text: "(内心)我叫刘备。眼前这两位,便是与我结为兄弟的关羽和张飞。此刻,三弟正与二弟谈论黄巾之乱。" },
{ type: "character", character: "zhangfei", text: "大哥!如今黄巾作乱,官府正在招募义兵。俺们既已结为兄弟,何不召集乡勇,起兵讨伐黄巾贼?" },
{ type: "character", character: "guanyu", text: "三弟所言有理。只是起兵讨贼,须备足钱粮、兵器,方能成事。此事如何安排,还请大哥定夺。" },
{
type: "choice", text: "还好我历史满分!但是我不想干活啊。", flag: "story.act1.liubeiOpening.reply", defaultChoice: "gather", choices: [
{ id: "gather", text: "眼下先召集乡亲,整备人手,再从长计议。待我上山巡视一番,说不定有一张SSR呢。" },
]
},
{ type: "character", character: "zhangfei", text: "SSR为何物?" },
{ type: "narrator", text: "你不等张飞吐槽,转身拂袖而去。" },
{ type: "narrator", text: "乡间小道之上,忽听前方有人高声喝道:“黄巾军押运辎重,闲人速速避让,莫要挡路!”" },
{ type: "narrator", text: "只见一人一马疾驰而来。" },
{ type: "character", character: "$player", text: "(内心)这就开始刷怪了?白送的物资来了。" },
{ type: "narrator", text: "只见你伸腿一拦,只见对方勒马拔剑,进入战斗。" },
];
export const reinforcementDialogue = [
{ type: "character", character: "$player", text: "(内心)我靠,对面有马我没马啊。" },
{ type: "character", character: "mengsan_sushuang_zhangshiping_shuying", text: "将军莫急,我等前来助战。" },
];
export const victoryDialogue = [
{ type: "character", character: "$player", text: "方才多谢二位出手相助,尚未请教二位尊姓大名?" },
{ type: "character", character: "mengsan_sushuang_zhangshiping_shuying", text: "在下苏双,这位是张世平。我二人皆是中山商贾。" },
{ type: "character", character: "$player", text: "原来是苏兄、张兄。不知二位为何来到此处?" },
{ type: "character", character: "mengsan_sushuang_zhangshiping_shuying", text: "我二人贩马经商,途经涿郡。久闻玄德素有豪侠之名,特来拜会。" },
{ type: "character", character: "mengsan_sushuang_zhangshiping_shuying", text: "入城打听之时,恰遇张壮士。听闻玄德正在此处,我二人便一路寻来。" },
{ type: "character", character: "mengsan_sushuang_zhangshiping_shuying", text: "不料刚到此地,便见玄德与黄巾贼交战。今日一见,果然名不虚传。" },
{ type: "character", character: "$player", text: "二位过誉了。既然远道而来,不如随我回寒舍一叙?" },
{ type: "character", character: "mengsan_sushuang_zhangshiping_shuying", text: "玄德盛情,我二人心领了。只是商队不日便要启程,实不便久留。" },
{ type: "character", character: "mengsan_sushuang_zhangshiping_shuying", text: "听闻玄德正欲招募乡勇、讨伐黄巾。我二人虽是商贾,也愿略尽绵薄之力。" },
{ type: "character", character: "mengsan_sushuang_zhangshiping_shuying", text: "我二人常年贩马,别的或许帮不上忙,良马倒有一些,愿赠与玄德,助义兵一臂之力。" },
{ type: "character", character: "mengsan_sushuang_zhangshiping_shuying", text: "至于甲胄兵器,我二人并不经营。听闻蜀郡有一年轻匠人,名唤蒲元,颇善锻造,如今在刘焉麾下。玄德若欲寻他,不妨前往投靠刘焉。" }
];
export const openingRewards = {
"act1.reward.dilu": {
id: "act1.reward.dilu", name: "的卢", description: "+1坐骑,加入本次征程的个人牌库。",
card: { name: "dilu", suit: "club", number: 5, nature: null },
},
};
export default {
id: "act1.battle.liubeiOpening", kind: "battle", name: "刘备初始剧情", mapName: "初识的卢",
requiredCharacter: "mengsan_liubei_shuying",
enemies: ["mengsan_soldier_shuying"], gold: 20,
skipRandomReward: true, fixedRewards: ["act1.reward.dilu"], openingDialogue, victoryDialogue,
battlePlan: {
units: [{
id: "soldier", character: "mengsan_soldier_shuying", camp: "enemy",
inheritSkills: false, skills: [], hand: 4, hp: 24, maxHp: 24,
equipment: [{ name: "dilu", suit: "club", number: 5 }],
}],
rules: [{
id: "merchants_arrive", name: "苏双与张世平支援",
when: { event: "turnEnd", actor: "player", actorTurns: 4 },
effects: [
{ type: "dialogue", lines: reinforcementDialogue },
{
type: "spawn", unit: {
id: "merchants", character: "mengsan_sushuang_zhangshiping_shuying", camp: "ally",
after: "player", inheritSkills: false, skills: [], hand: 4, hp: 4, maxHp: 4,
}
},
{ type: "discardEquipment", target: "soldier", name: "dilu" },
],
}],
},
};
+8
View File
@@ -0,0 +1,8 @@
import actMap from "./map.js";
export default {
map: actMap,
nodeContents: {},
rewardPools: {},
rewards: {},
};
+13
View File
@@ -0,0 +1,13 @@
const act2Map = {
id: "act2",
name: "第二关·迷梦",
floorNodes: [1, 4, 4, 4, 4, 1],
minFloorNodes: [1, 3, 2, 3, 3, 1],
nodeWeights: { battle: 55, elite: 15, event: 12, rest: 9, shop: 9 },
enemies: ["re_ganning", "re_zhangfei", "re_huangzhong", "re_weiyan"],
eliteEnemies: ["re_guanyu", "dianwei"],
boss: "shen_guanyu",
baseGold: 30,
};
export default act2Map;
+8
View File
@@ -0,0 +1,8 @@
import actMap from "./map.js";
export default {
map: actMap,
nodeContents: {},
rewardPools: {},
rewards: {},
};
+13
View File
@@ -0,0 +1,13 @@
const act3Map = {
id: "act3",
name: "第三关·终梦",
floorNodes: [1, 4, 4, 4, 4, 4, 1],
minFloorNodes: [1, 3, 2, 3, 2, 3, 1],
nodeWeights: { battle: 45, elite: 20, event: 15, rest: 10, shop: 10 },
enemies: ["re_simayi", "re_sunben", "dongzhuo", "re_yuanshao"],
eliteEnemies: ["shen_zhaoyun", "shen_simayi"],
boss: "shen_caocao",
baseGold: 40,
};
export default act3Map;
+99
View File
@@ -0,0 +1,99 @@
import { validateBattlePlan } from "../battle/battle-director.js";
import act1 from "./acts/act1/index.js";
import act2 from "./acts/act2/index.js";
import act3 from "./acts/act3/index.js";
import shared from "./shared/index.js";
const addEntries = (target, source, category) => {
Object.entries(source || {}).forEach(([id, value]) => {
if (Object.prototype.hasOwnProperty.call(target, id)) throw new Error(`梦三${category} ID重复:${id}`);
target[id] = value;
});
};
const packages = [shared, act1, act2, act3];
const nodeContents = {};
const rewardPools = {};
const rewards = {};
const dialogueTypes = new Set(["character", "narrator", "sound", "choice"]);
const validateDialogue = (dialogue, location) => {
if (dialogue == null) return;
if (!Array.isArray(dialogue)) throw new Error(`梦三剧情台词必须为数组:${location}`);
dialogue.forEach((line, index) => {
const lineLocation = `${location} #${index + 1}`;
if (!line || !dialogueTypes.has(line.type)) throw new Error(`梦三剧情台词类型无效:${lineLocation}`);
if (typeof line.text != "string" || !line.text.trim()) throw new Error(`梦三剧情台词内容为空:${lineLocation}`);
if (line.type == "character" && !line.character) throw new Error(`梦三角色台词缺少武将ID:${lineLocation}`);
if (line.when && (!/^story\.[\w.]+$/.test(line.when.flag || "") || typeof line.when.equals !== "string")) throw new Error(`梦三剧情条件无效:${lineLocation}`);
if (line.type == "choice" && (!/^story\.[\w.]+$/.test(line.flag || "") || !Array.isArray(line.choices) || line.choices.length < 1 ||
new Set(line.choices.map(choice => choice.id)).size !== line.choices.length ||
line.choices.some(choice => !/^[\w.-]+$/.test(choice.id || "") || typeof choice.text !== "string" || !choice.text.trim()) ||
(line.defaultChoice != null && !line.choices.some(choice => choice.id === line.defaultChoice)))) {
throw new Error(`梦三发言选项无效:${lineLocation}`);
}
if (line.speed != null && (!Number.isFinite(line.speed) || line.speed < 0)) {
throw new Error(`梦三剧情台词速度无效:${lineLocation}`);
}
});
};
packages.forEach(content => {
addEntries(nodeContents, content.nodeContents, "节点内容");
addEntries(rewardPools, content.rewardPools, "奖励池");
addEntries(rewards, content.rewards, "奖励");
});
const acts = [act1.map, act2.map, act3.map];
if (new Set(acts.map(act => act.id)).size != acts.length) throw new Error("梦三大关ID存在重复");
acts.forEach(act => {
(act.fixedNodes || []).forEach(node => {
if (!nodeContents[node.contentId]) throw new Error(`梦三固定节点内容不存在:${node.contentId}`);
if (!Number.isInteger(node.floor) || node.floor < 0 || node.floor >= act.floorNodes.length) {
throw new Error(`梦三固定节点楼层越界:${node.contentId}`);
}
});
});
Object.entries(rewardPools).forEach(([poolId, rewardIds]) => {
if (!Array.isArray(rewardIds) || rewardIds.length < 3) throw new Error(`梦三奖励池至少需要三项:${poolId}`);
if (new Set(rewardIds).size != rewardIds.length) throw new Error(`梦三奖励池存在重复项:${poolId}`);
rewardIds.forEach(rewardId => {
if (!rewards[rewardId]) throw new Error(`梦三奖励不存在:${poolId} -> ${rewardId}`);
});
});
Object.entries(nodeContents).forEach(([contentId, content]) => {
if (content.id != contentId) throw new Error(`梦三节点内容ID不一致:${contentId}`);
validateDialogue(content.dialogue, contentId);
validateDialogue(content.victoryDialogue, contentId + " 战后");
validateDialogue(content.openingDialogue, contentId + " 开场");
for (const id of content.fixedRewards || []) if (!rewards[id]) throw new Error("固定奖励不存在:" + id);
if (content.battlePlan) validateBattlePlan(content.battlePlan);
(content.choices || []).forEach(choice => {
if (!choice.id) throw new Error(`梦三剧情选项缺少ID:${contentId}`);
const outcome = choice.outcome || {};
if (outcome.battle?.battlePlan) validateBattlePlan(outcome.battle.battlePlan);
validateDialogue(outcome.dialogue, `${contentId} -> ${choice.id}`);
const referencedPools = [outcome.rewardPool, outcome.battle?.rewardPool].filter(Boolean);
referencedPools.forEach(poolId => {
if (!rewardPools[poolId]) throw new Error(`梦三剧情奖励池不存在:${contentId} -> ${poolId}`);
});
if (outcome.battle && !outcome.battle.enemies?.length && !outcome.battle.battlePlan) {
throw new Error(`梦三剧情战斗敌人池为空:${contentId} -> ${choice.id}`);
}
if (outcome.confirmResult != null && typeof outcome.confirmResult != "boolean") {
throw new Error(`梦三剧情confirmResult必须为布尔值:${contentId} -> ${choice.id}`);
}
if (choice.requires && !Array.isArray(choice.requires)) throw new Error(`梦三剧情requires必须为数组:${contentId}`);
if (choice.excludes && !Array.isArray(choice.excludes)) throw new Error(`梦三剧情excludes必须为数组:${contentId}`);
});
});
Object.values(rewards).forEach(reward => {
if (!reward.support) return;
validateBattlePlan({ units: [{ ...reward.support.unit, id: "reward_support" }], rules: [] });
const battles = reward.support.battles ?? -1;
if (battles !== -1 && (!Number.isInteger(battles) || battles < 1 || battles > 99)) throw new Error("梦三支援持续场数无效");
});
const contentRegistry = { acts, nodeContents, rewardPools, rewards };
export default contentRegistry;
+35
View File
@@ -0,0 +1,35 @@
// 梦三私有武将:不改动原版界刘备,也不导入整套国战技能。
export function createScenarioCharacters(Character) {
return {
mengsan_liubei_shuying: new Character({ sex: "male", group: "han", hp: 50, maxHp: 50,
skills: [], img: "image/character/re_liubei.jpg" }),
// 国战男性普通小兵使用原生 shibing1 立绘;实际战斗生命由怪物类或关卡配置决定。
mengsan_soldier_shuying: new Character({ sex: "male", group: "qun", hp: 4, maxHp: 4,
skills: [], img: "image/character/shibing1.jpg" }),
mengsan_flyconid_shuying: new Character({ sex: "none", group: "qun", hp: 48, maxHp: 48,
skills: [], img: "extension/术樱包/mengsan/assets/portraits/flyconid-portrait.png" }),
mengsan_raider_brute_shuying: new Character({ sex: "none", group: "qun", hp: 32, maxHp: 32,
skills: [], img: "extension/术樱包/mengsan/assets/portraits/raider-brute-portrait.png" }),
mengsan_raider_assassin_shuying: new Character({ sex: "none", group: "qun", hp: 21, maxHp: 21,
skills: [], img: "extension/术樱包/mengsan/assets/portraits/raider-assassin-portrait.png" }),
mengsan_raider_axe_shuying: new Character({ sex: "none", group: "qun", hp: 21, maxHp: 21,
skills: [], img: "extension/术樱包/mengsan/assets/portraits/raider-axe-portrait.png" }),
mengsan_raider_crossbow_shuying: new Character({ sex: "none", group: "qun", hp: 20, maxHp: 20,
skills: [], img: "extension/术樱包/mengsan/assets/portraits/raider-crossbow-portrait.png" }),
mengsan_raider_tracker_shuying: new Character({ sex: "none", group: "qun", hp: 23, maxHp: 23,
skills: [], img: "extension/术樱包/mengsan/assets/portraits/raider-tracker-portrait.png" }),
mengsan_sushuang_zhangshiping_shuying: new Character({ sex: "male", group: "shu", hp: 4, maxHp: 4,
skills: [], img: "extension/术樱包/mengsan/assets/portraits/sushuang-zhangshiping.png", names: "苏|双-张|世平" }),
};
}
export const scenarioTranslations = {
mengsan_liubei_shuying: "界刘备", mengsan_liubei_shuying_title: "50/50生命 · 无初始技能",
mengsan_soldier_shuying: "士兵",
mengsan_flyconid_shuying: "飞蝇菌子",
mengsan_raider_brute_shuying: "劫掠者暴徒",
mengsan_raider_assassin_shuying: "劫掠者刺客",
mengsan_raider_axe_shuying: "劫掠者斧手",
mengsan_raider_crossbow_shuying: "劫掠者弩手",
mengsan_raider_tracker_shuying: "劫掠者追踪手",
mengsan_sushuang_zhangshiping_shuying: "苏双&张世平",
};
+7
View File
@@ -0,0 +1,7 @@
import { rewardPools, rewards } from "./rewards.js";
export default {
nodeContents: {},
rewardPools,
rewards,
};
+27
View File
@@ -0,0 +1,27 @@
export const rewards = {
"shared.reward.support.scout": {
name: "道具·斥候援令", description: "本次征程后续每场战斗,友方张辽携 4 张手牌参战;重复获得不叠加人数。",
support: { category: "item", battles: -1, unit: { character: "re_zhangliao", camp: "ally", hand: 4 } },
},
"shared.reward.card.sha": { effectId: "card_sha", name: "获得一张【杀】", description: "加入独立永久牌组" },
"shared.reward.card.tao": { effectId: "card_tao", name: "获得一张【桃】", description: "加入独立永久牌组" },
"shared.reward.card.wuzhong": { card: { name: "wuzhong" }, name: "获得一张【无中生有】", description: "加入独立永久牌组" },
"shared.reward.card.upgrade": { effectId: "upgrade", name: "随机强化", description: "随机一张牌强化一级" },
"shared.reward.heal": { effectId: "heal", name: "整顿伤势", description: "回复 8 点生命" },
"shared.reward.item.handCharm": { effectId: "item_hand", name: "道具·束带", description: "基础手牌上限额外 +1" },
"shared.reward.skill.heroic": { effectId: "skill_yingyong", name: "极品技能·英勇", description: "本次征程永久获得【英勇】" },
"shared.reward.maxHp": { effectId: "max_hp", name: "极品强化·生机", description: "生命上限与当前生命各 +5" },
};
export const rewardPools = {
"shared.pool.battle.normal": [
"shared.reward.card.sha",
"shared.reward.card.tao",
"shared.reward.card.wuzhong",
],
"shared.pool.boss.premium": [
"shared.reward.skill.heroic",
"shared.reward.item.handCharm",
"shared.reward.maxHp",
],
};
+98
View File
@@ -0,0 +1,98 @@
# 梦三:关卡条件与战斗支援
## 约定
- 本模块是梦三玩法规则,不批量修改武将技能源码。
- 主角固定单位 ID:`player`;`ally` 为友方,`enemy` 为敌方。
- `neutral` 仅保留预设,目前配置为中立会报错,不启用中立行为。
- 主角使用个人牌堆;友方支援和敌人仍使用公共牌堆。
- 没有 `battlePlan` 的旧关卡继续使用原来随机的一名敌人。
- 本版单场累计最多 8 个席位,包含主角、初始单位、奖励支援、以后出现的援军。
## 配置位置
节点内容或剧情选项的 `outcome.battle` 中增加 `battlePlan`。
Boss 也可以在大关配置的 `bossBattlePlan` 中定义。
`units` 中每一项是一名初始角色,因此数组长度就是初始非主角人数。
```js
battlePlan: {
units: [
{ id: "captain", character: "re_xiahoudun", camp: "enemy", hand: 4 },
{ id: "guard", character: "re_xuzhu", camp: "enemy", hand: 2 },
],
rules: [
{
id: "rescue", name: "友军驰援",
when: { event: "roundStart", round: 3 },
effects: [{ type: "spawn", unit: {
id: "helper", character: "re_zhangliao", camp: "ally", hand: 4,
} }],
},
{
id: "low_hp", name: "背水一战",
when: { event: "state", all: [
{ unit: "captain", field: "alive", value: true },
{ unit: "captain", field: "hp", op: "lte", value: 2 },
] },
effects: [{ type: "draw", target: "captain", amount: 2 }],
},
{
id: "supply", name: "主角补给",
when: { event: "state", all: [
{ unit: "player", field: "hand", op: "lte", value: 1 },
] },
effects: [{ type: "draw", target: "player", amount: 2 }],
},
],
}
```
## 字段
初始/援军单位:`id`、`character`、`camp`;可选 `hand`(默认 4)、`hp`、`maxHp`、`skills`。
每个单位 ID 必须唯一,引用 ID 而不是武将名称,允许同武将的不同单位。
每条规则每场仅触发一次,效果按书写顺序执行;不支持任意脚本、eval 或无限重复规则。
- `when.event`:`battleStart` 开场、`roundStart` 新轮、`turnStart` 每名角色主循环回合开始、`state` 状态变化。
- `when.round`:至少到第 N 轮。主角第一次进入主循环为第 1 轮;额外技能回合不另计轮。
- `when.turn`:至少到主循环第 N 个回合;所有角色一起计数,额外技能回合不计。
- `when.actor`:限定当前主循环行动单位,可用于 turnStart/roundStart。
- `when.all`:所有条件同时满足。`hp`、`hand` 使用 `eq`/`gte`/`lte` 比较。
- `alive`、`linked`、`turnedOver` 比较布尔值;`camp` 比较 `ally`/`enemy`。
- state 在开场、回合边界及体力/手牌/死亡/横置/翻面事件后检查,不轮询。
效果:`spawn`(提供 unit)、`draw`/`recover`/`maxHp`(target + amount)、`skill`(target + skill)、`camp`(target + camp)。
主角不能改阵营;死亡或尚未出现的目标不会执行数值/技能增益。规则不会复活角色。
`skill` 为本场增加技能,战后随角色统一释放,不写入永久技能。
`blocksVictory: true` 用于必须等待的敌方援军波次;未触发时不会提前胜利。
默认 false,避免可选援军条件永久不成立导致战斗无法结束。
若设为 true,作者必须保证该条件可以达成。条件同样适用于玩家方。
## 奖励支援
在奖励注册表中配置 support,不设置旧的 effectId:
```js
"shared.reward.support.example": {
name: "道具·援令", description: "本次征程后续每场战斗获得友方支援。",
support: {
category: "item", // item 道具、bond 羁绊来源(仅数据预留)、buff 其他增益
battles: -1, // -1 或省略:本征程持续;正整数 N:持续 N 场战斗
unit: { character: "re_zhangliao", camp: "ally", hand: 4 },
},
},
```
再将奖励 ID 加入指定 rewardPools。相同奖励来源不叠加人数;临时次数可累加,永久来源保持永久。
数据保存在 `run.player.supports`,旧存档没有该字段时按空列表处理。
有限次数只随结算事务提交;重载未完成战斗不会额外扣次,重试结算不会重复发放。
行囊的“战斗支援”显示来源名称和持续场数。此版本未实现羁绊系统本身。
## 已接入的示例
- 林中伏兵“主动追击”:两名初始敌人,第 3 轮必定出现一名敌军援军。
- 敌军队长体力不高于 2 时摸两张;主角手牌不多于 1 时补两张,各限一次。
- 斥候谢礼奖励池加入“道具·斥候援令”,本征程后续每场由友方张辽参战。
## 结算和清理
仅主角死亡判负;存活友军不阻碍胜利。清空敌军且没有必须等待的敌军规则后判胜。
援军使用原生加入座次/enterGame,登记玩家 ID、技能释放和战斗资源清理。
身份模式原有的杀反贼摸三张、误杀忠臣弃牌惩罚不沿用;奖励由梦三结算和上述规则决定。
统计记录实际战败敌军数量,而非固定每场加一。
已做隔离配置/规则/事务检查;未启动游戏、未进行实际战斗或界面验收。
+20
View File
@@ -0,0 +1,20 @@
# 梦三战斗规则(测试阶段)
只影响梦三模式,不修改 noname 的标准/军争原始牌包。`cards/mode-cards.js` 从标准、军争实体牌列表逐一复制模式专属定义,沿用原牌名以保留响应、装备、转化兼容性;图鉴说明在梦三模式覆盖。新征程的界刘备为 50/50 生命,默认每回合摸 2 张、手牌上限 3、回合费用恢复至 3。主动使用牌消耗费用,转化牌按转化后的牌名计费;响应【闪】、救援【桃】等不消耗费用。默认主动牌 1 费,`battle/combat-rules.js` 中列出例外。【杀】1 费、可多次使用,牌定义的基础伤害为 4;【桃】及【桃园结义】回复 8 点生命;【南蛮入侵】、【万箭齐发】、【决斗】、【火攻】基础伤害 4,【闪电】命中伤害 12。其余卡牌保留原有效果,并加上梦三费用与图鉴说明。
## 怪物
`monsters/monster.js` 的 `Monster` 类统一提供阶级默认值。普通/精英/Boss 分别每回合摸 1/2/3 张、手牌上限 3/5/7、回合费用 2/3/4。每名敌人拥有自己的抽牌堆、弃牌堆与手牌;怪物默认使用阶级牌堆,不再从公共牌堆摸牌。友方支援仍用公共牌堆。
`HEALTH` 为目前各敌人的独立生命值;新怪物未配置时使用阶级兜底生命值。`OpeningSoldier extends Monster` 是继承示例;新子类在 `MONSTER_TYPES` 注册。关卡单位可以写 `tier`、`hp/maxHp`、`draw`、`handLimit`、`energy`、`deck` 覆盖默认值;`deck` 可为牌名数组(如 `deck:["sha","shan","tao"]`),也可用 `{name,suit,number}` 指定单张牌。牌名必须在 noname 中存在。
## 配置位置
- 玩家费用、手牌上限、卡牌费用与【杀】伤害:`battle/combat-rules.js`
- 梦三模式卡牌复制、内容与图鉴文案:`cards/mode-cards.js`
- 怪物阶级、默认牌堆、生命与继承示例:`monsters/monster.js`
- 刘备角色初始生命:`content/scenario-characters.js`
- 刘备专属初始牌组:`cards/starting-deck.js`
- 首关小兵覆盖数值:`content/acts/act1/stories/liubei-opening.js`
旧存档不作迁移。源码检查不等于游戏内、十周年 UI 或 AI 行为验收。
+26
View File
@@ -0,0 +1,26 @@
# 刘备首关配置
新征程仅显示梦三私有界刘备:4/4、无初始技能。原版界刘备和其他模式不变;旧征程不强行换主角。
## 编辑入口
`content/acts/act1/stories/liubei-opening.js`:
- `openingDialogue`:开战前播放。原先填写的穿越与关张对话误放在第四回合支援台词里,现已移到这里。
- `openingDialogue` 中的 `type:"choice"` 可让玩家选择刘备发言;`flag` 指定征程存档的 `storyFlags` 键,选中后存入选项 `id`。后续台词可用 `when:{flag:"...",equals:"选项id"}` 控制是否显示。选项会随本关胜利结算写入征程存档,后续关卡可据此分支;中途退出战斗不会单独保存选择。
- 每段对话左上角可点“跳过对话”。尚未选择的发言会采用该行的 `defaultChoice`;未配置时采用 `choices` 第一项,并照常写入 `storyFlags`。已手动选择的发言不会被跳过操作覆盖。一个选项的发言也有效。
- `reinforcementDialogue`:刘备第四次完整回合结束时的台词,空数组跳过。
- `victoryDialogue`:胜利后、奖励结算前台词;失败不播放,不给马。
- `battlePlan.units`:敌人;`skills` 添加技能,`inheritSkills:false` 不加载原武将技能。
- `hand` 初始手牌数(可为0)、`hp` 当前体力、`maxHp` 上限;`equipment` 初始装备,指定 name/suit/number,可选nature。同一普通装备槽不可重复。
- `when:{event:"turnEnd",actor:"player",actorTurns:4}`:主角本人第四次回合结束,不是全场第四回合,也不是第四轮开始。额外完整回合也计数。
- 支援单位 `after:"player"` 插入刘备下家;该支援仅当前战斗有效,不写入永久道具/羁绊。
- 苏双&张世平为一名男性蜀势力武将,暂设无技能、4/4、4张初始手牌,可自行调整。
- `discardEquipment` 弃置指定单位装备区的指定牌;已不在装备区则不重复弃置,不影响其他装备。
- `fixedRewards` 固定获得梅花5的卢一张,加入征程个人牌库;此关关闭随机三选一。奖励与节点完成一起事务提交,重试不会重复发牌。
- 初始士兵/支援手牌仍来自公共牌堆;弃掉的敌方的卢走原生弃牌流程,胜利所得的卢是持久牌库新卡,并非再从弃牌区拾取。
- 提前击败敌人允许正常获胜,此时未到第四次回合的支援不会触发。不强行等待、不添加免死。
## 新角色立绘
`assets/portraits/sushuang-zhangshiping.png` 为本次 image_gen 生成的原创双人立绘,不是官方素材。
## 验证边界
隔离脚本检查配置、回合计数、效果顺序及奖励幂等,不等于游戏/十周年UI验收。请开始新征程检查真实引擎的装备、座次、AI和剧情显示。
+784 -298
View File
File diff suppressed because it is too large Load Diff
+131
View File
@@ -0,0 +1,131 @@
import {
attackHitCount,
outgoingAttackDamage,
} from "../battle/intent-damage.js";
import { beginDeathBlow, isDeathBlowIntent } from "../battle/death-blow.js";
import { isStunned } from "../battle/stun-intent.js";
import { nextRandom } from "../progression/state.js";
import { selectFlyconidMove, recordFlyconidAction } from "./flyconid-intent.js";
import {
isRaiderCharacter,
selectRaiderMove,
recordRaiderAction,
} from "./raider-intent.js";
export const isFlyconid = player =>
player?.name === "mengsan_flyconid_shuying" &&
player.storage?.mengsanCamp_shuying === "enemy";
export const isRaider = player =>
player?.storage?.mengsanCamp_shuying === "enemy" &&
isRaiderCharacter(player.name);
export function createMonsterIntentActions(game, getActiveBattle) {
const planEnemyIntent = (player, run) => {
if (!player?.isAlive() || isStunned(player)) return;
if (isFlyconid(player)) {
if (player.storage.mengsanFlyconidIntent_shuying) return;
const move = selectFlyconidMove(
player.storage.mengsanFlyconidState_shuying || {},
() => nextRandom(run));
player.storage.mengsanFlyconidIntent_shuying = move;
game.mengsanSetEnemyIntent_shuying(player, move);
} else if (isRaider(player)) {
if (player.storage.mengsanRaiderIntent_shuying) return;
const move = selectRaiderMove(player.name,
player.storage.mengsanRaiderState_shuying || {});
player.storage.mengsanRaiderIntent_shuying = move;
game.mengsanSetEnemyIntent_shuying(player, move);
}
};
const applyIntentDebuff = (target, move) => {
if (!move.debuff) return;
const frail = move.debuff === "脆弱";
const key = frail ? "mengsanFrail_shuying" :
"mengsanVulnerable_shuying";
target.storage[key] = (target.storage[key] || 0) + move.stacks;
target.addSkill(frail ? "mengsan_frail_shuying" :
"mengsan_vulnerable_shuying");
target.markSkill(frail ? "mengsan_frail_shuying" :
"mengsan_vulnerable_shuying");
};
const dealIntentDamage = async (source, target, move) => {
if (move.damage == null) return;
for (let index = 0; index < attackHitCount(move); index++) {
if (!target.isAlive() || !source.isAlive()) break;
const hit = target.damage(
outgoingAttackDamage(move, source), source);
hit.mengsanAttack_shuying = true;
hit.mengsanScriptedSkill_shuying = true;
await hit;
}
};
const executeFlyconidIntent = async player => {
const move = player.storage.mengsanFlyconidIntent_shuying;
if (!move) return;
player.storage.mengsanFlyconidIntent_shuying = null;
game.mengsanSetEnemyIntent_shuying(player, null);
const paid = player.storage.mengsanEnergy_shuying >= 1;
player.storage.mengsanFlyconidState_shuying =
recordFlyconidAction(
player.storage.mengsanFlyconidState_shuying || {},
move, paid);
if (!paid) {
game.log(player, "费用不足,未发动", move.name);
return;
}
player.storage.mengsanEnergy_shuying--;
getActiveBattle()?.energyUI.get(player)?.();
game.log(player, "消耗1费用发动", move.name);
const target = game.me;
if (!target?.isAlive() || !player.isAlive()) return;
if (isDeathBlowIntent(move)) {
await beginDeathBlow(player, target, move);
return;
}
await dealIntentDamage(player, target, move);
if (target.isAlive() && player.isAlive()) {
applyIntentDebuff(target, move);
}
};
const executeRaiderIntent = async player => {
const move = player.storage.mengsanRaiderIntent_shuying;
if (!move) return;
player.storage.mengsanRaiderIntent_shuying = null;
game.mengsanSetEnemyIntent_shuying(player, null);
player.storage.mengsanRaiderState_shuying = recordRaiderAction(
player.storage.mengsanRaiderState_shuying || {});
if (player.storage.mengsanEnergy_shuying < 1) {
game.log(player, "费用不足,未发动", move.name);
return;
}
player.storage.mengsanEnergy_shuying--;
getActiveBattle()?.energyUI.get(player)?.();
game.log(player, "消耗1费用发动", move.name);
const target = game.me;
if (!target?.isAlive() || !player.isAlive()) return;
await dealIntentDamage(player, target, move);
if (target.isAlive() && player.isAlive()) {
applyIntentDebuff(target, move);
}
if (!player.isAlive() || !getActiveBattle()?.session.active) return;
if (move.block) await player.changeHujia(move.block);
if (move.strength) {
player.storage.mengsanStrength_shuying =
(player.storage.mengsanStrength_shuying || 0) +
move.strength;
player.addSkill("mengsan_raider_strength_shuying");
player.markSkill("mengsan_raider_strength_shuying");
}
};
return {
planEnemyIntent,
executeFlyconidIntent,
executeRaiderIntent,
};
}
+37
View File
@@ -0,0 +1,37 @@
// 冷却按飞蝇菌子自己的行动次数计算,不受玩家回合或增援数量影响。
export const FLYCONID_MOVES = Object.freeze({
smash: Object.freeze({ id: "smash", name: "猛砸", damage: 11 }),
frail: Object.freeze({ id: "frail", name: "脆弱孢子", damage: 8, debuff: "脆弱", stacks: 2 }),
vulnerable: Object.freeze({ id: "vulnerable", name: "易伤孢子", debuff: "易伤", stacks: 2 }),
});
export function eligibleFlyconidMoves(state = {}) {
const upcoming = (state.turnsTaken || 0) + 1;
const lastUsed = state.lastUsed || {};
const moves = [];
if (state.lastMove !== "smash") moves.push(FLYCONID_MOVES.smash);
if (lastUsed.frail == null || upcoming - lastUsed.frail > 2) moves.push(FLYCONID_MOVES.frail);
if (upcoming >= 2 && (lastUsed.vulnerable == null || upcoming - lastUsed.vulnerable > 3)) moves.push(FLYCONID_MOVES.vulnerable);
return moves;
}
export function selectFlyconidMove(state, random) {
const moves = eligibleFlyconidMoves(state);
if (!moves.length) return null;
const roll = random();
if (!Number.isFinite(roll) || roll < 0 || roll >= 1) throw new RangeError("怪物随机数必须在 [0,1) 内");
return moves[Math.floor(roll * moves.length)];
}
export function recordFlyconidAction(state, move, paid) {
const next = {
turnsTaken: (state.turnsTaken || 0) + 1,
lastMove: state.lastMove || null,
lastUsed: { ...(state.lastUsed || {}) },
};
if (paid && move) {
next.lastMove = move.id;
next.lastUsed[move.id] = next.turnsTaken;
}
return next;
}
+96
View File
@@ -0,0 +1,96 @@
import { createCardData } from "../cards/card-data.js";
// 梦三怪物规则只作用于敌方单位;子类可覆盖构造参数或 createDeck()。
const TIER_RULES = Object.freeze({
normal: Object.freeze({ draw: 1, handLimit: 3, energy: 2 }),
elite: Object.freeze({ draw: 2, handLimit: 5, energy: 3 }),
boss: Object.freeze({ draw: 3, handLimit: 7, energy: 4 }),
});
const BASE_DECKS = Object.freeze({
normal: Object.freeze(["sha", "sha", "sha", "sha", "shan", "shan", "tao", "jiu", "guohe", "sha"]),
elite: Object.freeze(["sha", "sha", "sha", "sha", "shan", "shan", "shan", "tao", "jiu", "juedou", "wuzhong", "guohe"]),
boss: Object.freeze(["sha", "sha", "sha", "sha", "sha", "shan", "shan", "shan", "tao", "tao", "jiu", "jiu", "juedou", "wuzhong", "guohe"]),
});
const HEALTH = Object.freeze({
mengsan_soldier_shuying: 24,
mengsan_flyconid_shuying: 48,
mengsan_raider_brute_shuying: 32,
mengsan_raider_assassin_shuying: 21,
mengsan_raider_axe_shuying: 21,
mengsan_raider_crossbow_shuying: 20,
mengsan_raider_tracker_shuying: 23,
re_xiahoudun: 30, re_zhangliao: 28, re_xuzhu: 34, re_lvbu: 120,
re_ganning: 39, re_zhangfei: 42, re_huangzhong: 37, re_weiyan: 40,
re_guanyu: 65, dianwei: 62, shen_guanyu: 165,
re_simayi: 47, re_sunben: 49, dongzhuo: 55, re_yuanshao: 52,
shen_zhaoyun: 76, shen_simayi: 80, shen_caocao: 210,
});
const validDeckCard = entry => typeof entry === "string" ? Boolean(entry) : Boolean(entry &&
typeof entry.name === "string" && entry.name &&
(entry.suit == null || ["spade", "heart", "club", "diamond"].includes(entry.suit)) &&
(entry.number == null || Number.isInteger(entry.number) && entry.number >= 1 && entry.number <= 13));
export class Monster {
constructor({ character, tier = "normal", hp, deck, draw, handLimit, energy } = {}) {
if (!TIER_RULES[tier]) throw new Error("梦三怪物阶级无效:" + tier);
if (typeof character !== "string" || !character) throw new Error("梦三怪物缺少武将ID");
const defaults = TIER_RULES[tier];
this.character = character;
this.tier = tier;
this.hp = hp ?? HEALTH[character] ?? (tier === "boss" ? 110 : tier === "elite" ? 60 : 32);
this.draw = draw ?? defaults.draw;
this.handLimit = handLimit ?? defaults.handLimit;
this.energy = energy ?? defaults.energy;
this.deck = deck || BASE_DECKS[tier];
if (![this.hp, this.draw, this.handLimit, this.energy].every(value => Number.isInteger(value) && value > 0)) throw new Error("梦三怪物数值无效");
if (!Array.isArray(this.deck) || !this.deck.length || this.deck.some(entry => !validDeckCard(entry))) throw new Error("梦三怪物牌堆无效");
}
createDeck(prefix) {
return this.deck.map((entry, index) => {
const card = typeof entry === "string" ? { name: entry } : entry;
return createCardData({
id: `${prefix}_${index}`, name: card.name,
suit: card.suit || ["spade", "heart", "club", "diamond"][index % 4],
number: card.number || index % 13 + 1,
nature: card.nature || null, affixes: Array.isArray(card.affixes) ? card.affixes.slice() : [], upgrade: card.upgrade || 0,
}, { enemy: true });
});
}
}
// 专属怪物示例:以后可在子类中覆写任意默认行为。
export class OpeningSoldier extends Monster {
constructor(options = {}) { super({ character: "mengsan_soldier_shuying", tier: "normal", hp: 24, ...options }); }
}
export class Flyconid extends Monster {
constructor(options = {}) { super({ ...options, character: "mengsan_flyconid_shuying", tier: "normal", hp: 48 }); }
}
const raiderClass = (character, hp) => class extends Monster {
constructor(options = {}) { super({ ...options, character, tier: "normal", hp }); }
};
export const RaiderBrute = raiderClass("mengsan_raider_brute_shuying", 32);
export const RaiderAssassin = raiderClass("mengsan_raider_assassin_shuying", 21);
export const RaiderAxe = raiderClass("mengsan_raider_axe_shuying", 21);
export const RaiderCrossbow = raiderClass("mengsan_raider_crossbow_shuying", 20);
export const RaiderTracker = raiderClass("mengsan_raider_tracker_shuying", 23);
// 新怪物子类在这里注册,未注册的角色使用 Monster 的阶级默认值。
export const MONSTER_TYPES = Object.freeze({
mengsan_soldier_shuying: OpeningSoldier,
mengsan_flyconid_shuying: Flyconid,
mengsan_raider_brute_shuying: RaiderBrute,
mengsan_raider_assassin_shuying: RaiderAssassin,
mengsan_raider_axe_shuying: RaiderAxe,
mengsan_raider_crossbow_shuying: RaiderCrossbow,
mengsan_raider_tracker_shuying: RaiderTracker,
});
export function createMonster(spec) {
const Type = Object.hasOwn(MONSTER_TYPES, spec.character) ? MONSTER_TYPES[spec.character] : Monster;
return new Type(spec);
}
export { TIER_RULES, BASE_DECKS };
+39
View File
@@ -0,0 +1,39 @@
// 普通难度数值;团伙每名成员仅预测并执行自己的一项技能,随后照常出牌。
export const RAIDER_MOVES = Object.freeze({
beat: Object.freeze({ id: "beat", name: "殴打", damage: 7 }),
roar: Object.freeze({ id: "roar", name: "怒吼", strength: 3 }),
killshot: Object.freeze({ id: "killshot", name: "致命射击", damage: 10 }),
swing: Object.freeze({ id: "swing", name: "挥击", damage: 5, block: 5 }),
bigSwing: Object.freeze({ id: "bigSwing", name: "大力挥舞", damage: 12 }),
reload: Object.freeze({ id: "reload", name: "装填", block: 3 }),
fire: Object.freeze({ id: "fire", name: "射击!", damage: 14 }),
track: Object.freeze({ id: "track", name: "追踪", debuff: "脆弱", stacks: 2 }),
hounds: Object.freeze({ id: "hounds", name: "放狗", damage: 1, hits: 8 }),
});
export const RAIDER_CYCLES = Object.freeze({
mengsan_raider_brute_shuying: Object.freeze([RAIDER_MOVES.beat, RAIDER_MOVES.roar]),
mengsan_raider_assassin_shuying: Object.freeze([RAIDER_MOVES.killshot]),
mengsan_raider_axe_shuying: Object.freeze([RAIDER_MOVES.swing, RAIDER_MOVES.swing, RAIDER_MOVES.bigSwing]),
mengsan_raider_crossbow_shuying: Object.freeze([RAIDER_MOVES.reload, RAIDER_MOVES.fire]),
mengsan_raider_tracker_shuying: Object.freeze([RAIDER_MOVES.track, RAIDER_MOVES.hounds]),
});
export function isRaiderCharacter(character) {
return Object.hasOwn(RAIDER_CYCLES, character);
}
export function selectRaiderMove(character, state = {}) {
const cycle = RAIDER_CYCLES[character];
if (!cycle) return null;
const turn = state.turnsTaken || 0;
if (!Number.isInteger(turn) || turn < 0) throw new RangeError("劫掠者行动次数无效");
if (character === "mengsan_raider_tracker_shuying") {
return turn === 0 ? RAIDER_MOVES.track : RAIDER_MOVES.hounds;
}
return cycle[turn % cycle.length];
}
export function recordRaiderAction(state = {}) {
return { turnsTaken: (state.turnsTaken || 0) + 1 };
}
+17
View File
@@ -0,0 +1,17 @@
export const isDialogueLineVisible = (line, run) => !line.when || run?.storyFlags?.[line.when.flag] === line.when.equals;
export const applyDialogueChoice = (run, line, choiceId) => {
const choice = line.choices?.find(item => item.id === choiceId);
if (!choice || !run || !/^story\.[\w.]+$/.test(line.flag || "")) throw new Error("梦三剧情发言选项无效");
run.storyFlags ||= {};
run.storyFlags[line.flag] = choice.id;
return choice.text;
};
export const applySkippedDialogueChoices = (lines, startIndex, run) => {
for (let index = startIndex; index < lines.length; index++) {
const line = lines[index];
if (!isDialogueLineVisible(line, run) || line.type !== "choice") continue;
applyDialogueChoice(run, line, line.defaultChoice || line.choices[0].id);
}
};
+91
View File
@@ -0,0 +1,91 @@
// Candidate factory. Storage writer body reused from batch2 MODIFIED_STORAGE.js.
export function createModeStorage({lib, game, config, localStorage, alert = () => {}, console = globalThis.console}) {
const MODE_ID = config.modeId;
const copy = value => JSON.parse(JSON.stringify(value));
// Keep one mode-level writer; a failed write must not poison later retries.
let modeStorageQueue = Promise.resolve();
const writeModeStorage = storage => {
if (!lib.db) {
// Do not switch backends after an IndexedDB error: that creates two saves.
localStorage.setItem(`${lib.configprefix}${MODE_ID}`, JSON.stringify(storage));
return Promise.resolve();
}
return new Promise((resolve, reject) => {
let transaction;
let requestError;
try {
// game.putDB resolves at request success, which is before commit.
transaction = lib.db.transaction(["data"], "readwrite");
transaction.oncomplete = () => resolve();
transaction.onerror = event => {
requestError = event.target?.error;
};
transaction.onabort = () => reject(transaction.error || requestError || new Error("梦三存档事务已中止"));
transaction.objectStore("data").put(storage, MODE_ID);
}
catch (error) {
if (transaction) {
try { transaction.abort(); }
catch {} // Already inactive; keep the original failure.
}
reject(error);
}
});
};
const persistModeStorage = (update = () => {}) => {
// Hold the engine reload guard from enqueue through commit and publication.
// reload2 also drains the engine's queued database operations on release.
lib.status.reload++;
const operation = modeStorageQueue.then(async () => {
const storage = copy(lib.storage);
update(storage);
storage.version = lib.version;
await writeModeStorage(storage);
lib.storage = storage;
}).finally(() => game.reload2());
modeStorageQueue = operation.catch(() => {});
return operation;
};
const saveRun = async run => {
try {
// Capture before enqueue: subsequent gameplay mutations cannot alter this save.
const snapshot = copy(run);
await persistModeStorage(storage => {
storage[config.saveKey] = snapshot;
});
}
catch (error) {
// Neither delete the previous save nor attempt a second destructive write.
alert("梦三存档失败,未覆盖上一次成功保存的进度。当前进度尚未保存,请勿刷新,并查看控制台错误。");
console.error("梦三存档失败:", error);
throw error;
}
};
const clearRun = async () => {
await persistModeStorage(storage => {
delete storage[config.saveKey];
});
};
return Object.freeze({
read: () => copy(lib.storage),
saveRun, clearRun,
async update(mutator) {
let value;
await persistModeStorage(storage => {
value = mutator(storage);
if (value && typeof value.then === "function") throw new TypeError("Storage mutator must be synchronous");
});
return value === undefined ? undefined : copy(value);
},
});
}
+20
View File
@@ -0,0 +1,20 @@
import config from "../config.js";
import { nextRandom } from "./state.js";
import { canAcquireCard } from "../cards/card-definitions.js";
export const rewardCardName = reward => reward?.card?.name || ({ card_sha: "sha", card_tao: "tao" })[reward?.effectId] || null;
export const canAcquireReward = (run, reward) => {
const name = rewardCardName(reward);
return !name || canAcquireCard(run?.player?.character, name);
};
export const getRandomRewardChoices = (run, poolId, count = 3) => {
const fallbackId = "shared.pool.battle.normal";
const pool = (config.rewardPools[poolId] || config.rewardPools[fallbackId])
.filter(id => canAcquireReward(run, config.rewards[id])).slice();
for (let index = pool.length - 1; index > 0; index--) {
const target = Math.floor(nextRandom(run) * (index + 1));
[pool[index], pool[target]] = [pool[target], pool[index]];
}
return pool.slice(0, count).map(id => ({ id, ...config.rewards[id] }));
};
@@ -1,4 +1,6 @@
import config from "./config.js";
import { createStartingDeck } from "../cards/starting-deck.js";
import config from "../config.js";
import { RAIDER_TRIO_ENCOUNTER, createRaiderTrioBattlePlan } from "../content/acts/act1/raider-trio.js";
const hashText = text => {
let value = 2166136261;
@@ -71,7 +73,24 @@ const getFloorRoutes = (run, act, floor, lastFloor) => {
const target = Math.floor(nextRandom(run) * (index + 1));
[routes[index], routes[target]] = [routes[target], routes[index]];
}
return routes.slice(0, count).sort((left, right) => left - right);
const selectedRoutes = routes.slice(0, count);
const fixedRoutes = [...new Set((act.fixedNodes || [])
.filter(node => node.floor == floor)
.map(node => node.routeIndex)
.filter(routeIndex => Number.isInteger(routeIndex) && routeIndex >= 0 && routeIndex < routeCount))];
fixedRoutes.forEach(routeIndex => {
if (selectedRoutes.includes(routeIndex)) return;
let replaceIndex = -1;
for (let index = selectedRoutes.length - 1; index >= 0; index--) {
if (!fixedRoutes.includes(selectedRoutes[index])) {
replaceIndex = index;
break;
}
}
if (replaceIndex >= 0) selectedRoutes[replaceIndex] = routeIndex;
else if (selectedRoutes.length < routeCount) selectedRoutes.push(routeIndex);
});
return selectedRoutes.sort((left, right) => left - right);
};
export const generateActMap = (run, actIndex) => {
@@ -84,8 +103,17 @@ export const generateActMap = (run, actIndex) => {
const floorNodes = [];
const routes = getFloorRoutes(run, act, floor, lastFloor);
routes.forEach((routeIndex, index) => {
const fixedNode = act.fixedNodes?.find(node => {
if (node.floor != floor) return false;
if (node.position == "start") return floor == 0;
return node.routeIndex == routeIndex;
});
let type;
if (floor == lastFloor) type = "boss";
else if (fixedNode?.type) type = fixedNode.type;
else if (act.requiredFloors?.[floor + 1]) {
type = act.requiredFloors[floor + 1];
}
else if (floor == 0) type = "battle";
else type = weightedType(run, act.nodeWeights);
const id = `${act.id}_f${floor}_n${index}_${Math.floor(nextRandom(run) * 1e6)}`;
@@ -93,6 +121,7 @@ export const generateActMap = (run, actIndex) => {
id,
floor,
type,
contentId: fixedNode?.contentId || null,
routeIndex,
x: Math.round((routeIndex + 1) * 100 / (config.routeCount + 1)),
y: Math.round(90 - floor * 80 / Math.max(1, lastFloor)),
@@ -118,16 +147,6 @@ export const generateActMap = (run, actIndex) => {
};
};
const createDeck = () => config.startingDeck.map((entry, index) => ({
id: `mengsan_card_${Date.now()}_${index}`,
suit: entry[0],
number: entry[1],
name: entry[2],
nature: entry[3] || null,
affixes: entry[4] ? entry[4].slice() : [],
upgrade: 0,
}));
export const createRun = character => {
const seed = (Date.now() ^ Math.floor(Math.random() * 0x7fffffff)) >>> 0;
const run = {
@@ -145,7 +164,7 @@ export const createRun = character => {
hp: null,
maxHp: null,
gold: 0,
deck: createDeck(),
deck: createStartingDeck(character),
permanentSkills: [],
temporarySkills: [],
items: [],
@@ -156,6 +175,7 @@ export const createRun = character => {
defeatedEnemies: 0,
goldEarned: 0,
},
storyFlags: {},
};
run.map = generateActMap(run, 0);
return run;
@@ -184,21 +204,23 @@ export const completeNode = (run, nodeId) => {
export const insertStoryNode = (run, sourceId) => {
const map = run.map;
const source = map.nodes.find(node => node.id == sourceId);
const edgeIndex = map.edges.findIndex(edge => edge[0] == sourceId);
if (!source || edgeIndex < 0) return null;
const oldEdge = map.edges[edgeIndex];
const target = map.nodes.find(node => node.id == oldEdge[1]);
if (!target) return null;
const outgoingEdges = map.edges.filter(edge => edge[0] == sourceId);
if (!source || !outgoingEdges.length) return null;
const targets = outgoingEdges.map(edge => map.nodes.find(node => node.id == edge[1])).filter(Boolean);
if (!targets.length) return null;
const averageTargetX = targets.reduce((sum, target) => sum + target.x, 0) / targets.length;
const averageTargetY = targets.reduce((sum, target) => sum + target.y, 0) / targets.length;
const node = {
id: `story_${hashText(`${run.runId}_${sourceId}_${run.revision}`)}`,
floor: source.floor + 0.45,
type: "story",
x: Math.max(8, Math.min(92, Math.round((source.x + target.x) / 2 + (nextRandom(run) - 0.5) * 16))),
y: Math.round((source.y + target.y) / 2),
x: Math.max(8, Math.min(92, Math.round((source.x + averageTargetX) / 2 + (nextRandom(run) - 0.5) * 16))),
y: Math.round((source.y + averageTargetY) / 2),
completed: false,
dynamic: true,
};
map.edges.splice(edgeIndex, 1, [source.id, node.id], [node.id, target.id]);
map.edges = map.edges.filter(edge => edge[0] != sourceId);
map.edges.push([source.id, node.id], ...targets.map(target => [node.id, target.id]));
map.nodes.push(node);
return node;
};
@@ -214,14 +236,33 @@ export const enterNextAct = run => {
return true;
};
export const getNodeEncounter = (run, node) => {
export const getNodeEncounter = (run, node, override = null) => {
const act = config.acts[run.actIndex];
let pool = act.enemies;
const content = node.contentId ? config.nodeContents?.[node.contentId] : null;
const encounter = override || content;
let pool = encounter?.enemies || act.enemies;
if (node.type == "elite" || node.type == "story") pool = act.eliteEnemies?.length ? act.eliteEnemies : act.enemies;
if (node.type == "boss") return { enemy: act.boss, gold: act.baseGold * 3, boss: true };
if (encounter?.enemies?.length) pool = encounter.enemies;
if (node.type == "boss") {
return { battlePlan: encounter?.battlePlan || act.bossBattlePlan || null, enemy: act.boss, tier: "boss", gold: act.baseGold * 3, boss: true, rewardPool: "shared.pool.boss.premium" };
}
const enemy = randomGet(run, pool.filter(Boolean));
return {
enemy: randomGet(run, pool.filter(Boolean)),
gold: node.type == "elite" || node.type == "story" ? act.baseGold * 2 : act.baseGold,
name: encounter?.name || (enemy === RAIDER_TRIO_ENCOUNTER ? "劫掠者团伙" : ""),
requiredCharacter: encounter?.requiredCharacter || null,
openingDialogue: encounter?.openingDialogue || [],
fixedRewards: encounter?.fixedRewards || [],
skipRandomReward: encounter?.skipRandomReward === true,
victoryDialogue: encounter?.victoryDialogue || [],
battlePlan: encounter?.battlePlan || (enemy === RAIDER_TRIO_ENCOUNTER ?
createRaiderTrioBattlePlan(() => nextRandom(run)) : null),
tier: encounter?.tier || (node.type === "elite" ? "elite" : "normal"),
enemy,
gold: encounter?.gold ?? (node.type == "elite" || node.type == "story" ? act.baseGold * 2 : act.baseGold),
boss: false,
contentId: node.contentId || null,
description: encounter?.description || "",
rewardPool: encounter?.rewardPool || "shared.pool.battle.normal",
rewardTitle: encounter?.rewardTitle || "战斗奖励(三选一)",
};
};
+13
View File
@@ -0,0 +1,13 @@
export const getAvailableStoryChoices = (run, content) => {
const flags = run.storyFlags || {};
return (content?.choices || []).filter(choice => {
return (choice.requires || []).every(flag => Boolean(flags[flag]))
&& (choice.excludes || []).every(flag => !flags[flag]);
});
};
export const applyStoryOutcome = (run, outcome = {}) => {
if (!run.storyFlags) run.storyFlags = {};
Object.assign(run.storyFlags, outcome.flags || {});
return outcome;
};
+23
View File
@@ -0,0 +1,23 @@
import { lib, game } from "../../../noname.js";
const MODE_ID = "mengsan_shuying";
export default function registerMengsan() {
if (lib.config.all.mode.includes(MODE_ID)) return;
game.addMode(MODE_ID, {
splash: "ext:术樱包/pve/images/tianshu.jpg",
}, {
translate: "梦三",
config: {},
extension: "术樱包",
});
// game.addMode 默认会闭包保存传入的完整模式对象;这里替换为延迟加载器,
// 确保只有用户真正进入梦三时才解析剧情、地图和奖励等内容模块。
lib.init[`setMode_${MODE_ID}`] = async () => {
const { createMengsanMode } = await import("./mode.js");
const mode = await createMengsanMode();
await game.import("mode", () => mode);
};
}
-258
View File
@@ -1,258 +0,0 @@
.mengsan-overlay-shuying {
position: fixed;
inset: 0;
z-index: 80;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
padding: 18px;
background: radial-gradient(circle at 50% 20%, rgba(68, 62, 83, 0.72), rgba(8, 10, 15, 0.96));
color: #f6ead0;
font-family: "Microsoft YaHei", sans-serif;
}
.mengsan-overlay-shuying *,
.mengsan-overlay-shuying *::before,
.mengsan-overlay-shuying *::after {
box-sizing: border-box;
float: none !important;
writing-mode: horizontal-tb !important;
-webkit-writing-mode: horizontal-tb !important;
text-orientation: mixed !important;
letter-spacing: normal;
}
.mengsan-panel-shuying {
position: relative !important;
left: auto !important;
top: auto !important;
right: auto !important;
bottom: auto !important;
display: flex !important;
flex-direction: column !important;
flex: none !important;
width: min(720px, 94vw);
height: auto !important;
min-height: 160px;
max-height: 92vh;
overflow: auto;
box-sizing: border-box;
padding: 22px;
border: 1px solid rgba(232, 202, 140, 0.55);
border-radius: 14px;
background: linear-gradient(145deg, rgba(31, 28, 38, 0.98), rgba(17, 19, 26, 0.98));
box-shadow: 0 20px 70px rgba(0, 0, 0, 0.58), inset 0 1px rgba(255, 255, 255, 0.08);
}
.mengsan-panel-shuying > .mengsan-title-shuying,
.mengsan-panel-shuying > .mengsan-description-shuying,
.mengsan-panel-shuying > .mengsan-choice-list-shuying,
.mengsan-panel-shuying > .mengsan-map-status-shuying,
.mengsan-panel-shuying > .mengsan-map-shuying,
.mengsan-choice-list-shuying > .mengsan-choice-shuying,
.mengsan-choice-shuying > .mengsan-choice-name-shuying,
.mengsan-choice-shuying > .mengsan-choice-description-shuying {
position: relative !important;
left: auto !important;
top: auto !important;
right: auto !important;
bottom: auto !important;
transform: none !important;
}
.mengsan-title-shuying {
display: block !important;
flex: none !important;
width: 100% !important;
height: auto !important;
margin-bottom: 14px;
color: #f2d28e;
font-size: 30px;
font-weight: 700;
text-align: center;
letter-spacing: 4px;
line-height: 1.35;
white-space: normal !important;
}
.mengsan-description-shuying,
.mengsan-map-status-shuying {
display: block !important;
flex: none !important;
width: 100% !important;
height: auto !important;
margin-bottom: 14px;
color: rgba(255, 255, 255, 0.78);
text-align: center;
line-height: 1.6;
}
.mengsan-choice-list-shuying {
display: grid;
flex: none !important;
width: 100% !important;
height: auto !important;
gap: 12px;
}
.mengsan-choice-shuying {
display: block !important;
width: 100% !important;
height: auto !important;
min-height: 64px;
padding: 14px 16px;
border: 1px solid rgba(242, 210, 142, 0.34);
border-radius: 9px;
background: rgba(255, 255, 255, 0.055);
cursor: pointer;
transition: transform 0.16s ease, border-color 0.16s ease, background 0.16s ease;
}
.mengsan-choice-shuying:hover {
transform: translateY(-2px);
border-color: rgba(242, 210, 142, 0.8);
background: rgba(242, 210, 142, 0.12);
}
.mengsan-choice-shuying.disabled {
cursor: default;
opacity: 0.35;
filter: grayscale(1);
}
.mengsan-choice-name-shuying {
display: block !important;
width: 100% !important;
height: auto !important;
color: #f6dca5;
font-size: 18px;
}
.mengsan-choice-description-shuying {
display: block !important;
width: 100% !important;
height: auto !important;
margin-top: 5px;
color: rgba(255, 255, 255, 0.65);
font-size: 13px;
}
.mengsan-map-panel-shuying {
position: absolute !important;
inset: 0 !important;
width: 100% !important;
height: 100% !important;
min-width: 100%;
min-height: 100%;
max-width: none !important;
max-height: none !important;
padding: clamp(12px, 2vw, 24px);
border: 0;
border-radius: 0;
background: transparent;
box-shadow: none;
overflow: hidden;
}
.mengsan-map-overlay-shuying {
padding: 0 !important;
background:
radial-gradient(circle at 50% 18%, rgba(67, 59, 82, 0.82), rgba(9, 10, 16, 0.97)),
repeating-linear-gradient(12deg, rgba(255, 255, 255, 0.018) 0 2px, transparent 2px 12px);
}
.mengsan-map-panel-shuying > .mengsan-title-shuying {
margin-bottom: 6px;
font-size: clamp(24px, 3vw, 36px);
}
.mengsan-map-panel-shuying > .mengsan-map-status-shuying {
margin-bottom: 10px;
}
.mengsan-map-shuying {
position: relative;
display: block !important;
flex: 1 1 auto !important;
width: 100%;
height: auto !important;
min-height: 0;
overflow: hidden;
border-radius: 0;
background: transparent;
}
.mengsan-lines-shuying {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
overflow: visible;
pointer-events: none;
}
.mengsan-lines-shuying line {
vector-effect: non-scaling-stroke;
stroke: rgba(232, 219, 190, 0.68);
stroke-width: 2;
stroke-linecap: round;
stroke-dasharray: 6 5;
}
.mengsan-lines-shuying line.completed {
stroke: rgba(243, 207, 128, 0.95);
}
.mengsan-lines-shuying line.dynamic {
stroke: rgba(118, 205, 255, 0.95);
stroke-dasharray: 3 4;
}
.mengsan-node-shuying {
position: absolute;
width: 66px;
height: 40px;
transform: translate(-50%, -50%);
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
border: 2px solid var(--node-color);
border-radius: 50%;
background: radial-gradient(circle at 38% 28%, rgba(255, 255, 255, 0.2), transparent 42%), var(--node-color);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.42);
color: #fff4df;
font-size: 12px;
text-align: center;
user-select: none;
}
.mengsan-node-shuying.selectable {
cursor: pointer;
animation: mengsan-node-pulse-shuying 1.6s infinite;
}
.mengsan-node-shuying.locked {
opacity: 0.45;
filter: grayscale(0.65);
}
.mengsan-node-shuying.completed {
opacity: 0.72;
box-shadow: 0 0 0 3px rgba(244, 211, 139, 0.3);
}
@keyframes mengsan-node-pulse-shuying {
0%, 100% { box-shadow: 0 0 0 0 rgba(242, 207, 132, 0.18), 0 5px 15px rgba(0, 0, 0, 0.42); }
50% { box-shadow: 0 0 0 8px rgba(242, 207, 132, 0), 0 5px 18px rgba(0, 0, 0, 0.55); }
}
@media (max-width: 600px) {
.mengsan-overlay-shuying { padding: 7px; }
.mengsan-panel-shuying { padding: 14px; }
.mengsan-title-shuying { font-size: 24px; }
.mengsan-map-panel-shuying { padding: 8px; }
.mengsan-map-shuying { min-height: 0; }
.mengsan-node-shuying { width: 54px; height: 36px; font-size: 11px; }
}
+143
View File
@@ -0,0 +1,143 @@
<#
Batch-crop Godot AtlasTexture .tres files into PNGs from their referenced atlas images.
Requires a FULL RECOVERY output where atlas sources are PNG/WebP. This script does not
unpack PCK files or decode .ctex; it only reads .tres/.tpsheet metadata and crops images.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ProjectRoot,
[Parameter(Mandatory = $true)]
[string]$OutputDirectory,
[string]$SpriteDirectory = 'images/atlases/compressed.sprites/card_template',
[switch]$Overwrite
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
$root = [System.IO.Path]::GetFullPath($ProjectRoot).TrimEnd('\')
$outRoot = [System.IO.Path]::GetFullPath($OutputDirectory).TrimEnd('\')
$relativeSpriteDir = $SpriteDirectory.TrimStart('\', '/').Replace('/', '\')
$sourceDir = [System.IO.Path]::GetFullPath((Join-Path $root $relativeSpriteDir))
if (-not (Test-Path -LiteralPath $root -PathType Container)) {
throw "ProjectRoot not found: $root"
}
if (-not (Test-Path -LiteralPath $sourceDir -PathType Container)) {
throw "SpriteDirectory not found: $sourceDir"
}
if ($outRoot.Equals($root, [System.StringComparison]::OrdinalIgnoreCase) -or
$outRoot.StartsWith($root + '\', [System.StringComparison]::OrdinalIgnoreCase)) {
throw 'OutputDirectory must be outside ProjectRoot so recovered source files stay untouched.'
}
$invariant = [System.Globalization.CultureInfo]::InvariantCulture
$files = @(Get-ChildItem -LiteralPath $sourceDir -Filter '*.tres' -File -Recurse)
$written = 0
$skipped = 0
$errors = [System.Collections.Generic.List[string]]::new()
foreach ($tres in $files) {
$sourceImage = $null
$crop = $null
try {
$text = [System.IO.File]::ReadAllText($tres.FullName)
if ($text -notmatch 'type="AtlasTexture"') {
$skipped++
continue
}
$atlasIdMatch = [regex]::Match($text, '(?m)^\s*atlas\s*=\s*ExtResource\("([^"]+)"\)')
$regionMatch = [regex]::Match($text, '(?m)^\s*region\s*=\s*Rect2i?\(\s*(-?[0-9.]+)\s*,\s*(-?[0-9.]+)\s*,\s*(-?[0-9.]+)\s*,\s*(-?[0-9.]+)\s*\)')
if (-not $atlasIdMatch.Success -or -not $regionMatch.Success) {
$skipped++
$errors.Add("Missing atlas/region fields: $($tres.FullName)")
continue
}
$atlasPath = $null
foreach ($blockMatch in [regex]::Matches($text, '(?m)^\s*\[ext_resource[^\]]*\]')) {
$block = $blockMatch.Value
$idMatch = [regex]::Match($block, '\bid="([^"]+)"')
$pathMatch = [regex]::Match($block, '\bpath="([^"]+)"')
if ($idMatch.Success -and $pathMatch.Success -and
$idMatch.Groups[1].Value -eq $atlasIdMatch.Groups[1].Value) {
$atlasPath = $pathMatch.Groups[1].Value
break
}
}
if (-not $atlasPath) {
$skipped++
$errors.Add("Could not resolve atlas ExtResource: $($tres.FullName)")
continue
}
if ($atlasPath.StartsWith('res://', [System.StringComparison]::OrdinalIgnoreCase)) {
$atlasRelative = $atlasPath.Substring(6).Replace('/', '\')
$atlasFile = Join-Path $root $atlasRelative
} else {
$atlasFile = Join-Path $tres.DirectoryName $atlasPath.Replace('/', '\')
}
if (-not (Test-Path -LiteralPath $atlasFile -PathType Leaf)) {
$skipped++
$errors.Add("Atlas image missing (Full Recovery should restore it as PNG): $atlasFile ; referenced by $($tres.FullName)")
continue
}
$values = @(
[double]::Parse($regionMatch.Groups[1].Value, $invariant),
[double]::Parse($regionMatch.Groups[2].Value, $invariant),
[double]::Parse($regionMatch.Groups[3].Value, $invariant),
[double]::Parse($regionMatch.Groups[4].Value, $invariant)
)
$rounded = @($values | ForEach-Object { [int][Math]::Round($_) })
for ($i = 0; $i -lt 4; $i++) {
if ([Math]::Abs($values[$i] - $rounded[$i]) -gt 0.001) {
throw "Non-integer pixel region in $($tres.FullName)"
}
}
$x = $rounded[0]; $y = $rounded[1]; $width = $rounded[2]; $height = $rounded[3]
if ($x -lt 0 -or $y -lt 0 -or $width -le 0 -or $height -le 0) {
throw "Invalid crop region Rect2($x, $y, $width, $height) in $($tres.FullName)"
}
$sourceImage = [System.Drawing.Bitmap]::FromFile($atlasFile)
if (($x + $width) -gt $sourceImage.Width -or ($y + $height) -gt $sourceImage.Height) {
throw "Crop exceeds atlas bounds ($($sourceImage.Width)x$($sourceImage.Height)): $($tres.FullName)"
}
$rect = [System.Drawing.Rectangle]::new($x, $y, $width, $height)
$crop = $sourceImage.Clone($rect, $sourceImage.PixelFormat)
$relativeTres = $tres.FullName.Substring($root.Length).TrimStart('\')
$relativeOutput = [System.IO.Path]::ChangeExtension($relativeTres, '.png')
$target = Join-Path $outRoot $relativeOutput
$targetDir = Split-Path -Parent $target
New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
if ((Test-Path -LiteralPath $target) -and -not $Overwrite) {
$skipped++
continue
}
if (Test-Path -LiteralPath $target) {
Remove-Item -LiteralPath $target -Force
}
$crop.Save($target, [System.Drawing.Imaging.ImageFormat]::Png)
$written++
}
catch {
$skipped++
$errors.Add("$($tres.FullName): $($_.Exception.Message)")
}
finally {
if ($null -ne $crop) { $crop.Dispose() }
if ($null -ne $sourceImage) { $sourceImage.Dispose() }
}
}
Write-Output "TRES scanned: $($files.Count)"
Write-Output "PNG written: $written"
Write-Output "Skipped: $skipped"
foreach ($message in $errors) { Write-Warning $message }
+176
View File
@@ -0,0 +1,176 @@
import { lib, get, ui } from "../../../../noname.js";
import { AFFIX_INFO } from "../cards/affixes.js";
const suits = { spade: "♠ 黑桃", heart: "♥ 红桃", club: "♣ 梅花", diamond: "♦ 方块" };
const types = { basic: "基本牌", trick: "锦囊牌", delay: "延时锦囊", equip: "装备牌" };
const affixes = Object.fromEntries(Object.entries(AFFIX_INFO).map(([key, info]) => [key, `${info.name}:${info.description}`]));
const text = value => {
const template = document.createElement("template");
// Translation markup is parsed inertly; only plain text is inserted into the UI.
template.innerHTML = String(value ?? "").replace(/<br\s*\/?\s*>/gi, "\n");
return template.content.textContent.trim();
};
const translate = value => text(lib.translate[value] || get.translation(value) || value);
export function describeLibraryCard(card) {
const info = lib.card[card.name];
const nature = typeof card.nature === "string" ? card.nature.split("|").filter(Boolean).map(translate).join("、") : "";
return {
name: translate(card.name), suit: suits[card.suit] || "无花色",
number: ({ 1: "A", 11: "J", 12: "Q", 13: "K" })[card.number] || String(card.number ?? "—"),
nature: nature || "无属性", type: types[info?.type] || "未知类别",
red: card.suit === "heart" || card.suit === "diamond",
description: text(lib.translate[`${card.name}_info`] || "暂无卡牌介绍。"),
affixes: (Array.isArray(card.affixes) ? card.affixes : []).filter(key => key !== "annihilate").map(key => affixes[key] || `词缀:${translate(key)}`),
upgrade: Number.isFinite(card.upgrade) ? card.upgrade : 0,
available: Boolean(info),
};
}
function element(tag, className, value, parent) {
const node = document.createElement(tag);
node.className = className;
if (value != null) node.textContent = value;
parent?.appendChild(node);
return node;
}
function button(label, parent, action, className = "ms-deck-button") {
const node = element("button", className, label, parent);
node.type = "button";
node.addEventListener("click", action);
return node;
}
// Read-only DOM previews, never game.createCard or Card.init: no IDs, triggers or pile writes.
function preview(card, details, parent) {
const face = element("div", "ms-deck-face", null, parent);
element("span", `ms-deck-corner${details.red ? " ms-deck-red" : ""}`, `${details.suit} ${details.number}`, face);
const art = element("div", "ms-deck-art", null, face);
element("span", "ms-deck-glyph", details.name, art);
const imageName = lib.card[card.name]?.cardimage || card.name;
// Only mode-standard local art paths; unknown or missing art keeps the text fallback.
if (/^[a-zA-Z0-9_]+$/.test(imageName)) {
const image = element("img", "ms-deck-image", null, art);
image.alt = "";
image.loading = "lazy";
image.addEventListener("error", () => image.remove(), { once: true });
image.src = `${lib.assetURL || ""}image/card/${imageName}.png`;
}
element("strong", "ms-deck-name", details.name, face);
element("span", "ms-deck-meta", `${details.type} · ${details.nature}`, face);
if (details.upgrade || details.affixes.length) {
element("span", "ms-deck-tags", [details.upgrade ? `强化 +${details.upgrade}` : "", ...details.affixes.map(value => value.split(":")[0])].filter(Boolean).join(" · "), face);
}
return face;
}
export function openCardLibrary(run, options = {}) {
const existing = document.querySelector("dialog.mengsan-deck-dialog-shuying[open]");
if (existing) { existing.focus(); return () => {}; }
const previousFocus = document.activeElement;
const dialog = element("dialog", "mengsan-deck-dialog-shuying", null);
dialog.setAttribute("aria-label", options.title || "卡牌库");
const header = element("header", "ms-deck-header", null, dialog);
const title = element("div", "ms-deck-title-group", null, header);
element("span", "ms-deck-eyebrow", options.eyebrow || "梦三 · 行囊", title);
element("h2", "ms-deck-title", options.title || "卡牌库", title);
let closed = false;
const close = () => {
if (closed) return;
closed = true;
if (dialog.open) dialog.close();
dialog.remove();
if (previousFocus?.isConnected) previousFocus.focus();
};
button("关闭", header, close);
const summary = element("p", "ms-deck-summary", null, dialog);
const body = element("div", "ms-deck-body", null, dialog);
const footer = element("p", "ms-deck-footer", "点击卡牌查看完整介绍 · 仅供查看,不改变牌组或抽牌顺序", dialog);
const current = Array.isArray(run?.player?.deck) ? run.player.deck : [];
let detail = false, selectedButton = null, scrollTop = 0;
const list = element("div", "ms-deck-grid", null, body);
const detailPanel = element("section", "ms-deck-detail", null, body);
detailPanel.hidden = true;
function back() {
detail = false; detailPanel.hidden = true; list.hidden = false;
detailPanel.replaceChildren(); body.scrollTop = scrollTop;
selectedButton?.focus({ preventScroll: true });
}
function showDetail(card, details, owner) {
selectedButton = owner; scrollTop = body.scrollTop;
detail = true; list.hidden = true; detailPanel.hidden = false;
detailPanel.replaceChildren();
const backButton = button("返回牌库", detailPanel, back);
const content = element("div", "ms-deck-detail-content", null, detailPanel);
preview(card, details, content);
const copy = element("div", "ms-deck-detail-copy", null, content);
element("h3", "", details.name, copy);
element("p", "", `${details.suit} ${details.number} · ${details.type} · ${details.nature}`, copy);
element("h4", "", "卡牌介绍", copy);
element("p", "ms-deck-rules", details.description, copy);
if (!details.available) element("p", "ms-deck-warning", "该卡牌定义未加载;保留存档记录,不删除此牌。", copy);
if (details.upgrade) element("p", "", `强化等级:${details.upgrade}(实际效果以玩法规则为准)`, copy);
for (const affix of details.affixes) element("p", "ms-deck-rules", affix, copy);
body.scrollTop = 0; backButton.focus();
}
function render() {
detail = false; list.hidden = false; detailPanel.hidden = true;
detailPanel.replaceChildren(); list.replaceChildren(); body.scrollTop = 0;
const sections = options.sections ? options.sections() : [{ title: "", cards: current }];
summary.textContent = options.sections ? "剩余牌堆按从左到右、从上到下的顺序摸取;第 1 张为下一张。" : `本次征程实际携带 · 共 ${current.length} 张 · 同名不同花色、点数分别展示`;
for (const section of sections) {
const cards = section.cards;
if (section.title) element("h3", "ms-deck-section", `${section.title} · ${cards.length} 张`, list);
if (!cards.length) element("p", "ms-deck-empty", section.ordered ? "剩余牌堆为空;下一次摸牌需按规则洗切弃牌堆,洗切后的顺序尚未确定。" : "此处暂无卡牌。", list);
cards.forEach((card, index) => {
const details = describeLibraryCard(card);
const tile = button("", list, () => showDetail(card, details, tile), "ms-deck-card");
tile.setAttribute("aria-label", `${section.ordered ? `第 ${index + 1} 张,` : ""}${details.name},${details.suit}${details.number},${details.nature},查看详情`);
if (section.ordered) element("span", "ms-deck-order", index === 0 ? "1 · 下一张" : `${index + 1}`, tile);
preview(card, details, tile);
element("span", "ms-deck-excerpt", details.description, tile);
});
}
}
dialog.addEventListener("cancel", event => { event.preventDefault(); if (detail) back(); else close(); });
dialog.addEventListener("close", close);
// Prevent the map's Escape/Tab handler from acting behind this modal.
dialog.addEventListener("keydown", event => event.stopPropagation());
render();
document.body.appendChild(dialog);
try { dialog.showModal(); } catch (error) { close(); throw error; }
header.querySelector("button").focus();
close.refresh = () => {
if (closed) return;
// Rebuild from live arrays after a pile mutation, including while viewing details.
const wasDetail = detail, offset = body.scrollTop;
render(); body.scrollTop = offset;
if (wasDetail) header.querySelector("button").focus();
};
return close;
}
// The battle view exposes only this player's own piles, including consumed cards.
export function mountBattlePiles(session, battle) {
let closeDialog = null, disposed = false;
const control = button("牌堆", ui.window, () => {
if (disposed || !session.active || battle.resolving) return;
closeDialog?.();
closeDialog = openCardLibrary(null, {
title: "战斗牌堆", eyebrow: "梦三 · 个人牌堆",
sections: () => [
{ title: "剩余牌堆", cards: battle.drawPile, ordered: true },
{ title: "弃牌堆", cards: battle.discardPile, ordered: false },
{ title: "消耗牌堆", cards: battle.exhaustPile, ordered: false },
],
});
}, "mengsan-battle-piles-button-shuying");
control.setAttribute("aria-haspopup", "dialog");
const dispose = () => {
if (disposed) return;
disposed = true; closeDialog?.(); closeDialog = null; control.remove();
};
session.ownResource(control, dispose);
return { dispose, refresh() { if (!disposed) closeDialog?.refresh?.(); } };
}
+193
View File
@@ -0,0 +1,193 @@
import { mountMenu } from "./navigation.js";
import { ui, get } from "../../../../noname.js";
import { isDialogueLineVisible, applyDialogueChoice, applySkippedDialogueChoices } from "../progression/dialogue-choice.js";
const TYPE_NAMES = {
character: "角色",
narrator: "旁白",
sound: "音效",
choice: "选择发言",
};
const resolveCharacter = (character, run) => character == "$player" ? run?.player?.character : character;
const resolveSpeaker = (line, character) => {
if (line.speaker == "$player") return character ? get.translation(character) : "你";
if (line.speaker) return line.speaker;
if (line.type == "character" && character) return get.translation(character);
return TYPE_NAMES[line.type] || "旁白";
};
export const splitDialogueText = text => Array.from(String(text || ""));
export const playDialogue = (lines, options = {}) => new Promise(resolve => {
if (!Array.isArray(lines) || !lines.length) {
resolve();
return;
}
const overlay = ui.create.div(".mengsan-dialogue-overlay-shuying", ui.window);
const stage = ui.create.div(".mengsan-dialogue-stage-shuying", overlay);
ui.create.div(".mengsan-dialogue-chapter-shuying", options.title || "剧情", stage);
const textBox = ui.create.div(".mengsan-dialogue-box-shuying", stage);
const portraitFrame = ui.create.div(
".mengsan-dialogue-portrait-frame-shuying", textBox);
const speaker = ui.create.div(".mengsan-dialogue-speaker-shuying", textBox);
const text = ui.create.div(".mengsan-dialogue-text-shuying", textBox);
const progress = ui.create.div(".mengsan-dialogue-progress-shuying", textBox);
const indicator = ui.create.div(".mengsan-dialogue-indicator-shuying", "◆", textBox);
const choices = ui.create.div(".mengsan-dialogue-choices-shuying", stage);
const skipButton = document.createElement("button");
skipButton.type = "button";
skipButton.className = "mengsan-dialogue-skip-shuying";
skipButton.textContent = "跳过对话";
skipButton.setAttribute("aria-label", "跳过对话,未选择的发言使用默认选项");
stage.appendChild(skipButton);
let lineIndex = -1;
let timer = null;
let typing = false;
let paused = false;
let currentSpeed = 28;
let characters = [];
let characterIndex = 0;
let currentLine = null;
let awaitingChoice = false;
const portrait = ui.create.div(".mengsan-dialogue-portrait-shuying", portraitFrame);
const reduceMotion = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;
const stopTimer = () => {
if (timer != null) clearTimeout(timer);
timer = null;
};
const finishTyping = () => {
stopTimer();
text.textContent = characters.join("");
characterIndex = characters.length;
typing = false;
if (currentLine?.type === "choice" && awaitingChoice) showChoices(currentLine);
else indicator.classList.add("visible");
};
function showChoices(line) {
choices.replaceChildren();
for (const item of line.choices) {
const button = document.createElement("button");
button.type = "button";
button.className = "mengsan-dialogue-choice-shuying";
button.textContent = item.text;
button.addEventListener("click", event => {
event.stopPropagation();
if (!awaitingChoice) return;
text.textContent = applyDialogueChoice(options.run, line, item.id);
awaitingChoice = false;
choices.replaceChildren();
speaker.textContent = get.translation(options.run.player.character);
stage.dataset.lineType = "character";
const character = options.run.player.character;
portraitFrame.classList.add("visible");
portrait.setBackground(character, "character");
indicator.classList.add("visible");
textBox.focus();
});
choices.appendChild(button);
}
choices.querySelector("button")?.focus();
}
const scheduleCharacter = speed => {
if (!typing || paused) return;
text.textContent += characters[characterIndex++];
if (characterIndex >= characters.length) {
finishTyping();
return;
}
timer = setTimeout(() => scheduleCharacter(speed), speed);
};
const close = () => {
stopTimer();
skipButton.removeEventListener("click", handleSkip);
textBox.removeEventListener("click", handleClick);
textBox.removeEventListener("keydown", handleKeydown);
choices.replaceChildren();
overlay.remove();
resolve();
};
const showNextLine = () => {
do { lineIndex++; } while (lineIndex < lines.length && !isDialogueLineVisible(lines[lineIndex], options.run));
if (lineIndex >= lines.length) {
close();
return;
}
const line = lines[lineIndex];
currentLine = line;
awaitingChoice = line.type === "choice";
choices.replaceChildren();
const lineType = TYPE_NAMES[line.type] ? line.type : "narrator";
const character = resolveCharacter(line.character, options.run);
stage.dataset.lineType = lineType;
speaker.textContent = resolveSpeaker(line, character);
progress.textContent = `${lineIndex + 1} / ${lines.length}`;
indicator.classList.remove("visible");
if (lineType == "character" && character) {
portraitFrame.classList.add("visible");
portrait.setBackground(character, "character");
portrait.setAttribute("aria-label", `${speaker.textContent}立绘`);
}
else {
portraitFrame.classList.remove("visible");
portrait.removeAttribute("aria-label");
}
characters = splitDialogueText(line.text);
characterIndex = 0;
text.textContent = "";
typing = characters.length > 0;
const speed = Number.isFinite(line.speed) ? Math.max(0, line.speed) : 28;
currentSpeed = speed;
if (!typing || reduceMotion || speed == 0) finishTyping();
else scheduleCharacter(speed);
};
function handleClick(event) {
event.preventDefault();
event.stopPropagation();
if (paused) return;
if (typing) finishTyping();
else if (awaitingChoice) return;
else showNextLine();
}
function handleKeydown(event) {
if (event.key == "Enter" || event.key == " ") handleClick(event);
}
function handleSkip(event) {
event.preventDefault();
event.stopPropagation();
if (paused) return;
applySkippedDialogueChoices(lines, lineIndex + (awaitingChoice ? 0 : 1), options.run);
close();
}
textBox.setAttribute("role", "button");
textBox.setAttribute("tabindex", "0");
textBox.setAttribute("aria-label", "剧情文本:点击补全文字或继续");
textBox.addEventListener("click", handleClick);
textBox.addEventListener("keydown", handleKeydown);
skipButton.addEventListener("click", handleSkip);
mountMenu(overlay, {
onOpen() { paused = true; stopTimer(); },
onClose() { paused = false; if (typing) scheduleCharacter(currentSpeed); },
});
const help = ui.create.div(".mengsan-dialogue-help-shuying", stage);
help.textContent = "点击补全文字 · 再次点击继续 · Enter / 空格";
showNextLine();
textBox.focus();
});
+13
View File
@@ -0,0 +1,13 @@
export function mountEnergy(player, session, document) {
const badge = document.createElement("div");
badge.className = "mengsan-energy-shuying";
const refresh = () => {
const current = player.storage.mengsanEnergy_shuying;
const maximum = player.storage.mengsanMaxEnergy_shuying;
badge.textContent = `费用 ${current}/${maximum}`;
};
player.appendChild(badge);
session.ownResource(badge, () => badge.remove());
refresh();
return refresh;
}
+63
View File
@@ -0,0 +1,63 @@
import { ui } from "../../../../noname.js";
import { mountMenu } from "./navigation.js";
export const chooseButtons = (title, choices, description = "", options = {}) => new Promise(resolve => {
const previousFocus = document.activeElement;
const overlay = ui.create.div(".mengsan-overlay-shuying.mengsan-flow-overlay-shuying", ui.window);
overlay.setAttribute("role", "dialog");
overlay.setAttribute("aria-modal", "true");
overlay.setAttribute("aria-label", title);
const panel = ui.create.div(".mengsan-panel-shuying.mengsan-flow-panel-shuying", overlay);
const eyebrow = document.createElement("p");
eyebrow.className = "mengsan-flow-eyebrow-shuying";
eyebrow.textContent = options.eyebrow || "梦三 · 征程";
panel.appendChild(eyebrow);
const heading = ui.create.div(".mengsan-title-shuying", panel);
heading.textContent = title;
heading.setAttribute("role", "heading");
heading.setAttribute("aria-level", "1");
if (description) {
const summary = ui.create.div(".mengsan-description-shuying", panel);
summary.textContent = description;
}
const buttons = ui.create.div(".mengsan-choice-list-shuying", panel);
const finish = id => {
if (overlay.dataset.resolved) return;
overlay.dataset.resolved = "true";
overlay.remove();
if (previousFocus?.isConnected) previousFocus.focus();
resolve(id);
};
choices.forEach(choice => {
const button = document.createElement("button");
button.type = "button";
button.className = "mengsan-choice-shuying";
button.dataset.choice = choice.id;
if (choice.danger) button.classList.add("danger");
const name = document.createElement("span");
name.className = "mengsan-choice-name-shuying";
name.textContent = choice.name;
button.appendChild(name);
if (choice.description) {
const detail = document.createElement("span");
detail.className = "mengsan-choice-description-shuying";
detail.textContent = choice.description;
button.appendChild(detail);
}
button.disabled = Boolean(choice.disabled);
button.addEventListener("click", () => finish(choice.id));
buttons.appendChild(button);
});
mountMenu(overlay);
overlay.addEventListener("keydown", event => {
if (event.key === "Escape" && options.back) {
event.preventDefault(); finish(options.back); return;
}
if (event.key !== "Tab") return;
const focusable = [...overlay.querySelectorAll("button:not(:disabled)")];
const first = focusable[0], last = focusable[focusable.length - 1];
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
});
buttons.querySelector("button:not(:disabled)")?.focus();
});
+90
View File
@@ -0,0 +1,90 @@
import { AFFIX_INFO } from "../cards/affixes.js";
import { describeLibraryCard } from "./card-library.js";
const node = (tag, className, label, parent) => {
const element = document.createElement(tag);
element.className = className;
if (label != null) element.textContent = label;
parent?.appendChild(element);
return element;
};
const button = (label, parent, action) => {
const element = node("button", "ms-deck-button", label, parent);
element.type = "button";
element.addEventListener("click", action);
return element;
};
// Keep the command battle-scoped; further GM actions can be added as panels here.
export function mountGMManager(session, owner, piles, battle, resources, game) {
let dialog = null, selected = null, previousFocus = null, disposed = false;
const available = () => !disposed && session.active && !battle.resolving;
const close = () => {
if (!dialog) return;
const current = dialog;
dialog = null;
if (current.open) current.close();
current.remove();
if (previousFocus?.isConnected) previousFocus.focus();
previousFocus = null;
};
const render = () => {
if (!dialog) return;
const list = dialog.querySelector(".ms-gm-hand");
const editor = dialog.querySelector(".ms-gm-editor");
list.replaceChildren(); editor.replaceChildren();
const hand = owner.getCards("h").filter(card => card.storage?.mengsanCard_shuying);
if (!hand.includes(selected)) selected = null;
if (!hand.length) node("p", "ms-deck-empty", "当前没有可编辑的梦三手牌。", list);
for (const [index, card] of hand.entries()) {
const data = card.storage.mengsanCard_shuying;
const details = describeLibraryCard({ ...data, name: card.name, suit: card.suit, number: card.number });
const label = `${index + 1}. ${details.name} ${details.suit}${details.number}${details.affixes.length ? ` · ${details.affixes.map(value => value.split(":")[0]).join("、")}` : ""}`;
const item = button(label, list, () => { selected = card; render(); });
item.classList.add("ms-gm-card");
item.setAttribute("aria-pressed", String(selected === card));
}
if (!selected) { node("p", "ms-deck-empty", "选择一张手牌,然后添加词缀。", editor); return; }
node("h3", "", `编辑:${describeLibraryCard(selected.storage.mengsanCard_shuying).name}`, editor);
const choices = node("div", "ms-gm-affixes", null, editor);
for (const [key, info] of Object.entries(AFFIX_INFO)) {
const applied = selected.storage.mengsanCard_shuying.affixes.includes(key);
const item = button(`${info.name}${applied ? " · 已有" : ""}`, choices, () => {
if (!available() || !owner.getCards("h").includes(selected)) { render(); return; }
piles.addAffix(selected, key);
render();
});
item.disabled = applied;
item.title = info.description;
}
};
const open = () => {
if (!available()) return false;
if (dialog?.open) { render(); dialog.focus(); return true; }
previousFocus = document.activeElement;
dialog = node("dialog", "mengsan-deck-dialog-shuying mengsan-gm-dialog-shuying", null);
dialog.setAttribute("aria-label", "梦三 GM 管理器");
dialog.tabIndex = -1;
const header = node("header", "ms-deck-header", null, dialog);
node("h2", "ms-deck-title", "GM 管理器", header);
button("关闭", header, close);
node("p", "ms-deck-summary", "手牌词缀 · 仅本场战斗生效,不改永久牌组或存档。", dialog);
button("刷新手牌", dialog, render);
node("div", "ms-gm-hand", null, dialog);
node("section", "ms-gm-editor", null, dialog);
const created = dialog;
dialog.addEventListener("close", () => { if (dialog === created) close(); });
dialog.addEventListener("keydown", event => event.stopPropagation());
document.body.appendChild(dialog);
try { dialog.showModal(); } catch (error) { close(); throw error; }
render();
dialog.querySelector(".ms-deck-header button").focus();
return true;
};
resources.field(globalThis, "mengsanGM_shuying", open);
resources.field(game, "mengsanGM_shuying", open);
const handle = { dispose: close };
session.ownResource(handle, () => { disposed = true; close(); });
return handle;
}
+154
View File
@@ -0,0 +1,154 @@
// 只呈现已经选定的预测技能;不从手牌或原生技能猜测意图。
import { attackHitCount, previewAttackDamage } from "../battle/intent-damage.js";
import { isDeathBlowIntent } from "../battle/death-blow.js";
import { isStunIntent } from "../battle/stun-intent.js";
export function attackIconForDamage(damage) {
if (!Number.isInteger(damage) || damage < 0) {
throw new RangeError("预测伤害必须是非负整数");
}
if (damage < 5) return 1;
if (damage < 10) return 2;
if (damage < 20) return 3;
if (damage < 40) return 4;
return 5;
}
export function mountEnemyIntent(player, session, assetBase, document,
getTarget = () => null) {
const badge = document.createElement("div");
badge.className = "mengsan-intent-shuying";
badge.hidden = true;
badge.setAttribute("aria-live", "polite");
badge.setAttribute("aria-atomic", "true");
const damageLine = document.createElement("span");
damageLine.className = "mengsan-intent-damage-shuying";
const amount = document.createElement("span");
amount.className = "mengsan-intent-amount-shuying";
const icon = document.createElement("img");
icon.className = "mengsan-intent-icon-shuying";
icon.alt = "";
icon.decoding = "async";
damageLine.append(icon, amount);
const debuffLine = document.createElement("span");
debuffLine.className = "mengsan-intent-debuff-shuying";
const debuffIcon = document.createElement("img");
debuffIcon.className = "mengsan-intent-icon-shuying";
debuffIcon.alt = "";
debuffIcon.decoding = "async";
debuffIcon.src = `${assetBase}/assets/intent/Intent_debuff.png`;
const debuffAmount = document.createElement("span");
debuffLine.append(debuffIcon, debuffAmount);
const blockLine = document.createElement("span");
blockLine.className = "mengsan-intent-block-shuying";
const blockIcon = document.createElement("img");
blockIcon.className = "mengsan-intent-icon-shuying";
blockIcon.alt = "";
blockIcon.decoding = "async";
blockIcon.src = `${assetBase}/assets/intent/Intent_defend.png`;
const blockAmount = document.createElement("span");
blockLine.append(blockIcon, blockAmount);
const buffLine = document.createElement("span");
buffLine.className = "mengsan-intent-buff-shuying";
const buffIcon = document.createElement("img");
buffIcon.className = "mengsan-intent-icon-shuying";
buffIcon.alt = "";
buffIcon.decoding = "async";
buffIcon.src = `${assetBase}/assets/intent/Intent_buff.png`;
const buffAmount = document.createElement("span");
buffLine.append(buffIcon, buffAmount);
badge.append(damageLine, debuffLine, blockLine, buffLine);
player.appendChild(badge);
let currentIntent = null;
let timer;
session.ownResource(badge, () => {
clearInterval(timer);
badge.remove();
});
const refresh = () => {
const intent = currentIntent;
if (!intent) {
badge.hidden = true;
return;
}
if (isStunIntent(intent)) {
damageLine.hidden = false;
debuffLine.hidden = true;
blockLine.hidden = true;
buffLine.hidden = true;
amount.textContent = "";
const src = `${assetBase}/assets/intent/Intent_stun.png`;
if (icon.getAttribute("src") !== src) icon.src = src;
if (badge.getAttribute("aria-label") !== "Stunned") {
badge.setAttribute("aria-label", "Stunned");
}
badge.hidden = false;
return;
}
const hasDamage = intent.damage != null;
const deathBlow = isDeathBlowIntent(intent);
if (deathBlow && !hasDamage) {
throw new TypeError("濒死一击必须有伤害数值");
}
damageLine.hidden = !hasDamage;
const hasDebuff = typeof intent.debuff === "string" &&
Number.isInteger(intent.stacks) && intent.stacks > 0;
debuffLine.hidden = !hasDebuff;
if (hasDebuff) {
const debuffText = `×${intent.stacks}`;
if (debuffAmount.textContent !== debuffText) {
debuffAmount.textContent = debuffText;
}
}
const hasBlock = Number.isInteger(intent.block) && intent.block > 0;
const hasStrength = Number.isInteger(intent.strength) && intent.strength > 0;
blockLine.hidden = !hasBlock;
buffLine.hidden = !hasStrength;
if (hasBlock) blockAmount.textContent = String(intent.block);
if (hasStrength) {
buffAmount.textContent = `+${intent.strength}`;
}
const effects = [];
if (hasDamage) {
const hits = attackHitCount(intent);
if (deathBlow && hits !== 1) {
throw new RangeError("濒死一击只能造成一次伤害");
}
const damage = previewAttackDamage(intent, player, getTarget());
const tier = deathBlow ? null :
attackIconForDamage(damage * hits);
const damageText = hits > 1 ? `${damage}×${hits}` :
String(damage);
if (amount.textContent !== damageText) {
amount.textContent = damageText;
}
const src = deathBlow ?
`${assetBase}/assets/intent/Intent_death_blow.png` :
`${assetBase}/assets/intent/Intent_attack_${tier}.png`;
if (icon.getAttribute("src") !== src) icon.src = src;
effects.push(`${deathBlow ? "Death Blow" : "Attack"}: ${damage} damage${hits > 1 ? ` × ${hits} hits` : ""}`);
}
if (hasDebuff) {
const label = intent.debuff === "脆弱" ? "Frail" :
intent.debuff === "易伤" ? "Vulnerable" : "Debuff";
effects.push(`${label} ×${intent.stacks}`);
}
if (hasBlock) effects.push(`Block ${intent.block}`);
if (hasStrength) effects.push(`Strength +${intent.strength}`);
if (!effects.length) {
damageLine.hidden = false;
amount.textContent = "";
const src = `${assetBase}/assets/intent/Intent_unknown.png`;
if (icon.getAttribute("src") !== src) icon.src = src;
effects.push("Unknown");
}
const label = effects.join(", ");
if (badge.getAttribute("aria-label") !== label) badge.setAttribute("aria-label", label);
badge.hidden = false;
};
timer = setInterval(refresh, 100);
return intent => {
currentIntent = intent;
refresh();
};
}
+1
View File
@@ -0,0 +1 @@
export { showMap as default, showMap } from "./renderer.js";
+472
View File
@@ -0,0 +1,472 @@
import { openCardLibrary } from "../card-library.js";
import { askMenu, openModeSelection } from "../navigation.js";
import { ui, get } from "../../../../../noname.js";
import config from "../../config.js";
import { getSelectableNodes } from "../../progression/state.js";
// Original vector pictograms; no external image/font requests.
const iconPaths = {
battle: "M8 5l19 22M24 4l4 4L9 27M5 23l5 5M22 7l5 5M6 4l5 2-3 4z",
elite: "M16 3l10 5v9c0 6-10 12-10 12S6 23 6 17V8zM10 13l6 4 6-4M16 17v7M11 5l5-3 5 3",
event: "M10 10c0-9 15-8 15 0 0 5-9 5-9 10M16 25v1",
story: "M8 5h18v20H10c-5 0-5-6 0-6h16M8 5c-5 0-5 6 0 6h3V5M12 10h10M12 14h8",
chest: "M4 13h24v15H4zM2 8h28v6H2zM16 8v20" +
"M9 8c-4-3-1-7 3-5l4 5M23 8c4-3 1-7-3-5l-4 5",
rest: "M3 26L16 5l13 21zM10 26l6-11 6 11M16 5V2M7 28h19",
shop: "M4 12l3-7h18l3 7M4 12v4h24v-4M7 16v12h18V16M12 28v-8h8v8M3 28h26M11 6v6M21 6v6",
boss: "M6 28V5M6 6c8-8 12 6 22-1v16c-10 7-14-7-22 1M11 10l11 7M22 10l-11 7M3 28h9",
};
const controlIconPaths = {
menu: "M5 8h22M5 16h22M5 24h22",
map: "M4 7l7-3 10 4 7-3v20l-7 3-10-4-7 3zM11 4v20M21 8v20",
bag: "M9 10V8a7 7 0 0114 0v2M6 10h20l2 18H4zM12 16v3M20 16v3",
book: "M5 5h9a5 5 0 015 5v17a5 5 0 00-5-5H5zM27 5h-9a5 5 0 00-5 5v17a5 5 0 015-5h9z",
record: "M8 4h16v24H8zM12 10h8M12 16h8M12 22h5",
settings: "M16 11a5 5 0 100 10 5 5 0 000-10zM16 3v4M16 25v4M3 16h4M25 16h4M7 7l3 3M22 22l3 3M25 7l-3 3M10 22l-3 3",
exit: "M13 5H6v22h7M20 10l6 6-6 6M26 16H11",
back: "M20 7l-9 9 9 9M11 16h16",
close: "M8 8l16 16M24 8L8 24",
};
const makeIcon = type => {
const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
icon.setAttribute("viewBox", "0 0 32 32");
icon.setAttribute("aria-hidden", "true");
icon.classList.add("mengsan-ink-icon-shuying");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", iconPaths[type] || iconPaths.event);
icon.appendChild(path);
return icon;
};
const makeControlIcon = type => {
const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
icon.setAttribute("viewBox", "0 0 32 32");
icon.setAttribute("aria-hidden", "true");
icon.classList.add("mengsan-control-icon-shuying");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", controlIconPaths[type]);
icon.appendChild(path);
return icon;
};
const createText = (className, text, parent) => {
const node = document.createElement("div");
node.className = className;
node.textContent = text;
parent.appendChild(node);
return node;
};
const nodeColor = {
battle: "#9d4937",
elite: "#7e3f79",
event: "#477aa6",
story: "#8c6a34",
chest: "#a27b35",
rest: "#3f8560",
shop: "#a27b35",
boss: "#a62727",
};
const createMapOverlay = title => {
const overlay = ui.create.div(".mengsan-overlay-shuying.mengsan-map-overlay-shuying", ui.window);
const panel = ui.create.div(".mengsan-panel-shuying.mengsan-map-panel-shuying", overlay);
const header = ui.create.div(".mengsan-map-header-shuying", panel);
const titleGroup = ui.create.div(".mengsan-map-title-group-shuying", header);
createText("mengsan-map-eyebrow-shuying", "MENGSAN EXPEDITION", titleGroup);
const heading = ui.create.div(".mengsan-title-shuying", titleGroup);
heading.textContent = `${title} · 行军图`;
return { overlay, panel, header };
};
const getTraversedEdgeIds = map => {
const traversed = new Set();
const completed = map.completedNodeIds || [];
for (let index = 1; index < completed.length; index++) {
traversed.add(`${completed[index - 1]}\u0000${completed[index]}`);
}
return traversed;
};
export const showMap = run => new Promise(resolve => {
const act = config.acts[run.actIndex];
const selectable = getSelectableNodes(run);
const selectableIds = new Set(selectable.map(node => node.id));
const traversedEdgeIds = getTraversedEdgeIds(run.map);
const { overlay, panel, header } = createMapOverlay(act.name);
let closeCardLibrary = null;
const finish = result => {
if (overlay.dataset.resolved) return;
overlay.dataset.resolved = "true";
document.removeEventListener("keydown", handleEscape);
closeCardLibrary?.();
overlay.remove();
resolve(result);
};
const menuTrigger = document.createElement("button");
menuTrigger.type = "button";
menuTrigger.className = "mengsan-map-menu-trigger-shuying";
menuTrigger.appendChild(makeControlIcon("menu"));
const menuTriggerLabel = document.createElement("span");
menuTriggerLabel.textContent = "菜单";
menuTrigger.appendChild(menuTriggerLabel);
menuTrigger.setAttribute("aria-haspopup", "dialog");
menuTrigger.setAttribute("aria-expanded", "false");
menuTrigger.setAttribute("aria-controls", "mengsan-map-menu-shuying");
header.insertBefore(menuTrigger, header.firstChild);
const status = ui.create.div(".mengsan-map-status-shuying", header);
const statusItems = [
["生命", run.player.hp == null ? "未初始化" : `${run.player.hp}/${run.player.maxHp}`],
["金币", String(run.player.gold)],
["牌组", String(run.player.deck.length)],
];
statusItems.forEach(([label, value]) => {
const item = ui.create.div(".mengsan-map-stat-shuying", status);
createText("mengsan-map-stat-label-shuying", label, item);
createText("mengsan-map-stat-value-shuying", value, item);
});
const menuLayer = ui.create.div(".mengsan-map-menu-layer-shuying", panel);
menuLayer.id = "mengsan-map-menu-shuying";
menuLayer.hidden = true;
const menuScrim = ui.create.div(".mengsan-map-menu-scrim-shuying", menuLayer);
const menuSheet = document.createElement("div");
menuSheet.className = "mengsan-map-menu-sheet-shuying";
menuSheet.setAttribute("role", "dialog");
menuSheet.setAttribute("aria-modal", "true");
menuSheet.setAttribute("aria-labelledby", "mengsan-map-menu-title-shuying");
menuLayer.appendChild(menuSheet);
const menuHeader = document.createElement("div");
menuHeader.className = "mengsan-map-menu-header-shuying";
menuSheet.appendChild(menuHeader);
const menuHeadingGroup = document.createElement("div");
menuHeadingGroup.className = "mengsan-map-menu-heading-group-shuying";
menuHeader.appendChild(menuHeadingGroup);
createText("mengsan-map-menu-kicker-shuying", "征程管理", menuHeadingGroup);
const menuTitle = createText("mengsan-map-menu-title-shuying", "行军菜单", menuHeadingGroup);
menuTitle.id = "mengsan-map-menu-title-shuying";
const closeMenu = document.createElement("button");
closeMenu.type = "button";
closeMenu.className = "mengsan-map-icon-button-shuying";
closeMenu.appendChild(makeControlIcon("close"));
closeMenu.setAttribute("aria-label", "关闭菜单");
menuHeader.appendChild(closeMenu);
const menuContent = document.createElement("div");
menuContent.className = "mengsan-map-menu-content-shuying";
menuSheet.appendChild(menuContent);
const menuFooter = document.createElement("div");
menuFooter.className = "mengsan-map-menu-footer-shuying";
menuSheet.appendChild(menuFooter);
const exitButton = document.createElement("button");
exitButton.type = "button";
exitButton.className = "mengsan-map-exit-fixed-shuying";
exitButton.appendChild(makeControlIcon("exit"));
const exitCopy = document.createElement("span");
exitCopy.className = "mengsan-map-exit-copy-shuying";
const exitName = document.createElement("strong");
exitName.textContent = "返回模式选择";
const exitDescription = document.createElement("small");
exitDescription.textContent = "保留已保存征程,选择其他模式";
exitCopy.append(exitName, exitDescription);
exitButton.appendChild(exitCopy);
exitButton.addEventListener("click", async () => {
if (exitButton.disabled) return;
exitButton.disabled = true;
try {
const result = await askMenu("返回模式选择?", "保留上次完成节点的存档,未完成内容不会提交。", [
{ id: "cancel", name: "留在行军图" },
{ id: "exit", name: "确认返回模式选择", danger: true },
]);
if (result === "exit") await openModeSelection();
} catch (error) {
console.error(error);
await askMenu("暂时无法返回", "征程未被清除,请重试。", [{ id: "close", name: "关闭提示" }]);
} finally { exitButton.disabled = false; }
});
menuFooter.appendChild(exitButton);
const setMenuOpen = open => {
if (open) renderMainMenu();
menuLayer.hidden = !open;
menuTrigger.setAttribute("aria-expanded", String(open));
panel.classList.toggle("menu-open", open);
if (open) requestAnimationFrame(() => menuSheet.querySelector("button")?.focus());
else menuTrigger.focus();
};
const createMenuAction = ({ icon, name, description, danger = false, disabled = false, onClick }) => {
const button = document.createElement("button");
button.type = "button";
button.className = "mengsan-map-menu-action-shuying";
if (danger) button.classList.add("danger");
button.disabled = disabled;
button.appendChild(makeControlIcon(icon));
const copy = document.createElement("div");
copy.className = "mengsan-map-menu-action-copy-shuying";
button.appendChild(copy);
createText("mengsan-map-menu-action-name-shuying", name, copy);
createText("mengsan-map-menu-action-description-shuying", description, copy);
button.addEventListener("click", onClick);
menuContent.appendChild(button);
return button;
};
const showMenuPage = (title, subtitle, render) => {
menuTitle.textContent = title;
menuContent.replaceChildren();
const intro = ui.create.div(".mengsan-map-menu-page-intro-shuying", menuContent);
intro.textContent = subtitle;
render(menuContent);
const back = document.createElement("button");
back.type = "button";
back.className = "mengsan-map-menu-back-shuying";
back.appendChild(makeControlIcon("back"));
const label = document.createElement("span");
label.textContent = "返回菜单";
back.appendChild(label);
back.addEventListener("click", renderMainMenu);
menuContent.appendChild(back);
requestAnimationFrame(() => back.focus());
};
const renderBackpack = parent => {
const summary = ui.create.div(".mengsan-map-inventory-summary-shuying", parent);
[["卡牌", run.player.deck.length], ["道具", run.player.items?.length || 0], ["技能", run.player.permanentSkills?.length || 0]].forEach(([label, value]) => {
const item = ui.create.div(".mengsan-map-inventory-count-shuying", summary);
createText("", String(value), item);
createText("", label, item);
});
const library = document.createElement("button");
library.type = "button";
library.className = "mengsan-map-menu-action-shuying";
library.setAttribute("aria-haspopup", "dialog");
library.appendChild(makeControlIcon("book"));
const copy = document.createElement("div");
copy.className = "mengsan-map-menu-action-copy-shuying";
createText("mengsan-map-menu-action-name-shuying", "卡牌库", copy);
createText("mengsan-map-menu-action-description-shuying", `共 ${run.player.deck.length} 张 · 查看花色、点数、属性和卡牌详情`, copy);
library.appendChild(copy);
library.addEventListener("click", () => { closeCardLibrary = openCardLibrary(run); });
parent.appendChild(library);
const appendNames = (title, values, emptyText) => {
createText("mengsan-map-inventory-section-title-shuying", title, parent);
const list = ui.create.div(".mengsan-map-inventory-list-shuying", parent);
if (!values?.length) {
createText("mengsan-map-empty-shuying", emptyText, list);
return;
}
values.forEach(value => {
const row = ui.create.div(".mengsan-map-inventory-row-shuying", list);
createText("", get.translation(value) || value, row);
createText("", "已获得", row);
});
};
const supports = run.player.supports || [];
createText("mengsan-map-inventory-section-title-shuying", "战斗支援", parent);
const supportList = ui.create.div(".mengsan-map-inventory-list-shuying", parent);
if (!supports.length) createText("mengsan-map-empty-shuying", "暂无战斗支援。", supportList);
for (const support of supports) {
const row = ui.create.div(".mengsan-map-inventory-row-shuying", supportList);
createText("", config.rewards[support.rewardId]?.name || get.translation(support.unit.character), row);
createText("", support.battles === -1 ? "本次征程持续生效" : `剩余 ${support.battles} 场`, row);
}
appendNames("永久道具", run.player.items, "尚未获得永久道具。");
appendNames("永久技能", run.player.permanentSkills, "尚未获得永久技能。");
};
const renderPlaceholder = (parent, message) => {
const empty = ui.create.div(".mengsan-map-placeholder-shuying", parent);
empty.appendChild(makeControlIcon("record"));
createText("mengsan-map-placeholder-title-shuying", "功能开发中", empty);
createText("mengsan-map-placeholder-text-shuying", message, empty);
};
function renderMainMenu() {
menuTitle.textContent = "行军菜单";
menuContent.replaceChildren();
createMenuAction({ icon: "map", name: "继续行军", description: "关闭菜单并返回当前路线", onClick: () => setMenuOpen(false) });
createMenuAction({ icon: "bag", name: "行囊", description: `查看牌组、道具与永久技能 · ${run.player.deck.length}张牌`, onClick: () => showMenuPage("行囊", "本次征程携带的资源", renderBackpack) });
createMenuAction({ icon: "book", name: "图鉴", description: "查看已发现的敌人、事件与奖励 · 开发中", onClick: () => showMenuPage("图鉴", "征程见闻与收集记录", parent => renderPlaceholder(parent, "后续将收录已发现的节点、敌人和奖励。")) });
createMenuAction({ icon: "record", name: "征程记录", description: `已通过 ${run.statistics?.completedNodes || 0} 个节点`, onClick: () => showMenuPage("征程记录", "本次征程的阶段统计", parent => {
const list = ui.create.div(".mengsan-map-record-list-shuying", parent);
[["已通过节点", run.statistics?.completedNodes || 0], ["击败敌人", run.statistics?.defeatedEnemies || 0], ["累计金币", run.statistics?.goldEarned || 0]].forEach(([label, value]) => {
const row = ui.create.div(".mengsan-map-inventory-row-shuying", list);
createText("", label, row);
createText("", String(value), row);
});
}) });
createMenuAction({ icon: "settings", name: "设置与说明", description: "显示、音效与玩法说明 · 开发中", onClick: () => showMenuPage("设置与说明", "个性化与帮助", parent => renderPlaceholder(parent, "后续将在这里提供显示、音效和操作设置。")) });
}
function handleEscape(event) {
if (window.inSplash) return;
if (document.querySelector("dialog.mengsan-deck-dialog-shuying[open]")) return;
if (document.querySelector(".mengsan-menu-dialog-shuying[open]")) return;
if (event.key == "Escape" && !menuLayer.hidden) {
event.preventDefault();
setMenuOpen(false);
}
else if (event.key == "Tab" && !menuLayer.hidden) {
const focusable = Array.from(menuSheet.querySelectorAll("button:not(:disabled)"));
if (!focusable.length) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
}
else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
}
renderMainMenu();
menuTrigger.addEventListener("click", () => setMenuOpen(true));
closeMenu.addEventListener("click", () => setMenuOpen(false));
menuScrim.addEventListener("click", () => setMenuOpen(false));
document.addEventListener("keydown", handleEscape);
const legend = document.createElement("details");
legend.className = "mengsan-ink-legend-shuying";
legend.open = window.matchMedia("(min-width: 900px)").matches;
const summary = document.createElement("summary");
summary.textContent = "行军图例";
legend.appendChild(summary);
Object.keys(iconPaths).forEach(type => {
const item = document.createElement("div");
item.appendChild(makeIcon(type));
const label = document.createElement("span");
label.textContent = type === "boss" ? "关底主将" : config.nodeNames[type];
item.appendChild(label);
legend.appendChild(item);
});
const hint = document.createElement("p");
hint.textContent = "朱圈可行 · 墨线已行";
legend.appendChild(hint);
panel.appendChild(legend);
const viewport = ui.create.div(".mengsan-map-viewport-shuying", panel);
let drag = null;
let suppressClick = false;
viewport.addEventListener("pointerdown", event => {
if (!event.isPrimary || event.button !== 0) return;
suppressClick = false;
if (event.pointerType !== "mouse") return;
drag = { id: event.pointerId, y: event.clientY, top: viewport.scrollTop, moved: false };
});
viewport.addEventListener("pointermove", event => {
if (!drag || drag.id !== event.pointerId) return;
const distance = event.clientY - drag.y;
if (!drag.moved && Math.abs(distance) < 6) return;
drag.moved = true;
suppressClick = true;
if (!viewport.hasPointerCapture(event.pointerId)) viewport.setPointerCapture(event.pointerId);
viewport.classList.add("dragging");
viewport.scrollTop = drag.top - distance;
event.preventDefault();
});
const endDrag = event => {
if (!drag || drag.id !== event.pointerId) return;
drag = null;
viewport.classList.remove("dragging");
if (viewport.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
};
viewport.addEventListener("pointerup", endDrag);
viewport.addEventListener("pointercancel", endDrag);
viewport.addEventListener("lostpointercapture", endDrag);
viewport.addEventListener("pointerleave", event => {
if (drag && !drag.moved) endDrag(event);
});
viewport.addEventListener("click", event => {
if (suppressClick && event.detail !== 0) {
event.preventDefault();
event.stopImmediatePropagation();
suppressClick = false;
}
}, true);
const map = ui.create.div(".mengsan-map-shuying", viewport);
const floorCount = Math.max(...run.map.nodes.map(node =>
Math.floor(node.floor))) + 1;
map.style.setProperty("--mengsan-map-min-height",
`${floorCount * 150}px`);
const landscape = document.createElementNS("http://www.w3.org/2000/svg", "svg");
landscape.classList.add("mengsan-ink-landscape-shuying");
landscape.setAttribute("viewBox", "0 0 800 1200");
landscape.setAttribute("preserveAspectRatio", "none");
landscape.setAttribute("aria-hidden", "true");
["M0 580L45 380 80 420 145 210 204 340 242 310 295 590Z", "M510 950l80-240 30 40 60-280 42 110 32-70 46 330v110Z", "M0 1140q150-75 320-5t480-30v95H0Z"].forEach(d => {
const mountain = document.createElementNS("http://www.w3.org/2000/svg", "path");
mountain.setAttribute("d", d);
landscape.appendChild(mountain);
});
map.appendChild(landscape);
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.classList.add("mengsan-lines-shuying");
svg.setAttribute("viewBox", "0 0 100 100");
svg.setAttribute("preserveAspectRatio", "none");
svg.setAttribute("aria-hidden", "true");
map.appendChild(svg);
const nodeMap = new Map(run.map.nodes.map(node => [node.id, node]));
run.map.edges.forEach(edge => {
const source = nodeMap.get(edge[0]);
const target = nodeMap.get(edge[1]);
if (!source || !target) return;
const line = document.createElementNS("http://www.w3.org/2000/svg", "path");
const midY = (source.y + target.y) / 2;
line.setAttribute("d", `M ${source.x} ${source.y} C ${source.x} ${midY}, ${target.x} ${midY}, ${target.x} ${target.y}`);
if (source.id === run.map.currentNodeId && selectableIds.has(target.id)) line.classList.add("available");
if (traversedEdgeIds.has(`${source.id}\u0000${target.id}`)) line.classList.add("completed");
if (source.dynamic || target.dynamic) line.classList.add("dynamic");
svg.appendChild(line);
});
run.map.nodes.forEach(node => {
const button = document.createElement("button");
button.type = "button";
button.className = "mengsan-node-shuying";
map.appendChild(button);
button.style.left = `${node.x}%`;
button.style.top = `${node.y}%`;
button.style.setProperty("--node-color", nodeColor[node.type] || "#666");
const content = node.contentId ? config.nodeContents?.[node.contentId] : null;
const label = content?.mapName || (node.type === "boss" ? "关底主将" : config.nodeNames[node.type]) || node.type;
button.appendChild(makeIcon(node.type));
const caption = document.createElement("span");
caption.textContent = label;
button.appendChild(caption);
button.title = label;
button.setAttribute("aria-label", `${label},${node.completed ? "已完成" : selectableIds.has(node.id) ? "可前往" : "未开放"}`);
button.setAttribute("aria-disabled", String(!selectableIds.has(node.id)));
button.tabIndex = selectableIds.has(node.id) ? 0 : -1;
button.dataset.type = node.type;
if (node.id === run.map.currentNodeId) {
button.classList.add("current");
button.setAttribute("aria-current", "step");
}
button.dataset.nodeId = node.id;
if (node.completed) button.classList.add("completed");
else if (selectableIds.has(node.id)) button.classList.add("selectable");
else button.classList.add("locked");
button.addEventListener("click", event => {
event.preventDefault();
if (!selectableIds.has(node.id) || overlay.dataset.resolved) return;
finish(node);
});
});
requestAnimationFrame(() => {
if (!overlay.isConnected) return;
const current = nodeMap.get(run.map.currentNodeId) || selectable[0];
viewport.scrollTop = current
? Math.max(0, map.offsetHeight * current.y / 100 - viewport.clientHeight * 0.76)
: viewport.scrollHeight;
});
});
export default showMap;
+120
View File
@@ -0,0 +1,120 @@
import { lib, game, ui } from "../../../../noname.js";
import { save } from "../../../../noname/util/config.js";
let selectingMode = false;
// Reuse the registered engine splash, not reload-to-the-current-mode or a fake mode list.
export const openModeSelection = async () => {
if (selectingMode) return;
const splash = lib.onloadSplashes.find(item => item.id === lib.config.splash_style) || lib.onloadSplashes[0];
if (!splash) throw new Error("模式选择界面未加载,请稍后重试。");
selectingMode = true;
const previousSplash = window.inSplash;
const previousFocus = document.activeElement;
const previousInert = ui.window.inert;
const node = ui.create.div("#splash", document.body);
node.style.zIndex = "1000";
window.inSplash = true;
ui.window.inert = true;
try {
let choose;
const selected = new Promise(resolve => { choose = resolve; });
await splash.init(node, choose);
const mode = await selected;
if (!lib.config.all.mode.includes(mode)) throw new Error("所选模式不可用。");
await save("mode", "config", mode);
lib.config.mode = mode;
localStorage.setItem(`${lib.configprefix}directstart`, "true");
// Reload only AFTER a mode is chosen; retain engine pending-write handling.
node.inert = true;
game.reload();
// Keep the abandoned flow inert while the engine waits for pending DB writes.
await new Promise(() => {});
} catch (error) {
// DefaultSplash owns a Vue app. Clean it up if opening/saving failed.
splash.app?.unmount?.();
throw error;
} finally {
node.remove();
window.inSplash = previousSplash;
ui.window.inert = previousInert;
selectingMode = false;
if (previousFocus?.isConnected) previousFocus.focus();
}
};
export const askMenu = (title, description, choices) => new Promise(resolve => {
const previousFocus = document.activeElement;
const dialog = document.createElement("dialog");
dialog.className = "mengsan-menu-dialog-shuying";
dialog.setAttribute("aria-label", title);
const heading = document.createElement("h2");
heading.textContent = title;
const body = document.createElement("p");
body.textContent = description;
dialog.append(heading, body);
let closed = false;
const finish = value => {
if (closed) return;
closed = true;
dialog.close();
dialog.remove();
if (previousFocus?.isConnected) previousFocus.focus();
resolve(value);
};
for (const choice of choices) {
const button = document.createElement("button");
button.type = "button";
button.textContent = choice.name;
if (choice.danger) button.className = "danger";
button.addEventListener("click", () => finish(choice.id));
dialog.appendChild(button);
}
dialog.addEventListener("cancel", event => { event.preventDefault(); finish(null); });
document.body.appendChild(dialog);
dialog.showModal();
dialog.querySelector("button")?.focus();
});
export const mountMenu = (overlay, options = {}) => {
const button = document.createElement("button");
button.type = "button";
button.className = "mengsan-flow-menu-shuying";
const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
icon.setAttribute("viewBox", "0 0 24 24");
icon.setAttribute("aria-hidden", "true");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", "M4 6h16M4 12h16M4 18h16");
icon.appendChild(path);
const label = document.createElement("span");
label.textContent = "菜单";
button.append(icon, label);
button.setAttribute("aria-haspopup", "dialog");
let opened = false;
button.addEventListener("click", async event => {
event.stopPropagation();
if (opened) return;
opened = true;
options.onOpen?.();
try {
const action = await askMenu("征程菜单", "退出不删除存档。未完成的节点与对话将在下次进入时重新开始。", [
{ id: "resume", name: "继续当前界面" },
{ id: "exit", name: "返回模式选择" },
]);
if (action !== "exit") return;
const confirmed = await askMenu("返回模式选择?", "保留上次已完成节点的存档。本次尚未完成的内容不会提交。", [
{ id: "cancel", name: "留在梦三" },
{ id: "confirm", name: "确认返回模式选择", danger: true },
]);
if (confirmed === "confirm") await openModeSelection();
} catch (error) {
console.error("梦三返回模式选择失败:", error);
await askMenu("暂时无法返回", "没有清除征程。请关闭提示后重试。", [{ id: "close", name: "回到当前界面" }]);
} finally {
opened = false;
options.onClose?.();
}
});
overlay.appendChild(button);
return button;
};
+190
View File
@@ -0,0 +1,190 @@
import { lib, get } from "../../../../noname.js";
import { cardCost } from "../battle/combat-rules.js";
import { chooseButtons } from "./flow-ui.js";
const element = (tag, className, text, parent) => {
const node = document.createElement(tag);
node.className = className;
if (text != null) node.textContent = text;
parent?.appendChild(node);
return node;
};
const plainText = value => {
const template = document.createElement("template");
template.innerHTML = String(value ?? "").replace(/<br\s*\/?\s*>/gi, "\n");
return template.content.textContent.trim();
};
const cardNameOf = choice => choice?.card?.name || ({ card_sha: "sha", card_tao: "tao" })[choice?.effectId] || null;
export const isCardReward = choice => Boolean(cardNameOf(choice));
const viewCard = choice => {
const name = cardNameOf(choice);
const info = lib.card[name];
const imageName = info?.cardimage || name;
const image = /^[a-zA-Z0-9_]+$/.test(imageName) ? `${lib.assetURL || ""}image/card/${imageName}.png` : null;
const type = { basic: "基本牌", trick: "锦囊牌", delay: "延时锦囊", equip: "装备牌" }[info?.type] || "卡牌";
return {
name: get.translation(name), type, image, cost: cardCost({ name }),
description: plainText(lib.translate[`${name}_info`] || choice.description || "暂无卡牌介绍。"),
};
};
const restoreFocus = previous => { if (previous?.isConnected) previous.focus(); };
const RETURN_TO_VICTORY = Symbol("return to victory choice");
// Reusable card-only selector. It accepts three cards today and can lay out four or five later.
// Callers supply stable choice IDs; this UI never creates or awards cards itself.
export function chooseCardDialog(choices, { title = "选择一张牌", allowSkip = true, skipLabel = "跳过" } = {}) {
if (!Array.isArray(choices) || !choices.length || choices.some(choice => !choice?.id || !isCardReward(choice))) {
return Promise.reject(new TypeError("chooseCardDialog requires nonempty card choices with IDs"));
}
return new Promise((resolve, reject) => {
const previousFocus = document.activeElement;
const dialog = element("dialog", "mengsan-card-choice-dialog-shuying", null);
dialog.setAttribute("aria-label", title);
const stage = element("div", "mengsan-card-choice-stage-shuying", null, dialog);
const banner = element("header", "mengsan-card-choice-heading-shuying", null, stage);
element("span", "mengsan-reward-overline-shuying", "梦三 · 战利品", banner);
element("h2", "", title, banner);
element("p", "", "择一入阵,余者留于身后", banner);
const cards = element("div", "mengsan-card-choice-grid-shuying", null, stage);
cards.style.setProperty("--choice-count", String(Math.min(choices.length, 5)));
let settled = false;
const finish = id => {
if (settled) return;
settled = true;
if (dialog.open) dialog.close();
dialog.remove();
restoreFocus(previousFocus);
resolve(id);
};
for (const choice of choices) {
const view = viewCard(choice);
const card = element("button", "mengsan-card-choice-tile-shuying", null, cards);
card.type = "button";
card.setAttribute("aria-label", `${view.name},${view.type},${view.description}。选择此牌`);
card.addEventListener("click", () => finish(choice.id));
element("span", "mengsan-card-choice-cost-shuying", String(view.cost), card);
element("span", "mengsan-card-choice-name-shuying", view.name, card);
const artwork = element("span", "mengsan-card-choice-art-shuying", null, card);
if (view.image) {
const image = element("img", "", null, artwork);
image.src = view.image; image.alt = ""; image.loading = "lazy";
image.addEventListener("error", () => image.remove(), { once: true });
}
element("span", "mengsan-card-choice-glyph-shuying", view.name.slice(0, 1), artwork);
element("span", "mengsan-card-choice-kind-shuying", view.type, card);
element("span", "mengsan-card-choice-description-shuying", view.description, card);
}
if (allowSkip) {
const skip = element("button", "mengsan-card-choice-skip-shuying", skipLabel, stage);
skip.type = "button";
skip.addEventListener("click", () => finish(null));
}
dialog.addEventListener("cancel", event => event.preventDefault());
dialog.addEventListener("keydown", event => event.stopPropagation());
// The engine scales <body>; attach to <html> so viewport-sized modals stay full-screen.
document.documentElement.appendChild(dialog);
try { dialog.showModal(); cards.querySelector("button")?.focus(); }
catch (error) { dialog.remove(); restoreFocus(previousFocus); reject(error); }
});
}
// Reusable post-battle choice surface. Each option owns its follow-up; the surface
// only resolves a stable candidate ID (or null) and never awards a reward itself.
export function chooseVictoryOptions(options, { title = "战后抉择", allowSkip = true } = {}) {
if (!Array.isArray(options) || !options.length || options.some(option => !option?.id || !option?.label)) {
return Promise.reject(new TypeError("chooseVictoryOptions requires nonempty options with IDs and labels"));
}
return new Promise((resolve, reject) => {
const previousFocus = document.activeElement;
const dialog = element("dialog", "mengsan-victory-dialog-shuying", null);
dialog.setAttribute("aria-label", title);
const stage = element("div", "mengsan-victory-stage-shuying", null, dialog);
const intro = element("header", "mengsan-victory-intro-shuying", null, stage);
element("span", "mengsan-reward-overline-shuying", "梦三 · 战后", intro);
element("span", "mengsan-victory-seal-shuying", "胜", intro);
element("h2", "", title, intro);
element("p", "", "此役已定,选择下一段征途的收获。", intro);
const board = element("div", "mengsan-victory-options-shuying", null, stage);
element("span", "mengsan-victory-eyebrow-shuying", "可选战利品", board);
let settled = false, choosing = false;
const finish = id => {
if (settled) return;
settled = true;
if (dialog.open) dialog.close();
dialog.remove();
restoreFocus(previousFocus);
resolve(id);
};
for (const [index, option] of options.entries()) {
const entry = element("button", "mengsan-victory-option-shuying", null, board);
entry.type = "button";
entry.setAttribute("aria-label", `${option.label}。${option.description || ""}`);
element("span", "mengsan-victory-option-index-shuying", String(index + 1).padStart(2, "0"), entry);
const copy = element("span", "mengsan-victory-option-copy-shuying", null, entry);
element("strong", "", option.label, copy);
if (option.description) element("small", "", option.description, copy);
element("span", "mengsan-victory-option-arrow-shuying", "›", entry).setAttribute("aria-hidden", "true");
entry.addEventListener("click", async () => {
if (settled || choosing) return;
choosing = true;
entry.disabled = true;
if (dialog.open) dialog.close();
try {
const selected = option.choose ? await option.choose() : option.id;
if (selected === RETURN_TO_VICTORY) {
dialog.showModal();
entry.disabled = false;
choosing = false;
entry.focus();
} else finish(selected);
}
catch (error) {
if (!settled) { settled = true; dialog.remove(); restoreFocus(previousFocus); reject(error); }
}
});
}
if (allowSkip) {
const skip = element("button", "mengsan-victory-skip-shuying", "放弃本次选择", stage);
skip.type = "button";
skip.addEventListener("click", () => { if (!choosing) finish(null); });
}
dialog.addEventListener("cancel", event => event.preventDefault());
dialog.addEventListener("keydown", event => event.stopPropagation());
document.documentElement.appendChild(dialog);
try { dialog.showModal(); board.querySelector("button")?.focus(); }
catch (error) { dialog.remove(); restoreFocus(previousFocus); reject(error); }
});
}
// Gold is a persisted candidate, not an automatic reward. The card pool remains
// a separate Dialog; skipping that Dialog returns to the victory choices.
export function chooseBattleReward(choices) {
if (!Array.isArray(choices) || !choices.length) return Promise.resolve(null);
const gold = choices.find(choice => choice.kind === "gold");
const rewards = choices.filter(choice => choice.kind !== "gold");
const options = [];
if (gold) options.push({
id: gold.id,
label: `金币 · ${gold.amount}`,
description: "将此关金币收入征程钱袋。",
});
if (rewards.length) {
const cardOnly = rewards.every(isCardReward);
options.push({
id: "choose-reward",
label: cardOnly ? "择一张牌" : "挑选一项战利品",
description: cardOnly ? "从本次候选卡牌中选择一张,加入牌组。" : "检视本次战利品,再决定带走哪一项。",
async choose() {
const selected = cardOnly
? await chooseCardDialog(rewards, {skipLabel:"跳过选卡"})
: await chooseButtons("选择一项奖励", rewards);
return selected ?? RETURN_TO_VICTORY;
},
});
}
return chooseVictoryOptions(options);
}
+1389
View File
File diff suppressed because it is too large Load Diff
+36 -1
View File
@@ -210,7 +210,7 @@ export default function initShuYingMenu({ lib, game, ui, shuYing, updater }) {
menu.update_channel = {
name: channelText(updater.getUpdateChannel()),
clear: true,
intro: "切换后立即从 Gitea 对应标签下载并校验文件,完成后需重启游戏。测试版可能回退到较早的内容。",
intro: "切换后立即从当前下载源的对应标签下载并校验文件,完成后需重启游戏。测试版可能回退到较早的内容。",
async onclick() {
if (!shuYing.m_bIsDownload) {
alert("有其他文件正在下载,请稍后再试吧。");
@@ -239,6 +239,28 @@ export default function initShuYingMenu({ lib, game, ui, shuYing, updater }) {
},
};
const sourceText = source => `下载源:${source == "github" ? "GitHub" : "Gitea"}(点击切换)`;
menu.update_source = {
name: sourceText(updater.getUpdateSource()),
clear: true,
intro: "选择从 GitHub 或 Gitea 获取标签与文件;切换后刷新在线版本,实际下载由版本检测触发。",
onclick() {
if (!shuYing.m_bIsDownload) {
alert("有其他文件正在下载,请稍后再试吧。");
return;
}
const next = updater.getUpdateSource() == "github" ? "gitea" : "github";
game.saveConfig("shuYing_update_source", next);
const text = sourceText(next);
menu.update_source.name = text;
this.innerHTML = text;
game.saveConfig("shuYing_online_version", null);
shuYing.updateOnlineVersionMenu(null, "检测中...");
shuYing.getVersion();
},
};
menu.updateLog = {
name: '<div class="hth_menu">▶更新日志</div>',
clear: true,
@@ -317,6 +339,19 @@ export default function initShuYingMenu({ lib, game, ui, shuYing, updater }) {
},
};
menu.mengsanModule = {
name: "梦三模式(按需安装/卸载)",
clear: true,
onclick() {
if (shuYing.m_bIsDownload) {
shuYing.m_bIsDownload = false;
updater.manageMengsanModule(shuYing);
} else {
alert("有其他文件正在下载,请稍后再试吧。");
}
},
};
menu.repairBug = {
name: "本地资源修复",
clear: true,
+7 -8
View File
@@ -1015,18 +1015,17 @@ const skill = {
},
async content(event, trigger, player) {
const target = trigger.player;
const loseEvent = target.loseHp(trigger.num);
loseEvent.shuYing_Tianshu_Skill_09_Skill3 = true;
loseEvent.shuYing_source = player;
await loseEvent;
await target.loseHp(trigger.num);
if (!target.isIn()) return;
const loseHpNum = target
.getHistory("loseHp", evt => {
// 体力变化记录在全局历史中,只累计本回合该目标流失的体力。
const loseHpNum = game
.getGlobalHistory("changeHp", evt => {
return (
evt.shuYing_Tianshu_Skill_09_Skill3 &&
evt.shuYing_source == player
evt.player == target &&
evt.getParent().name == "loseHp" &&
evt.num < 0
);
})
.reduce((sum, evt) => {
+84 -2
View File
@@ -24,6 +24,7 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
corpseChooseCleanup: null,
corpseChooseEvent: null,
initialBoss: null,
defending: false,
virtualIdol: null,
running: false,
pendingSpawn: false,
@@ -100,6 +101,27 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
const isVirtualIdol = player => Boolean(player && (getVirtualIdolIds().includes(player.name1) || getVirtualIdolIds().includes(player.name)));
// 判断指定角色是否为当前关卡实际召唤的 Boss;玩家变身为同名动态武将时不会被误判。
const isCurrentStageBoss = player => Boolean(player?.storage?.shuYing_tianshu_stageBoss && player.storage.shuYing_tianshu_stageIndex == state.stageIndex);
// 应战身份独立于 game.me/game.boss,避免动态换控后误判阵营和胜负。
const swapDefendingBoss = target => {
if (!state.defending || !target || !game.players.includes(target) || !isCurrentStageBoss(target)) return;
game.swapControl(target);
game.onSwapControl?.();
// 应战开局沿用主 Boss UI,会隐藏 fakeme;换成动态 Boss 后必须恢复代理头像。
// 直接复用已经显示正确的角色头像,不按克隆 ID 拼接图片路径。
if (ui.fakeme) {
game.singleHandcard = true;
ui.arena?.classList.add("single-handcard");
ui.window?.classList.add("single-handcard");
ui.fakeme.style.display = "";
ui.fakeme.current = target.name;
ui.fakeme.style.backgroundImage = target.node.avatar.style.backgroundImage;
ui.updatehl?.();
}
};
const getNextDefendingBoss = dead => {
const bosses = game.players.filter(isCurrentStageBoss).sort((a, b) => Number(a.dataset.position) - Number(b.dataset.position));
return bosses.find(boss => Number(boss.dataset.position) > Number(dead?.dataset.position ?? -1)) || bosses[0];
};
// 判断指定角色是否属于开局捕获的玩家方。
const isCapturedPlayerSide = player => Boolean(getPlayerKey(player) && state.playerSideIds[getPlayerKey(player)]);
// 获取玩家方角色列表,可按是否存活、是否包含虚拟偶像过滤。
@@ -188,6 +210,20 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
// 结束当前 phase 事件,把后续行动权交给指定角色;保留旧版重置轮数与阶段的做法。
const finishCurrentPhaseTo = target => {
if (!target) return;
// 清剿把弃牌事件挂在上层队列;finish 不会清空队列,不能让旧关结算弃掉新关奖励。
let pendingParent = _status.event;
const pendingVisited = new Set();
while (pendingParent && !pendingVisited.has(pendingParent)) {
pendingVisited.add(pendingParent);
for (const queue of [pendingParent.next, pendingParent.after]) {
if (!Array.isArray(queue)) continue;
for (let i = queue.length - 1; i >= 0; i--) {
if (queue[i]?.name == "qingjiao_discard") queue.splice(i, 1);
}
}
if (pendingParent.name == "phaseLoop") break;
pendingParent = pendingParent.getParent ? pendingParent.getParent() : pendingParent.parent;
}
const phase = _status.event?.getParent ? _status.event.getParent("phase") : getParentEvent("phase");
if (phase) {
if (typeof game.resetSkills == "function") game.resetSkills();
@@ -314,6 +350,16 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
boss.storage.shuYing_tianshu_stageBoss = true;
boss.storage.shuYing_tianshu_stageIndex = state.stageIndex;
boss.storage.shuYing_tianshu_originalBossName = originalName;
if (state.defending) {
const originalIsUnderControl = boss.isUnderControl;
boss.isUnderControl = function (self, me = game.me) {
if (state.running && state.defending && isCurrentStageBoss(this) && isCurrentStageBoss(me)
&& !_status.connectMode && !game.notMe && !this.isMad() && get.config("single_control")) {
return this == me ? Boolean(self) : true;
}
return originalIsUnderControl.call(this, self, me);
};
}
game.addVideo("setIdentity", boss, boss.identity);
if (game.playerMap) game.playerMap[boss.dataset.position] = boss;
game.arrangePlayers();
@@ -591,6 +637,7 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
player._start_cards.addArray(cards);
}
}
if (state.defending) swapDefendingBoss(getNextDefendingBoss());
};
// 读取玩家当前武将牌上自带的技能,避免过关奖励重复刷出本体技能。
const getCharacterCardSkills = player => {
@@ -976,6 +1023,8 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
};
// 让指定玩家从 UI 中选择一个奖励技能,并返回刷新请求或最终技能。
const chooseRewardSkill = async (player, choices, canRefresh) => {
// 应战者不能代替敌方选奖励;沿用无人类操作时的自动选择路径。
if (state.defending) return choices[0] || null;
const chooser = getRewardSkillChooser(player);
const canChoose = chooser == game.me || chooser?.isUnderControl?.();
if (!canChoose || typeof shuYing.chooseSkillRewardDialog != "function") return choices[0] || null;
@@ -1019,7 +1068,7 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
if (state.clearingStage) return;
state.clearingStage = true;
if (state.stageIndex >= tianshuConfig.stages.length - 1) {
game.over(game.me !== game.boss);
game.over(!state.defending);
return;
}
await reviveVirtualIdolIfNeeded();
@@ -1059,6 +1108,7 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
if (!isCurrentStageBoss(deadBoss)) return;
if (deadBoss.storage.shuYing_tianshu_bossDieHandled) return;
deadBoss.storage.shuYing_tianshu_bossDieHandled = true;
if (state.defending && game.me == deadBoss) swapDefendingBoss(getNextDefendingBoss(deadBoss));
const stageCleared = !game.players.some(current => isCurrentStageBoss(current));
const finalCleared = stageCleared && state.stageIndex >= tianshuConfig.stages.length - 1;
if (!finalCleared && event.source && event.source.isIn()) {
@@ -1073,6 +1123,22 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
if (state.running) return;
state.running = true;
state.initialBoss = game.boss || null;
state.defending = Boolean(state.initialBoss && game.me == state.initialBoss);
if (state.defending) {
// 应战原生布局是 0/2/4/6;先恢复挑战者 1/2/3,再安排 Boss 和偶像,避免重叠。
game.players.filter(current => current != state.initialBoss && current.side === false)
.sort((a, b) => Number(a.dataset.position) - Number(b.dataset.position))
.forEach((current, index) => { current.dataset.position = index + 1; });
game.arrangePlayers();
const originalModeSwapPlayer = game.modeSwapPlayer;
game.modeSwapPlayer = function (target) {
if (state.running && state.defending && isCurrentStageBoss(target)) {
swapDefendingBoss(target);
return;
}
return originalModeSwapPlayer.apply(this, arguments);
};
}
installHiddenBossCorpseCheckHook();
spawnVirtualIdol();
capturePlayerSide();
@@ -1116,7 +1182,7 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
canReceiveOpeningProtection: player => Boolean(player && player.isIn() && !isCurrentStageBoss(player) && (isCapturedPlayerSide(player) || isVirtualIdol(player))),
// 玩家死亡后检查是否达到失败条件。
checkPlayerDefeat() {
if (this.isPlayerSideDefeated()) game.over(game.me === game.boss);
if (this.isPlayerSideDefeated()) game.over(state.defending);
},
refreshBonds: refreshTianshuBonds,
queueBondRefresh: queueTianshuBondRefresh,
@@ -1173,9 +1239,25 @@ export default function initTianshu(lib, game, ui, get, ai, _status, shuYing) {
game.addGlobalSkill("shuYing_Tianshu_NewSpawnStage");
game.addGlobalSkill("shuYing_Tianshu_NewBossDie");
game.addGlobalSkill("shuYing_Tianshu_NewPlayerDie");
game.addGlobalSkill("shuYing_Tianshu_DefendingControl");
game.addGlobalSkill("shuYing_Tianshu_BondManager");
},
},
shuYing_Tianshu_DefendingControl: {
trigger: { global: "phaseBefore" },
forced: true,
silent: true,
charlotte: true,
forceDie: true,
firstDo: true,
filter(event) {
return state.running && state.defending && !_status.connectMode
&& get.config("single_control") && isCurrentStageBoss(event.player);
},
async content(event, trigger) {
swapDefendingBoss(trigger.player);
},
},
shuYing_Tianshu_BondManager: {
mode: ["boss"],
trigger: { global: "changeSkillsAfter" },
+39
View File
@@ -0,0 +1,39 @@
# 更新清单与可选模块
## 梦三模式
梦三仍与主包保存在同一仓库,但作为独立下载模块发布。基础清单
`dist/manifest.json` 不包含 `mengsan/` 文件;模块清单
`dist/modules/mengsan.json` 单独记录梦三文件、大小和 SHA-256。
用户通过扩展菜单的“梦三模式(按需安装/卸载)”下载或卸载。主包版本
更新只检查主包文件,以及本地已安装模块的文件;“查漏补缺”会检查主包
资源和已安装模块,不会自动下载未安装的梦三模式。
## 发布流程
1. 在 `tools/manifest_config.json` 的 `core` 中维护主包必须文件。
2. 在 `modules` 中维护可选模块的目录、入口和显示名。
3. 发布工作流为每个模块生成独立清单,并将清单提交到发布标签。
4. 完整 ZIP 安装包仍包含所有模块,供离线或整包安装使用。
客户端从标签的 raw 文件路径读取清单。因此 Gitea 发布必须使用已经包含
`dist/manifest.json` 和 `dist/modules/*.json` 的同一标签;当前 Gitea 工作流
会生成并上传附件,但不会改写触发它的标签。
发布时生成器会把 `tools/legacy/mengsan-files.json`、上一次完整清单和当前模块
文件合并,随新标签发布迁移路径清单。它用于接管旧安装中的梦三文件并清理
不再属于新版本的文件。该文件由迁移时仓库内的梦三路径生成,作为冻结的旧版
所有权记录,兼容旧更新器已经推进主包版本号、但尚未更新梦三模块的用户。
## 旧文件与目录
升级时比较旧版和新版的文件路径清单,删除旧清单有、新清单没有的模块文件;
新增或损坏文件会按 SHA-256 下载和修复。模块卸载只删除模块清单声明的文件。
不根据“目录不在新清单中”递归删除目录,避免误删用户自行放入目录的文件。
确需删除整个旧目录时,先确认其不包含用户数据,再通过主包清单的
`removeDirectories` 明确声明。
新增模块时,清单生成器可通过配置建立独立清单;客户端的安装菜单、启动
加载和卸载入口仍需为该模块添加对应管理逻辑。
+201 -49
View File
@@ -12,6 +12,7 @@ EXCLUDE_DIRS = {
".gitea",
".github",
".update_tmp",
".planning",
"dist",
"tools",
"__pycache__",
@@ -68,15 +69,36 @@ def load_config(root: Path, config_path: str) -> dict:
"core": [],
"remove": [],
"removeDirectories": [],
"modules": {},
}
with path.open("r", encoding="utf-8") as file:
config = json.load(file)
modules = {}
for name, item in config.get("modules", {}).items():
legacy_files = item.get("legacy_files", [])
legacy_source = item.get("legacy_files_from")
if legacy_source:
legacy_path = Path(legacy_source)
if not legacy_path.is_absolute():
legacy_path = root / legacy_path
with legacy_path.open("r", encoding="utf-8") as file:
legacy_files = json.load(file)
if not isinstance(legacy_files, list):
raise ValueError(f"legacy file list must be an array: {name}")
modules[name] = {
"root": normalize_path(item["root"]),
"entry": normalize_path(item["entry"]),
"title": item.get("title", name),
"legacy_files": [normalize_path(path) for path in legacy_files],
}
return {
"core": [normalize_path(item) for item in config.get("core", [])],
"remove": [normalize_path(item) for item in config.get("remove", [])],
"removeDirectories": [normalize_path(item) for item in config.get("removeDirectories", [])],
"modules": modules,
}
@@ -117,67 +139,168 @@ def set_nested_file(tree: dict, relative_path: str, info: dict) -> None:
}
def build_manifest(root: Path, version: str, config: dict) -> dict:
flat_files = {}
tree = {
"type": "directory",
"name": root.name,
"children": {},
}
core_files = config["core"]
core_file_set = set(core_files)
remove_files = config["remove"]
remove_directories = config["removeDirectories"]
validate_config_files(root, core_files, "core")
validate_relative_paths(remove_files, "remove")
validate_relative_paths(remove_directories, "removeDirectories")
def build_manifest(root: Path, version: str, config: dict,
previous_manifest=None) -> tuple[dict, dict, dict]:
module_configs = config.get("modules", {})
module_roots = {name: item["root"] for name, item in module_configs.items()}
validate_relative_paths(list(module_roots.values()), "module roots")
if len(set(module_roots.values())) != len(module_roots):
raise ValueError("module roots must be unique")
for name, item in module_configs.items():
for other_name, other_root in module_roots.items():
if name != other_name and (
item["root"] == other_root
or item["root"].startswith(other_root + "/")
or other_root.startswith(item["root"] + "/")
):
raise ValueError("module roots cannot overlap")
def owned_by_module(path: str) -> bool:
return any(path == module_root or path.startswith(module_root + "/")
for module_root in module_roots.values())
config["remove"] = [file for file in config["remove"]
if not owned_by_module(file)]
config["removeDirectories"] = [
directory for directory in config["removeDirectories"]
if not any(directory == module_root
or directory.startswith(module_root + "/")
or module_root.startswith(directory + "/")
for module_root in module_roots.values())
]
all_files = {}
for path in scan_files(root):
relative_path = str(path.relative_to(root)).replace("\\", "/")
info = {
all_files[relative_path] = {
"size": path.stat().st_size,
"sha256": sha256_file(path),
}
flat_files[relative_path] = info
set_nested_file(tree["children"], relative_path, info)
def make_manifest(file_map: dict, core_files: list[str], removals: list[str],
remove_directories: list[str], module_id: str = "") -> dict:
tree = {
"type": "directory",
"name": root.name,
"children": {},
}
for relative_path, info in file_map.items():
set_nested_file(tree["children"], relative_path, info)
remove_file_conflicts = [file for file in remove_files if file in flat_files]
if remove_file_conflicts:
raise ValueError(f"remove still contains current files: {', '.join(remove_file_conflicts)}")
core_file_set = set(core_files)
validate_config_files(root, core_files, "core")
missing_core = [file for file in core_files if file not in file_map]
if missing_core:
raise ValueError(
"core contains files outside this manifest: "
+ ", ".join(missing_core)
)
validate_relative_paths(removals, "remove")
validate_relative_paths(remove_directories, "removeDirectories")
conflicts = [file for file in removals if file in file_map]
if conflicts:
raise ValueError(f"remove still contains current files: {', '.join(conflicts)}")
directory_conflicts = [
directory for directory in remove_directories
if any(file == directory or file.startswith(directory + "/")
for file in file_map)
]
if directory_conflicts:
raise ValueError(
"removeDirectories still contain current files: "
+ ", ".join(directory_conflicts)
)
remove_directory_conflicts = [
directory for directory in remove_directories
if any(file == directory or file.startswith(f"{directory}/") for file in flat_files)
]
if remove_directory_conflicts:
raise ValueError(
"removeDirectories still contain current files: "
+ ", ".join(remove_directory_conflicts)
)
folder_digest = hashlib.sha256()
for relative_path in sorted(file_map):
info = file_map[relative_path]
folder_digest.update(relative_path.encode("utf-8"))
folder_digest.update(str(info["size"]).encode("ascii"))
folder_digest.update(info["sha256"].encode("ascii"))
folder_digest = hashlib.sha256()
for relative_path in sorted(flat_files):
info = flat_files[relative_path]
folder_digest.update(relative_path.encode("utf-8"))
folder_digest.update(str(info["size"]).encode("ascii"))
folder_digest.update(info["sha256"].encode("ascii"))
result = {
"version": version,
"generated_at": datetime.now(timezone.utc).isoformat(),
"algorithm": "sha256",
"update_channels": True,
"file_count": len(file_map),
"size_bytes": sum(info["size"] for info in file_map.values()),
"folder_sha256": folder_digest.hexdigest(),
"core": core_files,
"assets": [file for file in sorted(file_map) if file not in core_file_set],
"remove": removals,
"removeDirectories": remove_directories,
"files": file_map,
"tree": tree,
}
if module_id:
result["module_id"] = module_id
return result
return {
"version": version,
"generated_at": datetime.now(timezone.utc).isoformat(),
"algorithm": "sha256",
"update_channels": True,
"file_count": len(flat_files),
"folder_sha256": folder_digest.hexdigest(),
"core": core_files,
"assets": [file for file in sorted(flat_files) if file not in core_file_set],
"remove": remove_files,
"removeDirectories": remove_directories,
"files": flat_files,
"tree": tree,
module_files = {name: {} for name in module_configs}
base_files = {}
for path, info in all_files.items():
owner = next((name for name, module_root in module_roots.items()
if path == module_root or path.startswith(module_root + "/")), None)
if owner:
module_files[owner][path] = info
else:
base_files[path] = info
base_manifest = make_manifest(
base_files, config["core"], config["remove"], config["removeDirectories"]
)
base_manifest["modules"] = {
name: {
"title": item["title"],
"entry": item["entry"],
"manifest": f"dist/modules/{name}.json",
"file_count": len(module_files[name]),
"size_bytes": sum(info["size"] for info in module_files[name].values()),
}
for name, item in module_configs.items()
}
manifests = {}
legacy_manifests = {}
for name, item in module_configs.items():
files = module_files[name]
if item["entry"] not in files:
raise FileNotFoundError(f"module entry is missing: {item['entry']}")
manifests[name] = make_manifest(
files, [item["entry"]], [], [], module_id=name
)
manifests[name]["assets"] = [
file for file in sorted(files) if file != item["entry"]
]
if not item["entry"].startswith(item["root"] + "/"):
raise ValueError(f"module entry is outside its root: {item['entry']}")
previous_files = previous_manifest.get("files", {}) \
if isinstance(previous_manifest, dict) else {}
legacy_files = set(item["legacy_files"])
legacy_files.update(module_files[name])
legacy_files.update(
file for file in previous_files
if isinstance(file, str) and file.startswith(item["root"] + "/")
)
legacy_files = sorted(legacy_files)
if legacy_files:
validate_relative_paths(list(legacy_files), "legacy module files")
if any(not file.startswith(item["root"] + "/")
for file in legacy_files):
raise ValueError(f"legacy files escape module root: {name}")
legacy_manifests[name] = {
"version": version,
"module_id": name,
"snapshot": "legacy",
"files": legacy_files,
}
base_manifest["modules"][name]["legacy_manifest"] = (
f"dist/modules/{name}.legacy.json"
)
return base_manifest, manifests, legacy_manifests
def main() -> None:
parser = argparse.ArgumentParser(description="Generate shuying manifest.json")
@@ -194,10 +317,37 @@ def main() -> None:
raise ValueError("Version cannot be empty")
output = (root / args.out).resolve()
previous_manifest = None
if output.is_file():
with output.open("r", encoding="utf-8") as file:
previous_manifest = json.load(file)
config = preserve_removals(load_config(root, args.config), output)
manifest = build_manifest(root, version, config)
manifest, modules, legacy_modules = build_manifest(
root, version, config, previous_manifest
)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
module_output = output.parent / "modules"
for name, module_manifest in modules.items():
module_path = module_output / f"{name}.json"
module_path.parent.mkdir(parents=True, exist_ok=True)
module_path.write_text(
json.dumps(module_manifest, ensure_ascii=False, indent=2),
encoding="utf-8",
)
for name, module_manifest in legacy_modules.items():
module_path = module_output / f"{name}.legacy.json"
module_path.parent.mkdir(parents=True, exist_ok=True)
module_path.write_text(
json.dumps(module_manifest, ensure_ascii=False, indent=2),
encoding="utf-8",
)
if module_output.is_dir():
expected = {f"{name}.json" for name in modules}
expected.update(f"{name}.legacy.json" for name in legacy_modules)
for stale in module_output.glob("*.json"):
if stale.name not in expected:
stale.unlink()
print(f"version: {version}")
print(f"file_count: {manifest['file_count']}")
@@ -207,6 +357,8 @@ def main() -> None:
print(f"remove_directory_count: {len(manifest['removeDirectories'])}")
print(f"folder_sha256: {manifest['folder_sha256']}")
print(f"generated: {output}")
for name, module_manifest in modules.items():
print(f"module_{name}_file_count: {module_manifest['file_count']}")
if __name__ == "__main__":
+61
View File
@@ -0,0 +1,61 @@
[
"mengsan/assets/flyconid-portrait.png",
"mengsan/assets/intent/Intent_attack_1.webp",
"mengsan/assets/intent/Intent_attack_2.webp",
"mengsan/assets/intent/Intent_attack_3.webp",
"mengsan/assets/intent/Intent_attack_4.webp",
"mengsan/assets/intent/Intent_attack_5.webp",
"mengsan/assets/intent/Intent_debuff.webp",
"mengsan/assets/sushuang-zhangshiping.png",
"mengsan/config.js",
"mengsan/content/acts/act1/index.js",
"mengsan/content/acts/act1/map.js",
"mengsan/content/acts/act1/rewards.js",
"mengsan/content/acts/act1/stories/forest-ambush.js",
"mengsan/content/acts/act1/stories/liubei-opening.js",
"mengsan/content/acts/act2/index.js",
"mengsan/content/acts/act2/map.js",
"mengsan/content/acts/act3/index.js",
"mengsan/content/acts/act3/map.js",
"mengsan/content/affixes.js",
"mengsan/content/card-definitions.js",
"mengsan/content/card-library.js",
"mengsan/content/mode-cards.js",
"mengsan/content/registry.js",
"mengsan/content/scenario-characters.js",
"mengsan/content/shared/index.js",
"mengsan/content/shared/rewards.js",
"mengsan/docs/battle-config.md",
"mengsan/docs/combat-rules.md",
"mengsan/docs/liubei-opening.md",
"mengsan/map/index.js",
"mengsan/map/renderer.js",
"mengsan/mode.js",
"mengsan/register.js",
"mengsan/runtime/battle-director.js",
"mengsan/runtime/battle-flow.js",
"mengsan/runtime/battle-loop.js",
"mengsan/runtime/battle-resources.js",
"mengsan/runtime/battle-session.js",
"mengsan/runtime/battle-settlement.js",
"mengsan/runtime/card-data.js",
"mengsan/runtime/card-library.js",
"mengsan/runtime/combat-rules.js",
"mengsan/runtime/dialogue-choice.js",
"mengsan/runtime/dialogue.js",
"mengsan/runtime/engine-session.js",
"mengsan/runtime/flow-ui.js",
"mengsan/runtime/flyconid-intent.js",
"mengsan/runtime/gm-manager.js",
"mengsan/runtime/intent-display.js",
"mengsan/runtime/mode-storage.js",
"mengsan/runtime/monster.js",
"mengsan/runtime/navigation.js",
"mengsan/runtime/personal-piles.js",
"mengsan/runtime/reward-ui.js",
"mengsan/runtime/reward.js",
"mengsan/runtime/skill-teardown.js",
"mengsan/runtime/story.js",
"mengsan/state.js",
"mengsan/style.css"
]
+9 -5
View File
@@ -4,10 +4,6 @@
"menu.js",
"function.js",
"update.js",
"mengsan/mode.js",
"mengsan/config.js",
"mengsan/state.js",
"mengsan/style.css",
"tianshu/extension.js",
"tianshu/config.js",
"pve/boss/index.js",
@@ -79,5 +75,13 @@
"pve/boss/sets/tianshu/voices.js"
],
"remove": [],
"removeDirectories": []
"removeDirectories": [],
"modules": {
"mengsan": {
"root": "mengsan",
"entry": "mengsan/register.js",
"title": "梦三模式",
"legacy_files_from": "tools/legacy/mengsan-files.json"
}
}
}
+443 -40
View File
@@ -1,6 +1,8 @@
import { lib, game } from "../../noname.js";
const repositoryApi = "https://gitea.diuse.work/api/v1/repos/Diuse/noname-shuying";
const giteaRepositoryApi = "https://gitea.diuse.work/api/v1/repos/Diuse/noname-shuying";
const githubRepositoryApi = "https://api.github.com/repos/Shu-Ying/noname-shuying";
const githubRawBase = "https://raw.githubusercontent.com/Shu-Ying/noname-shuying";
const coreTempDir = "extension/术樱包/.update_tmp";
function parseVersion(version) {
@@ -30,15 +32,25 @@ function getUpdateChannel() {
? "preview" : "stable");
}
function getRemoteUrl(tag, path) {
const filePath = path.split("/").map(encodeURIComponent).join("/");
return `${repositoryApi}/raw/${filePath}?ref=${encodeURIComponent(tag)}`;
function getUpdateSource() {
return lib.config.shuYing_update_source == "github" ? "github" : "gitea";
}
async function getLatestTag(channel = getUpdateChannel()) {
function getRemoteUrl(tag, path, source = getUpdateSource()) {
const filePath = path.split("/").map(encodeURIComponent).join("/");
if (source == "github") {
return `${githubRawBase}/${encodeURIComponent(tag)}/${filePath}`;
}
return `${giteaRepositoryApi}/raw/${filePath}?ref=${encodeURIComponent(tag)}`;
}
async function getLatestTag(channel = getUpdateChannel(), source = getUpdateSource()) {
let latest = null;
for (let page = 1; ; page++) {
const response = await fetch(`${repositoryApi}/tags?page=${page}&limit=50`);
const tagsUrl = source == "github"
? `${githubRepositoryApi}/tags?page=${page}&per_page=50`
: `${giteaRepositoryApi}/tags?page=${page}&limit=50`;
const response = await fetch(tagsUrl);
if (!response.ok) throw new Error(`标签请求失败:${response.status}`);
const tags = await response.json();
if (!Array.isArray(tags)) throw new Error("标签列表格式错误");
@@ -55,7 +67,7 @@ async function getLatestTag(channel = getUpdateChannel()) {
}
if (tags.length < 50) break;
}
if (!latest) throw new Error(`Gitea 镜像尚无${channel == "preview" ? "测试版" : "正式版"}标签`);
if (!latest) throw new Error(`更新源尚无${channel == "preview" ? "测试版" : "正式版"}标签`);
return latest;
}
@@ -153,6 +165,12 @@ function escapeHTML(text) {
}[char]));
}
function formatBytes(bytes) {
const value = Math.max(0, Number(bytes) || 0);
if (value < 1024 * 1024) return `${Math.ceil(value / 1024)} KB`;
return `${(value / 1024 / 1024).toFixed(1)} MB`;
}
function setProgress(shuYing, options = {}) {
if (!shuYing?.text) return;
@@ -192,8 +210,8 @@ function splitPath(path) {
};
}
async function fetchFile(path, tag) {
const response = await fetch(getRemoteUrl(tag, path));
async function fetchFile(path, tag, source) {
const response = await fetch(getRemoteUrl(tag, path, source));
if (!response.ok) throw new Error(`${path} 下载失败:${response.status}`);
return await response.arrayBuffer();
@@ -209,7 +227,7 @@ async function writeTargetFile(data, target) {
}
async function downloadFile(path, target, manifest) {
const data = await fetchFile(path, manifest.tag_name);
const data = await fetchFile(path, manifest.tag_name, manifest.source);
if (manifest?.files?.[path]) {
await verifyFile(path, data, manifest);
}
@@ -217,22 +235,35 @@ async function downloadFile(path, target, manifest) {
return data;
}
async function getManifestFromTag(tag, requireChannels = true) {
const response = await fetch(getRemoteUrl(tag.name, "dist/manifest.json"));
async function getManifestFromTag(tag, requireChannels = true,
source = getUpdateSource()) {
const response = await fetch(getRemoteUrl(tag.name, "dist/manifest.json", source));
if (!response.ok) throw new Error(`校验清单请求失败:${response.status}`);
const manifest = await response.json();
if (requireChannels && manifest?.update_channels !== true) {
throw new Error("目标标签尚未包含新版更新器,请发布支持通道切换的版本");
}
validateManifest(manifest, tag.version);
manifest.tag_name = tag.name;
manifest.source = source;
return manifest;
}
function validateManifest(manifest, version, moduleId = "") {
if (!manifest || manifest.algorithm != "sha256"
|| !manifest.files || Array.isArray(manifest.files)
|| typeof manifest.files != "object"
|| manifest.version != tag.version) {
|| manifest.version != version
|| (moduleId && manifest.module_id != moduleId)) {
throw new Error("校验清单格式错误");
}
const files = getManifestFileKeys(manifest);
if (moduleId && files.some(file => !file.startsWith(`${moduleId}/`))) {
throw new Error(`校验清单包含越界的 ${moduleId} 模块文件`);
}
if (!files.length || files.some(file => {
const info = manifest.files[file];
return !info || !Number.isSafeInteger(info.size) || info.size < 0
@@ -244,13 +275,34 @@ async function getManifestFromTag(tag, requireChannels = true) {
getManifestAssetFiles(manifest, coreFiles);
getManifestRemoveFiles(manifest);
getManifestRemoveDirectories(manifest);
manifest.tag_name = tag.name;
return manifest;
}
async function getManifest(channel = getUpdateChannel()) {
return getManifestFromTag(await getLatestTag(channel));
async function getModuleManifest(tag, rootManifest, moduleId,
source = rootManifest?.source || getUpdateSource()) {
const descriptor = rootManifest?.modules?.[moduleId];
if (!descriptor || !isSafeManifestPath(descriptor.manifest)) {
throw new Error(`更新清单未提供 ${moduleId} 模块`);
}
if (typeof descriptor.entry != "string"
|| !isSafeManifestPath(descriptor.entry)
|| !descriptor.entry.startsWith(`${moduleId}/`)) {
throw new Error(`${moduleId} 模块入口配置无效`);
}
const response = await fetch(getRemoteUrl(tag.name, descriptor.manifest, source));
if (!response.ok) throw new Error(`${moduleId} 模块清单请求失败:${response.status}`);
const manifest = await response.json();
validateManifest(manifest, tag.version, moduleId);
if (!manifest.files[descriptor.entry]) {
throw new Error(`${moduleId} 模块清单缺少入口文件`);
}
manifest.tag_name = tag.name;
manifest.source = source;
return manifest;
}
async function getManifest(channel = getUpdateChannel(), source = getUpdateSource()) {
return getManifestFromTag(await getLatestTag(channel, source), true, source);
}
function normalizeManifestPath(path) {
@@ -595,6 +647,89 @@ async function getChangedFiles(manifest) {
return changed;
}
function makeLegacyModuleManifest(manifest, moduleId) {
const prefix = `${moduleId}/`;
const files = Object.fromEntries(Object.entries(manifest.files || {})
.filter(([file]) => file.startsWith(prefix)));
if (!Object.keys(files).length) return null;
const entry = `${moduleId}/register.js`;
return {
...manifest,
module_id: moduleId,
files,
core: files[entry] ? [entry] : [],
assets: Object.keys(files).filter(file => file != entry),
remove: [],
removeDirectories: [],
};
}
async function getInstalledModuleManifest(moduleId, version, source) {
const tag = { name: `v${version}`, version };
const oldRoot = await getManifestFromTag(tag, false, source);
if (oldRoot.modules?.[moduleId]) {
return await getModuleManifest(tag, oldRoot, moduleId, source);
}
return makeLegacyModuleManifest(oldRoot, moduleId);
}
async function getLegacyModuleManifest(moduleId, rootManifest) {
const path = rootManifest?.modules?.[moduleId]?.legacy_manifest;
if (!path) return null;
if (!isSafeManifestPath(path)) {
throw new Error(`${moduleId} 迁移清单路径无效`);
}
const response = await fetch(getRemoteUrl(
rootManifest.tag_name, path, rootManifest.source
));
if (!response.ok) throw new Error(`${moduleId} 迁移清单请求失败:${response.status}`);
const snapshot = await response.json();
if (snapshot.version != rootManifest.version
|| snapshot.module_id != moduleId
|| snapshot.snapshot != "legacy"
|| !Array.isArray(snapshot.files)) {
throw new Error(`${moduleId} 迁移清单格式错误`);
}
const files = uniqueManifestList(snapshot.files);
if (files.some(file => !file.startsWith(`${moduleId}/`))) {
throw new Error(`${moduleId} 迁移清单包含越界文件`);
}
return { files: Object.fromEntries(files.map(file => [file, {}])) };
}
async function isMengsanInstalled(localVersion, previousManifest,
currentManifest) {
const saved = lib.config.shuYing_mengsan_installed_version;
if (saved == "disabled") return false;
if (saved) return true;
const entryPath = "extension/术樱包/mengsan/register.js";
if (typeof game.checkFile == "function"
&& await safeCheckFile(entryPath) == 1) {
return true;
}
if (typeof game.checkFile != "function" && typeof game.readFile == "function") {
try {
await readFile(entryPath);
return true;
}
catch (error) { }
}
const oldManifest = previousManifest || (parseVersion(localVersion)
? await getManifestFromTag({
name: `v${localVersion}`, version: localVersion,
}, false, currentManifest.source).catch(() => null)
: null);
return !!oldManifest?.files?.["mengsan/register.js"];
}
function mergeRemovedFiles(manifest, oldFiles, retainedFiles = []) {
const current = new Set(getManifestFileKeys(manifest));
const retained = new Set(retainedFiles);
manifest.remove = [...new Set([...(manifest.remove || []),
...oldFiles.filter(file => !current.has(file) && !retained.has(file))])];
getManifestRemoveFiles(manifest);
}
async function getObsoleteFiles(manifest) {
const existing = [];
for (const file of getManifestRemoveFiles(manifest)) {
@@ -621,13 +756,15 @@ async function updateAllFiles(shuYing, manifest, files) {
const oldRoot = `${coreTempDir}/old`;
const backedUp = new Set();
const installed = [];
const obsoleteBackups = [];
const obsoleteFiles = getManifestRemoveFiles(manifest);
let filesInstalled = false;
try {
ensureProgressNode(shuYing);
await createDir(`${newRoot}/`);
await createDir(`${oldRoot}/`);
await createFolders(`${newRoot}/`, files);
await createFolders(`${oldRoot}/`, files);
await createFolders(`${oldRoot}/`, [...files, ...obsoleteFiles]);
for (let i = 0; i < files.length; i++) {
const file = files[i];
@@ -658,11 +795,25 @@ async function updateAllFiles(shuYing, manifest, files) {
installed.push(file);
await writeTargetFile(await readFile(`${newRoot}/${file}`), target);
}
filesInstalled = true;
for (const file of obsoleteFiles) {
const target = `extension/术樱包/${file}`;
try {
const original = await readFile(target);
await writeTargetFile(original, `${oldRoot}/${file}`);
backedUp.add(file);
obsoleteBackups.push(file);
}
catch (error) {
if (await safeCheckFile(target) == 1) throw error;
}
}
await removeManifestOldPaths(shuYing, manifest);
filesInstalled = true;
}
catch (error) {
for (const file of filesInstalled ? [] : installed.reverse()) {
const rollbackFiles = filesInstalled ? []
: [...installed, ...obsoleteBackups].reverse();
for (const file of rollbackFiles) {
const target = `extension/术樱包/${file}`;
try {
if (backedUp.has(file)) {
@@ -679,7 +830,7 @@ async function updateAllFiles(shuYing, manifest, files) {
throw error;
}
finally {
for (const file of files) {
for (const file of new Set([...files, ...backedUp])) {
await removeFile(`${newRoot}/${file}`);
if (backedUp.has(file)) await removeFile(`${oldRoot}/${file}`);
}
@@ -727,8 +878,9 @@ async function downloadList(shuYing, files, manifest) {
}
}
async function getOnlineVersion(channel = getUpdateChannel()) {
const manifest = await getManifest(channel);
async function getOnlineVersion(channel = getUpdateChannel(),
source = getUpdateSource()) {
const manifest = await getManifest(channel, source);
return { online_version: manifest.version, manifest };
}
@@ -736,48 +888,131 @@ async function checkVersion(shuYing, options = {}) {
try {
shuYing._updateLogs = [];
await addLog(shuYing, "版本检查开始");
const onlineVersion = await getOnlineVersion(options.channel);
const onlineVersion = await getOnlineVersion(options.channel, options.source);
const localVersion = lib.config.shuYing_local_version || "0.0.0.0";
const manifest = onlineVersion.manifest;
if (!options.switchChannel && parseVersion(localVersion)
&& compareVersions(onlineVersion.online_version, localVersion) < 0) {
throw new Error("Gitea 镜像尚未同步到本地版本,请稍后重试");
throw new Error("目标更新源的版本落后于本地版本,请稍后重试");
}
if (options.switchChannel && parseVersion(localVersion)
&& localVersion != manifest.version) {
const previous = await getManifestFromTag({
name: `v${localVersion}`,
version: localVersion,
}, false);
const targetFiles = new Set(getManifestFileKeys(manifest));
const removed = getManifestFileKeys(previous)
.filter(file => !targetFiles.has(file));
manifest.remove = [...new Set([...(manifest.remove || []), ...removed])];
getManifestRemoveFiles(manifest);
let previousManifest = null;
if (parseVersion(localVersion) && localVersion != manifest.version) {
previousManifest = await getManifestFromTag({
name: `v${localVersion}`, version: localVersion,
}, false, manifest.source).catch(error => {
console.warn("读取本地旧版清单失败,跳过旧文件差集清理:", error);
return null;
});
}
const installedMengsan = await isMengsanInstalled(
localVersion, previousManifest, manifest
);
if (installedMengsan
&& !lib.config.shuYing_mengsan_installed_version
&& parseVersion(localVersion)) {
game.saveConfig("shuYing_mengsan_installed_version",
localVersion == manifest.version ? "legacy" : localVersion);
}
if (previousManifest) {
const retainedModuleFiles = manifest.modules?.mengsan
? getManifestFileKeys(previousManifest)
.filter(file => file.startsWith("mengsan/"))
: [];
mergeRemovedFiles(
manifest,
getManifestFileKeys(previousManifest),
retainedModuleFiles
);
}
const changed = await getChangedFiles(manifest);
const obsolete = await getObsoleteFiles(manifest);
await addLog(shuYing, `Gitea 标签:${manifest.tag_name};待更新文件:${changed.length};待删除文件:${obsolete.length}`);
let mengsanManifest = null;
let mengsanChanged = [];
let mengsanObsolete = [];
let mengsanUpdateError = null;
let previousMengsan = null;
if (installedMengsan && manifest.modules?.mengsan) {
try {
mengsanManifest = await getModuleManifest({
name: manifest.tag_name, version: manifest.version,
}, manifest, "mengsan");
const installedModuleVersion =
lib.config.shuYing_mengsan_installed_version;
if (installedModuleVersion
&& installedModuleVersion != "disabled"
&& parseVersion(installedModuleVersion)
&& installedModuleVersion != manifest.version) {
previousMengsan = await getInstalledModuleManifest(
"mengsan", installedModuleVersion, manifest.source
);
}
else if (previousManifest && previousManifest.modules?.mengsan) {
previousMengsan = await getModuleManifest({
name: `v${localVersion}`, version: localVersion,
}, previousManifest, "mengsan", manifest.source);
}
else if (previousManifest) {
previousMengsan = makeLegacyModuleManifest(
previousManifest, "mengsan"
);
}
if (!previousMengsan
&& (!installedModuleVersion || installedModuleVersion == "legacy")) {
previousMengsan = await getLegacyModuleManifest(
"mengsan", manifest
);
}
if (previousMengsan) {
mergeRemovedFiles(
mengsanManifest,
getManifestFileKeys(previousMengsan)
);
}
mengsanChanged = await getChangedFiles(mengsanManifest);
mengsanObsolete = await getObsoleteFiles(mengsanManifest);
}
catch (error) {
mengsanUpdateError = error;
await addLog(shuYing, `梦三模块更新暂不可用:${getErrorMessage(error)}`);
}
}
const allChangedCount = changed.length + mengsanChanged.length;
const allObsoleteCount = obsolete.length + mengsanObsolete.length;
await addLog(shuYing, `更新源:${manifest.source};标签:${manifest.tag_name};待更新文件:${allChangedCount};待删除文件:${allObsoleteCount}`);
if (localVersion == onlineVersion.online_version
&& !changed.length && !obsolete.length) {
&& !allChangedCount && !allObsoleteCount && !mengsanUpdateError) {
game.saveConfig("shuYing_online_version", onlineVersion.online_version);
alert("本地版本为最新版");
return onlineVersion.online_version;
}
const message = localVersion == onlineVersion.online_version
? `当前版本有 ${changed.length} 个文件需修复、${obsolete.length} 个旧文件需删除,是否继续?`
? `当前版本有 ${allChangedCount} 个文件需修复、${allObsoleteCount} 个旧文件需删除,是否继续?`
: `检测到最新版本为:${onlineVersion.online_version}, 本地版本为:${localVersion},是否更新?`;
if (!options.switchChannel && !confirm(message)) {
return null;
}
await updateAllFiles(shuYing, manifest, changed);
if (mengsanManifest && !mengsanUpdateError) {
try {
await updateAllFiles(shuYing, mengsanManifest, mengsanChanged);
game.saveConfig("shuYing_mengsan_installed_version", manifest.version);
}
catch (error) {
mengsanUpdateError = error;
await addLog(shuYing, `梦三模块更新失败:${getErrorMessage(error)}`);
}
}
game.saveConfig("shuYing_local_version", onlineVersion.online_version);
game.saveConfig("shuYing_online_version", onlineVersion.online_version);
await addLog(shuYing, "版本更新完成");
alert("下载完成,重启生效");
alert(mengsanUpdateError
? "主包更新完成;梦三模块未完成更新,可稍后重试。"
: "下载完成,重启生效");
return onlineVersion.online_version;
}
catch (error) {
@@ -806,6 +1041,69 @@ async function repairMissingFiles(shuYing) {
setProgress(shuYing, { title: "查漏补缺", status: "获取校验清单", current: 0, total: 1 });
const manifest = await getManifest();
const files = getManifestDownloadFiles(manifest);
const localVersion = lib.config.shuYing_local_version || "0.0.0.0";
let previousManifest = null;
if (parseVersion(localVersion) && localVersion != manifest.version) {
previousManifest = await getManifestFromTag({
name: `v${localVersion}`, version: localVersion,
}, false, manifest.source).catch(() => null);
if (previousManifest) {
const retainedModuleFiles = manifest.modules?.mengsan
? getManifestFileKeys(previousManifest)
.filter(file => file.startsWith("mengsan/"))
: [];
mergeRemovedFiles(
manifest,
getManifestFileKeys(previousManifest),
retainedModuleFiles
);
}
}
const installedMengsan = await isMengsanInstalled(
localVersion, previousManifest, manifest
);
let mengsanManifest = null;
let previousMengsan = null;
if (installedMengsan && manifest.modules?.mengsan) {
mengsanManifest = await getModuleManifest({
name: manifest.tag_name, version: manifest.version,
}, manifest, "mengsan");
const installedModuleVersion =
lib.config.shuYing_mengsan_installed_version;
if (installedModuleVersion == "legacy") {
previousMengsan = await getLegacyModuleManifest(
"mengsan", manifest
);
}
else if (installedModuleVersion
&& parseVersion(installedModuleVersion)
&& installedModuleVersion != manifest.version) {
previousMengsan = await getInstalledModuleManifest(
"mengsan", installedModuleVersion, manifest.source
);
}
else if (previousManifest?.modules?.mengsan) {
previousMengsan = await getModuleManifest({
name: `v${localVersion}`, version: localVersion,
}, previousManifest, "mengsan", manifest.source);
}
else if (previousManifest) {
previousMengsan = makeLegacyModuleManifest(
previousManifest, "mengsan"
);
}
else if (!installedModuleVersion) {
previousMengsan = await getLegacyModuleManifest(
"mengsan", manifest
);
}
if (previousMengsan) {
mergeRemovedFiles(
mengsanManifest,
getManifestFileKeys(previousMengsan)
);
}
}
await addLog(shuYing, `待检查文件数:${files.length}`);
await addLog(shuYing, `校验清单版本:${manifest.version || "未知"};清单文件数:${Object.keys(manifest.files || {}).length}`);
@@ -815,6 +1113,11 @@ async function repairMissingFiles(shuYing) {
await downloadList(shuYing, files, manifest);
await removeManifestOldPaths(shuYing, manifest);
if (mengsanManifest) {
const moduleChanged = await getChangedFiles(mengsanManifest);
await updateAllFiles(shuYing, mengsanManifest, moduleChanged);
game.saveConfig("shuYing_mengsan_installed_version", manifest.version);
}
setProgress(shuYing, { title: "查漏补缺", status: "完成", current: files.length, total: files.length });
await addLog(shuYing, "查漏补缺完成");
@@ -831,6 +1134,104 @@ async function repairMissingFiles(shuYing) {
}
}
async function manageMengsanModule(shuYing) {
setBusy(shuYing, true);
try {
shuYing._updateLogs = [];
const localVersion = lib.config.shuYing_local_version || "0.0.0.0";
const rootManifest = await getManifest();
const installed = await isMengsanInstalled(
localVersion, null, rootManifest
);
if (installed) {
if (!confirm("确认卸载梦三模式?只删除梦三模块清单拥有的文件。")) return;
let moduleManifest;
const moduleVersion = lib.config.shuYing_mengsan_installed_version;
if (moduleVersion == "legacy" || !moduleVersion) {
const legacyManifest = await getLegacyModuleManifest(
"mengsan", rootManifest
).catch(() => null);
const currentManifest = await getModuleManifest({
name: rootManifest.tag_name, version: rootManifest.version,
}, rootManifest, "mengsan");
let localManifest = null;
if (parseVersion(localVersion)
&& localVersion != rootManifest.version) {
localManifest = await getInstalledModuleManifest(
"mengsan", localVersion, rootManifest.source
).catch(() => null);
}
moduleManifest = {
files: Object.fromEntries([...new Set([
...getManifestFileKeys(legacyManifest || { files: {} }),
...getManifestFileKeys(localManifest || { files: {} }),
...getManifestFileKeys(currentManifest),
])].map(file => [file, {}])),
};
}
else if (parseVersion(moduleVersion || "")) {
moduleManifest = await getInstalledModuleManifest(
"mengsan", moduleVersion, rootManifest.source
).catch(async error => {
await addLog(shuYing, `读取已安装模块清单失败:${getErrorMessage(error)}`);
return null;
});
}
if (!moduleManifest && parseVersion(localVersion)) {
moduleManifest = await getInstalledModuleManifest(
"mengsan", localVersion, rootManifest.source
).catch(() => null);
}
if (!moduleManifest) {
moduleManifest = await getModuleManifest({
name: rootManifest.tag_name, version: rootManifest.version,
}, rootManifest, "mengsan");
}
const files = getManifestFileKeys(moduleManifest);
if (typeof game.removeFile != "function") {
throw new Error("当前环境不支持安全卸载文件");
}
for (const file of files) {
await addLog(shuYing, `卸载梦三文件:${file}`);
await removeFile(`extension/术樱包/${file}`);
if (typeof game.checkFile == "function"
&& await safeCheckFile(`extension/术樱包/${file}`) == 1) {
throw new Error(`梦三文件删除失败:${file}`);
}
}
game.saveConfig("shuYing_mengsan_installed_version", "disabled");
alert("梦三模式文件已卸载,请重启游戏生效。");
return;
}
const moduleInfo = rootManifest.modules?.mengsan;
const sizeText = moduleInfo?.size_bytes
? `,约 ${formatBytes(moduleInfo.size_bytes)}` : "";
if (!confirm(`梦三模式尚未安装,是否下载并校验全部梦三资源${sizeText}?`)) return;
const moduleManifest = await getModuleManifest({
name: rootManifest.tag_name, version: rootManifest.version,
}, rootManifest, "mengsan");
const files = getManifestFileKeys(moduleManifest);
ensureProgressNode(shuYing);
setProgress(shuYing, {
title: "安装梦三模式", status: "准备下载", current: 0,
total: files.length * 2,
});
await updateAllFiles(shuYing, moduleManifest, files);
game.saveConfig("shuYing_mengsan_installed_version", rootManifest.version);
alert("梦三模式下载完成,请重启游戏生效。");
}
catch (error) {
console.error(error);
await addLog(shuYing, `梦三模块操作失败:${getErrorMessage(error)}`);
alert("梦三模式操作失败,请检查网络或 extension/术樱包/log.txt。");
}
finally {
removeProgressNode(shuYing);
setBusy(shuYing, false);
}
}
async function repairCoreFiles(shuYing) {
let shouldDownload = false;
let manifest;
@@ -885,7 +1286,9 @@ async function repairCoreFiles(shuYing) {
export default {
getOnlineVersion,
getUpdateChannel,
getUpdateSource,
checkVersion,
repairMissingFiles,
repairCoreFiles,
manageMengsanModule,
};