From 4fd7a6613064cf771c3381eb21e0d7f6792e5036 Mon Sep 17 00:00:00 2001 From: nukcole Date: Wed, 11 Nov 2026 02:07:38 +0800 Subject: [PATCH 1/3] Install rule packs from the public games repo; New game offers installed packs (RPG R7) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vdVgYTb9jm7MRdePSgs8B --- CHANGELOG.md | 1 + CLAUDE.md | 1 + docs/rpg-engine-prd.md | 1 + packs/dungeon-crawl/system.md | 2 + packs/narrative-check/system.md | 2 + packs/turn-battle/rules.ink | 3 +- packs/turn-battle/system.md | 2 + .../turn-battle/\350\257\264\346\230\216.md" | 2 +- src/api.ts | 15 +- src/game/system.ts | 4 +- src/i18n.ts | 20 ++ src/main.ts | 185 ++++++++++++++++-- src/templates/install.ts | 109 +++++++++++ tests/install.test.ts | 67 +++++++ tests/system.test.ts | 2 + 15 files changed, 396 insertions(+), 20 deletions(-) create mode 100644 src/templates/install.ts create mode 100644 tests/install.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b9dcc0..317ac23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Release notes for each version; the GitHub release carries the same text and the ## Unreleased +- New command "Install rule pack (download)": lists the rule packs published in the public games repo (luoxin9510/ink-games, `systems/`), asks before downloading, then writes the chosen pack into `规则包//` / `Rule packs//` (files of the same names are overwritten, others kept; nothing is written when a download fails). "New game" also offers packs installed in the vault, not only the bundled ones. A pack's `system.md` now lists its files (`files:`). `api.availablePacks()`, `api.installPack(id)`. - Two more rule packs (RPG R6), both in "New game". **Turn battle**: a knight, a mage and a cleric against a band of foes, everyone acting once a round by speed; attacks, arts (shield bash stuns, fireball hits every foe, mend heals and cures), guarding, potions, poison and stun; the story spawns the foes and calls `-> battle ->`, then reads `battle_result`. **Narrative checks**: the rules of the dorm horror game *302* (2d6 checks on choices, six difficulties, five skills that speak as inner voices, fear and stamina, companions' fear and trust, fear lowering reason) plus `clamp()`; a game adds its own characters, resources and items. - Levels and campaigns (RPG R5). `levels: { resource: xp, at: [0, 4, 10] }` gives the story `level`, `next_level_at()`, `level_up_ready()` and `level_up()`; the status bar shows the level and marks when one can be taken. Perks are ordinary items. A line tagged `#sheet` (or the command "Save character sheet", `api.saveSheet()`) writes the character being played as a note in the game's `sheets:` folder: its frontmatter is a `characters` entry (skills, items, what is worn, counts, level, resources, statuses), its body gets the adventure's epilogue. The next adventure reads such notes with `characters: { from: ../角色 }`. Characters written in `game.md` can also set `equipped`, `level`, `resources` and `statuses`. diff --git a/CLAUDE.md b/CLAUDE.md index 660636c..6612900 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,6 +47,7 @@ PRD: `docs/game-engine-prd.md` — TTRPG-style rules engine on top of Inkwright - RPG R4 stacks, slots, statuses: `ItemDef.stack` (count VAR ``, `_n`; `inkgen stackInk`: `give(item, n)`/`take(item, n)` → taken/`inv_count(item)`, list-item arguments, the inventory follows the count; non-stacking items: give adds, take removes one, count 0/1), `CharacterDef.counts` (set in `pick_character`, also carried); `slots: SlotDef[]` + `ItemDef.slot` (`slotInk`: `VAR equipped`, `equip` drops the slot's other items and carries it, `unequip`; `pick_character` equips the first carried item per slot; character only); `collectModifiers` counts a slotted item only while equipped and carried, and the character's own statuses' `modifiers`. `statuses: StatusDef[]` (name, desc, modifiers, `rest`): `src/game/statuses.ts` (pure store `who|id|turns;…`, turns ≤ 0 = until cleared, re-adding keeps the longer; tested in `tests/statuses.test.ts`), `statusInk` (`VAR statuses`, pure EXTERNALs `status_put/in/left/take/tick/rest` with no-engine fallbacks where nothing takes hold, wrappers `add_status(who, id, turns)`, `has_status`, `status_turns`, `clear_status` ("" = all of who's), `tick_statuses`, `rest_statuses`; who = an entity/member id or `InkNames.self` "me"/zh "我"), `GameEngine.bindStatuses`, `statusesOf` → `hud().statuses` (the character's), `PartyMemberView.statuses`, `EntityView.statuses`; `ItemView.count/equipped/slot`. Problems `itemSlot`, `statusSkill`, `countItem`; the new InkNames are reserved only when used (`amountParam` also with stacks). Panel: `status.ts itemChip`/`statusTags` (`.inkwright-item-equipped`, `.inkwright-status`); web `renderHud` `itemText`/`statusText`. Random runs: stack counts in `resources` (as `_n`, no top), `SimulateResult.statuses` (`StatusTally`: appearances between steps, runs). Tests: `tests/game-gear.test.ts`, the web gear test. - RPG R5 levels and sheets: `levels: LevelsDef` (`resource`, `at`; problems `levelsResource`, `levelsOrder`), `inkgen levelInk` (`VAR level`, `next_level_at`, `level_up_ready`, `level_up`; InkNames reserved only with levels), `hud().level` (`{ level, next, ready }`; panel `chipRow` + `.inkwright-level-ready`, web line). `CharacterDef.equipped/level/resources/statuses` (loaded by `pick_character`; `equipped` over the first carried item per slot; problems `characterLevel`, `characterResource`, `characterStatus`). `src/game/sheet.ts` (pure): `sheetOf(config, state, current)` (the played character as a `characters` entry; `GameEngine.sheet()`), `sheetName`, `sheetNote(yaml, oldBody, epilogue, title, date)` (frontmatter replaced, body kept, a section added), `characterFromNote` (uses `isCharacter` from config.ts). `main.ts`: `saveSheet(epilogue?)` (folder `sheets` relative to the story's, default `T().sheetsFolder`; refused outside the vault; the state read at once, the write queued with `runs.enqueue`; the character's sheet found by frontmatter id, else named by `sheetName`; `ownWrites` makes the change events of that file within `OWN_WRITE_MS` not trigger a recompile, since a camp reads the folder it writes; the engine still goes stale, which is right: the next play needs the new presets), the controller's `RunHost.afterChoose(paragraphs)` (called only after the player takes a choice, with the text it produced; a `#sheet` line there writes, so back/replay/load/language never do), command `save-sheet`, `api.saveSheet`. `characters: { from }` → `GameConfig.charactersFrom` (no `noCharacters` until resolved), `resolve.ts resolveCharacters` (first in `resolveConfig`; the folder and notes are dependencies; problem `charactersFolder`). Tests: `tests/campaign.test.ts`. - RPG R6 packs: `packs/turn-battle` (no engine changes: party + the `foe` kind; `battle` knot: rounds, `ready_all` clears `acted`, `next_actor` = the fastest standing one not yet acted, heroes first on ties (recursive `fastest` over `nth_one`); a hero's options are threads per foe/ally, a foe acts in `foe_turn`; stun/guard/poison statuses; damage atk + 2d6 - 4 - def; `battle_result`, `battle_round`; balance by a strategy bot: 2026-11-10 numbers in its `说明.md`) and `packs/narrative-check` (dorm-302's rules: difficulties, five voiced skills, fear/hp, companion fear/trust, the fear modifier; `rules.ink` = `clamp`). dorm-302 vendors a copy in `packs/narrative-check/`; its check-ink output was compared before and after the switch. `tests/system.test.ts` plays every template and a 3 on 3 round order. +- RPG R7 install: a pack's `system.md` lists its files (`files:`, pack paths; the template's `_engine.ink` left out; `tests/install.test.ts` checks every bundled pack; `layerSystem` drops `files`). `src/templates/install.ts` (pure: `PACK_SOURCE` = ink-games `systems/` raw URL, `parseIndex` of `systems/index.json`, `isPackId`, `isPackPath` (relative, no `..`/hidden/odd characters), `packFiles`, `packUrl`, `downloadPack(fetchText, source, id, frontmatter)` = system.md then each listed file, all or nothing). `main.ts`: `availablePacks`, `installPack(id, { ask, source })` (`ConfirmModal`, then `requestUrl`, writes into the installed copy's folder or `/`), command `install-pack` (`PackPickModal` shows the installed version); `packBundle()` = bundled packs plus vault-installed ones with a template (installed wins), used by `newGame`/`pickNewGame`. The packs in ink-games must match `packs/` (its build checks). - Tabletop PRD: `docs/tabletop-prd.md` — solo TTRPG / board-game support on top of game mode: five primitives (free rolls, random tables, decks, `#input`, play log to a note), what qualifies, the order to build them in. Read it before adding any of those. - Tabletop slice 1, dice and tables: `src/game/dice.ts` parses and rolls formulas (`parseFormula`, `rollFormula`; `d66` is two d6 read as tens and units); `src/game/tables.ts` is the table logic (ranges, the dice given or inferred, `rowAt`, `tableProblems` for gaps/overlaps/bad dice, `rowsFromMarkdown` for a note's first markdown table, `resolveTables` fills `from:` tables in and lists the notes read). The engine binds one more EXTERNAL, `roll_dice(formula, label)`, on the check's seed and roll counter; `roll(formula)`, `table_roll`, `table_text`, `table_id` and `table(name)` are generated ink: the lookups are plain ink, so a story reads the same row without the engine (the fallback `roll_dice` returns each table's average, 1 for other dice). `engine.rolls` is `CheckRecord | DiceRecord` (`kind`); the panel, the web player and the journal render both kinds of card. The explorer gives the engine a fixed rng, so table rolls repeat between walks; the config's `from:` notes are compile dependencies (`GameNoteRead.files`), and `main.ts` resolves them wherever it loads a config (`resolveConfig`; `gameConfigFor` is async; `check-ink` reads them from disk). Formulas may explode (`d6!`, `DiceFormula.explode`: a top face rolls another die, faces appended, at most 20 extra; `averageFormula` uses the exploding mean). Keep highest/lowest (`4d6kh3`, `2d20kl` = kl1; `DiceFormula.keep`, not with explode/pool/d66; ties keep the earlier die; `averageFormula` sums the expected order statistics, `keptMean`) and pools (`5d6>=5`, `DiceFormula.pool` = the target; total = hits + bonus; may explode). `rollFormula` returns `dropped` (indices of faces not kept or missed), copied to `DiceRecord.dropped` when non-empty; the panel (`.inkwright-die-dropped`), the web card (`.die.dropped`) fade them and the journal strikes them out (`~~2~~`). Table ranges may be open (`6+`, `≤0`/`<=0`: `Range` with ±Infinity; `tableProblems` clamps them to the dice span, the generated lookup treats an open top as the last row). Journal: `src/play/journal.ts` (`renderJournal`, pure) and `writeJournal()` in main.ts (command `write-journal`, `api.journal()`), path from the note's `journal.path`. - Tabletop slice 2, decks: `decks:` in the config (`DeckDef`: id, name, `cards: CardDef[]`; deck and card ids share the id namespace, each deck also owns `_pile`). The generated ink declares `LIST ` with the cards and `VAR _pile` holding what is left; `draw(deck)` asks `roll_dice(LIST_COUNT(pile), "")` for a position and takes the k-th lowest card out (`nth_card`), `shuffle(deck)` is `LIST_ALL`, `deck_left(deck)` is `LIST_COUNT`. The engine recognises the deck by the label, reads the pile from the state to size the die and name the card (`DiceRecord.deck`), and `hud().decks` lists each pile; the fallback draws the lowest card. A hand is any list the story keeps. diff --git a/docs/rpg-engine-prd.md b/docs/rpg-engine-prd.md index 9a2c193..6bf2db9 100644 --- a/docs/rpg-engine-prd.md +++ b/docs/rpg-engine-prd.md @@ -155,6 +155,7 @@ entities: # 开局就有的(固定的) - 游戏的 `game.md` 写 `system: ../../系统/地城爬行`。引擎先读系统的配置,再叠上游戏自己的(同 id 的以游戏的为准)。生成的 `_engine.ink` 会 INCLUDE 系统的 `rules.ink`。 - **版本**:`system.md` 带 `version`。游戏可以写上自己要的版本;版本对不上时,面板和 `check-ink` 给出提示。 - **分发**:先是复制文件夹;之后在 ink-games 公开仓库放第一方的包,再做"安装系统包"命令(从网址下载到 vault,下载前要用户确认)。 +- **R7 落地的做法(2026-11-11)**:每个包的 `system.md` 用 `files:` 列出自己的文件(模板生成的 `_engine.ink` 不列,装好后「新建游戏」会生成)。ink-games 的 `systems/index.json` 列出所有包(id、版本、名字、简介)。命令「安装规则包」的流程:读列表 → 选一个包 → 确认框(写明来源网址、装到哪个文件夹、会覆盖同名文件)→ 先下 `system.md`,再逐个下它列出的文件,全部成功才写进 `规则包//`。路径只认包里的相对路径(不能有 `..`、隐藏文件、怪字符),所以一个包写不到 vault 的别处。「新建游戏」除了插件自带的包,也列出 vault 里装好的、带模板的包;同 id 时用 vault 里那份,因为游戏实际用的就是它。ink-games 的构建会检查 `systems/` 和 inkwright 的 `packs/` 逐字相同,`files:` 列得对不对。 - **R3 落地的做法(2026-11-10)**:第一方的包放在 inkwright 仓库的 `packs//`,随插件打包(`virtual:packs`)。"新建游戏"把包装进 vault 的 `规则包//`(已有的不覆盖,作者可能改过),把包的 `template/` 复制到新文件夹,并把 `system:` 改成从游戏到包的相对路径。`system:` 写成 `路径` 或 `{ path, version }`;版本只比主版本号,所以 `system.md` 的 `version` 要加引号(`"1.0"`,否则 YAML 读成数字 1)。`system.md` 的 `pack: { name, description }` 是给选择器看的,和 `version` 一样不进游戏配置。包里的 `表/` 等 `from:` 路径相对于包写,叠加时改成相对于游戏。`check-ink` 跳过含 `system.md` 的文件夹本身的 ink,包的 `template/` 照常检查,仓库里有测试保证模板的引擎是最新的、两种语言都能玩到结局。 - **第一方的包**(原创): - **叙事检定**:把宿舍游戏的检定、心声、恐惧整理出来; diff --git a/packs/dungeon-crawl/system.md b/packs/dungeon-crawl/system.md index e96245a..aa77ed8 100644 --- a/packs/dungeon-crawl/system.md +++ b/packs/dungeon-crawl/system.md @@ -1,5 +1,7 @@ --- version: "1.1" +# The pack's files besides this note, for "Install rule pack". +files: [rules.ink, template/game.md, template/main.ink, 说明.md] pack: name: { zh: 地城爬行, en: Dungeon crawl } description: { zh: "四人小队一间一间往下走,最深处是深渊督军(2d6 战斗、火把、药水)", en: "A crew of four goes down room by room to the pit warlord (2d6 fights, torches, potions)" } diff --git a/packs/narrative-check/system.md b/packs/narrative-check/system.md index 0d7d7b4..58b1797 100644 --- a/packs/narrative-check/system.md +++ b/packs/narrative-check/system.md @@ -1,5 +1,7 @@ --- version: "1.0" +# The pack's files besides this note, for "Install rule pack". +files: [rules.ink, template/game.md, template/main.ink, 说明.md] pack: name: { zh: 叙事检定, en: Narrative checks } description: { zh: "2d6 + 技能对难度的检定,五种技能各是一个内心的声音,恐惧和体力两条血条,同伴的恐惧和信任", en: "2d6 + skill against a difficulty, five skills that are inner voices, fear and stamina, companions' fear and trust" } diff --git a/packs/turn-battle/rules.ink b/packs/turn-battle/rules.ink index fe57ca5..afc8f5e 100644 --- a/packs/turn-battle/rules.ink +++ b/packs/turn-battle/rules.ink @@ -7,7 +7,8 @@ // random hero; a foe with venom 1 poisons a hero not yet poisoned instead. Damage = attack + 2d6 - 4 - defence, at // least 1; 11 or 12 on the dice is a critical (+2). At the end of a round poison bites (-2) and statuses count down. // Everything here works on the game's party (stats hp, mp, atk, def, spd, art, acted) and the "foe" kind (hp, atk, -// def, spd, venom, acted), so a game may change both in its own game.md. +// def, spd, venom, acted), so a game may change both in its own game.md. Who is a hero is told by art: every party +// member needs art 1, 2 or 3; one with art 0 (or none) would act and fall like a foe. VAR battle_result = "" VAR battle_round = 0 diff --git a/packs/turn-battle/system.md b/packs/turn-battle/system.md index 7e94a91..1cc4739 100644 --- a/packs/turn-battle/system.md +++ b/packs/turn-battle/system.md @@ -1,5 +1,7 @@ --- version: "1.0" +# The pack's files besides this note, for "Install rule pack". +files: [rules.ink, template/game.md, template/main.ink, 说明.md] pack: name: { zh: 回合战斗, en: Turn battle } description: { zh: "三人小队对一群敌人,按速度轮流出手(攻击、技能、防御、药水,中毒和眩晕)", en: "A party of three against a band of foes, taking turns by speed (attacks, arts, guarding, potions, poison and stun)" } diff --git "a/packs/turn-battle/\350\257\264\346\230\216.md" "b/packs/turn-battle/\350\257\264\346\230\216.md" index 0580227..ffeb74e 100644 --- "a/packs/turn-battle/\350\257\264\346\230\216.md" +++ "b/packs/turn-battle/\350\257\264\346\230\216.md" @@ -46,7 +46,7 @@ INCLUDE _engine.ink ## 改它 -游戏笔记里写同 id 的条目就会替换包里的:换一支小队写 `party:`(每名队员要有 `hp`、`hp_max`、`mp`、`mp_max`、`atk`、`def`、`spd`、`art`、`acted`;`art` 1/2/3 决定技能),改敌人写同 id 的 `foe` 种类(整个种类替换)。包的 `system.md` 不用动。要改流程,把 `rules.ink` 里的段落复制到自己的故事里改名再用。 +游戏笔记里写同 id 的条目就会替换包里的:换一支小队写 `party:`(每名队员要有 `hp`、`hp_max`、`mp`、`mp_max`、`atk`、`def`、`spd`、`art`、`acted`;`art` 1/2/3 决定技能。**`art` 必须是 1、2 或 3**:规则靠它分辨谁是队员,写成 0 或不写的队员会像敌人一样自动行动、倒下时直接消失),改敌人写同 id 的 `foe` 种类(整个种类替换)。包的 `system.md` 不用动。要改流程,把 `rules.ink` 里的段落复制到自己的故事里改名再用。 ## 平衡(2026-11-10) diff --git a/src/api.ts b/src/api.ts index 6e29dfe..f09f41b 100644 --- a/src/api.ts +++ b/src/api.ts @@ -46,6 +46,8 @@ export interface ApiHost { importRun(path: string): Promise<{ id: string; name: string } | null>; newJournalGame(folder?: string): Promise<{ path: string | null }>; newGame(pack: string | null, folder?: string): Promise<{ path: string | null }>; + availablePacks(): Promise<{ id: string; version: string }[] | null>; + installPack(id: string, options?: { ask?: boolean }): Promise<{ path: string | null }>; saveSheet(epilogue?: string): Promise<{ path: string | null }>; } @@ -168,9 +170,12 @@ Visible play panel (the user sees what you do): importRun(path) import an exported run file as a save of the current story -> { id, name } | null newJournalGame(folder?) make a solo journal game from the template in a new folder (default: 旅途日记 / Road journal, numbered when taken), open its main.ink and the panel -> { path } (the main.ink) - newGame(pack, folder?) a game on a bundled rule-system pack ("dungeon-crawl"; null = the journal template): the pack + newGame(pack, folder?) a game on a rule-system pack, bundled or installed ("dungeon-crawl"; null = the journal template): the pack goes to 规则包/ / Rule packs/ unless already there, its template to the new folder (default: the pack's name), system: pointing at the pack, engine generated -> { path } + availablePacks() the rule packs on offer for download (systems/index.json of luoxin9510/ink-games) -> [{ id, version, name, description }] | null + installPack(id, { ask? }) download a pack into 规则包/ / Rule packs/ (the installed copy's folder if any): asks the + player first unless ask is false, overwrites files of the same names -> { path } | { path: null } saveSheet(epilogue?) game mode: write the character being played as a sheet note in the game's sheets folder (default 角色/Characters next to the story); a line tagged #sheet does it after a choice -> { path } @@ -357,6 +362,14 @@ export class InkwrightApi { return this.host.newGame(pack, folder); } + availablePacks(): Promise<{ id: string; version: string }[] | null> { + return this.host.availablePacks(); + } + + installPack(id: string, options: { ask?: boolean } = {}): Promise<{ path: string | null }> { + return this.host.installPack(id, options); + } + saveSheet(epilogue?: string): Promise<{ path: string | null }> { return this.host.saveSheet(epilogue); } diff --git a/src/game/system.ts b/src/game/system.ts index 929b431..590c1d5 100644 --- a/src/game/system.ts +++ b/src/game/system.ts @@ -24,14 +24,14 @@ export function systemRef(fm: unknown): SystemRef | null { /** * The pack's frontmatter under the game's. Lists whose entries all have an `id` (skills, resources, items, tables, * kinds…) are joined by id: the pack's first, a game entry with the same id takes its place, new ones follow. Any - * other value the game sets (rules, party, a map, languages…) replaces the pack's whole. The pack's own `version` + * other value the game sets (rules, party, a map, languages…) replaces the pack's whole. The pack's own `version`, `files` * and `pack` (its name and description, for the new-game picker) stay out; the game's `system` stays in. `rel` is the pack's folder seen from the game's: the pack's `from:` * notes and pictures are written relative to the pack and are moved to be relative to the game. */ export function layerSystem(pack: Record, game: Record, rel: string): Record { const moved = movePaths(pack, rel); const out: Record = {}; - for (const [k, v] of Object.entries(moved)) if (k !== "version" && k !== "system" && k !== "pack") out[k] = v; + for (const [k, v] of Object.entries(moved)) if (k !== "version" && k !== "system" && k !== "pack" && k !== "files") out[k] = v; for (const [k, v] of Object.entries(game)) { const mine = out[k]; out[k] = keyed(mine) && keyed(v) ? joinById(mine, v) : v; diff --git a/src/i18n.ts b/src/i18n.ts index 5a290da..e75063d 100644 --- a/src/i18n.ts +++ b/src/i18n.ts @@ -249,6 +249,16 @@ const zh = { newGameJournalDesc: "每天一个提示,写一段,掷骰问问题(不用规则包)", packsFolder: "规则包", packUnknown: (id: string) => `没有这个规则包:${id}`, + installPack: "安装规则包(从网上下载)", + packPick: "安装哪个规则包?", + packHave: (v: string) => `已装 ${v}`, + packIndexFailed: "读不到规则包列表(没有网络,或者地址打不开)", + packInstallTitle: (id: string) => `安装规则包 ${id}`, + packInstallConfirm: (url: string, dir: string, have: string | null) => `将从 ${url} 下载这个包的文件,写进 ${dir}/。${have === null ? "" : `那里已经装着 ${have} 版,同名文件会被覆盖(你改过的也会),别的文件不动。`}`, + install: "下载并安装", + cancel: "取消", + packInstalled: (dir: string, v: string) => `规则包已装到 ${dir}(${v} 版)`, + packDownloadFailed: (id: string, detail: string) => `规则包 ${id} 下载失败,什么都没写:${detail}`, templateFolder: "旅途日记", templateWhere: "新游戏放在哪个文件夹(没有会新建):", create: "新建", @@ -449,6 +459,16 @@ const en: Strings = { newGameJournalDesc: "A prompt a day, a paragraph written, dice for questions (no rule pack)", packsFolder: "Rule packs", packUnknown: (id) => `No such rule pack: ${id}`, + installPack: "Install rule pack (download)", + packPick: "Which rule pack should be installed?", + packHave: (v) => `installed: ${v}`, + packIndexFailed: "Could not read the list of rule packs (offline, or the address does not answer)", + packInstallTitle: (id) => `Install rule pack ${id}`, + packInstallConfirm: (url, dir, have) => `The pack's files will be downloaded from ${url} and written into ${dir}/.${have === null ? "" : ` Version ${have} is installed there: files with the same names are overwritten (your changes too), others are left alone.`}`, + install: "Download and install", + cancel: "Cancel", + packInstalled: (dir, v) => `Rule pack installed in ${dir} (version ${v})`, + packDownloadFailed: (id, detail) => `Rule pack ${id} could not be downloaded; nothing was written: ${detail}`, templateFolder: "Road journal", templateWhere: "Folder for the new game (made if it is not there):", create: "Create", diff --git a/src/main.ts b/src/main.ts index 90848ac..6f4ca47 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,4 +1,4 @@ -import { FuzzySuggestModal, Modal, Notice, Platform, Plugin, Setting, TFile, TFolder, moment, normalizePath, parseYaml, stringifyYaml, type App, type WorkspaceLeaf } from "obsidian"; +import { FuzzySuggestModal, Modal, Notice, Platform, Plugin, Setting, TFile, TFolder, moment, normalizePath, parseYaml, requestUrl, stringifyYaml, type App, type WorkspaceLeaf } from "obsidian"; import { InkwrightApi } from "./api"; import { compileStory } from "./compile/compile"; import type { StoryGraph } from "./compile/graph"; @@ -20,7 +20,8 @@ import { folderOf, storyName } from "./paths"; import { engineFile, localize, playableCharacters, readConfig, type CharacterDef, type ConfigProblem, type GameConfig } from "./game/config"; import { splitNote } from "./game/frontmatter"; import { journalTemplate } from "./templates/journal"; -import { packGame, packList } from "./templates/packs"; +import { packGame, packList, type PackBundle } from "./templates/packs"; +import { PACK_SOURCE, downloadPack, indexText, packFiles, parseIndex, type IndexEntry } from "./templates/install"; import { joinPath, withSystem } from "./game/system"; import { sheetName, sheetNote } from "./game/sheet"; import PACKS from "virtual:packs"; @@ -135,7 +136,8 @@ export default class InkwrightPlugin extends Plugin implements PlayController, G this.addCommand({ id: "toggle-player-mode", name: T().togglePlayerMode, callback: () => this.togglePlayerMode() }); this.addCommand({ id: "export-run", name: T().exportRun, callback: () => void this.exportRun() }); this.addCommand({ id: "import-run", name: T().importRun, callback: () => this.pickRunToImport() }); - this.addCommand({ id: "new-game", name: T().newGame, callback: () => this.pickNewGame() }); + this.addCommand({ id: "new-game", name: T().newGame, callback: () => void this.pickNewGame() }); + this.addCommand({ id: "install-pack", name: T().installPack, callback: () => void this.pickPackToInstall() }); this.addCommand({ id: "save-sheet", name: T().saveSheet, callback: () => void this.saveSheet() }); this.addCommand({ id: "new-journal-game", name: T().newJournalGame, callback: () => new FolderModal(this.app, T().templateFolder, (f) => void this.newJournalGame(f)).open() }); @@ -428,31 +430,138 @@ export default class InkwrightPlugin extends Plugin implements PlayController, G }); } + /** The vault's packs folders, under either language's name (the current one first). */ + private packsFolders(): string[] { + return [...new Set([T().packsFolder, stringsFor("zh").packsFolder, stringsFor("en").packsFolder])]; + } + + /** Where pack `id` is installed (the folder holding its system.md), or null. */ + private installedPackDir(id: string): string | null { + const dirs = this.packsFolders().map((f) => normalizePath(`${f}/${id}`)); + return dirs.find((d) => this.app.vault.getAbstractFileByPath(`${d}/system.md`) instanceof TFile) ?? null; + } + + /** + * The packs to make games from: the bundled ones, and those installed in the vault (by "Install rule pack" or by + * hand) whose system.md lists a template; an installed copy with a template wins over the bundled one, since it is + * what the game will use. + */ + private async packBundle(): Promise { + const out: PackBundle = { ...PACKS }; + for (const folder of this.packsFolders()) { + const root = this.app.vault.getAbstractFileByPath(normalizePath(folder)); + if (!(root instanceof TFolder)) continue; + for (const child of root.children) { + if (!(child instanceof TFolder)) continue; + const system = await this.readFile(`${child.path}/system.md`).catch(() => null); + const list = system === null ? null : packFiles(splitNote(system, parseYaml).frontmatter); + if (system === null || !list || !list.includes("template/game.md")) continue; + const files: Record = { "system.md": system }; + for (const path of list.slice(1)) { + const text = await this.readFile(`${child.path}/${path}`).catch(() => null); + if (text !== null) files[path] = text; + } + if (files["template/game.md"] !== undefined) out[child.name] = files; + } + } + return out; + } + /** - * A new game: `pack` null = the journal template, else a bundled rule-system pack (RPG PRD §5). The pack goes to - * `//` unless a copy is there already (the author may have changed it), the pack's template to the - * new folder with `system:` pointing at the pack, and the engine is generated. + * A new game: `pack` null = the journal template, else a rule-system pack (bundled or installed; RPG PRD §5). The + * pack goes to `//` unless a copy is there already (the author may have changed it), the pack's + * template to the new folder with `system:` pointing at the pack, and the engine is generated. */ - newGame(pack: string | null = null, folder?: string): Promise<{ path: string | null }> { + async newGame(pack: string | null = null, folder?: string): Promise<{ path: string | null }> { if (pack === null) return this.newJournalGame(folder); - const info = packList(PACKS, getLanguage(), (t) => splitNote(t, parseYaml).frontmatter).find((p) => p.id === pack); + const bundle = await this.packBundle(); + const info = packList(bundle, getLanguage(), (t) => splitNote(t, parseYaml).frontmatter).find((p) => p.id === pack); if (!info) { new Notice(T().packUnknown(pack)); - return Promise.resolve({ path: null }); + return { path: null }; } // A copy already installed (under either language's folder name) is used as it is; a file of the pack that is // missing from it is written, one that is there is left alone. const vault = this.app.vault; - const dirs = [...new Set([T().packsFolder, stringsFor("zh").packsFolder, stringsFor("en").packsFolder])].map((f) => normalizePath(`${f}/${pack}`)); - const packDir = dirs.find((d) => vault.getAbstractFileByPath(`${d}/system.md`) instanceof TFile) ?? normalizePath(`${T().packsFolder}/${pack}`); + const packDir = this.installedPackDir(pack) ?? normalizePath(`${T().packsFolder}/${pack}`); return this.createGame(folder ?? info.name, info.name, (dir) => { - const out = packGame(PACKS, pack, packDir, dir); + const out = packGame(bundle, pack, packDir, dir); if (!out) return null; const missing = Object.entries(out.pack).filter(([p]) => !vault.getAbstractFileByPath(p)); return { ...Object.fromEntries(missing), ...out.game }; }); } + /** The packs offered for download (`systems/index.json` of the public games repo), or null when it cannot be read. */ + async availablePacks(source = PACK_SOURCE): Promise { + try { + const index = parseIndex((await requestUrl({ url: `${source.replace(/\/?$/, "/")}index.json` })).text); + return index.length > 0 ? index : null; + } catch { + return null; + } + } + + /** + * Installs pack `id` from `source` into `//` (the installed copy's folder when there is one): + * after the player says yes (`ask`), system.md and every file it lists are downloaded, then written over the files + * of the same name; other files in the folder are left alone. Nothing is written when any download fails. + */ + async installPack(id: string, options: { ask?: boolean; source?: string } = {}): Promise<{ path: string | null }> { + const source = options.source ?? PACK_SOURCE; + const dir = this.installedPackDir(id) ?? normalizePath(`${T().packsFolder}/${id}`); + if (options.ask !== false) { + const have = await this.readFile(`${dir}/system.md`).then((t) => { + const v = (splitNote(t, parseYaml).frontmatter as { version?: unknown } | null)?.version; + return typeof v === "string" || typeof v === "number" ? String(v) : "?"; + }, () => null); + const yes = await new Promise((done) => new ConfirmModal(this.app, T().packInstallTitle(id), T().packInstallConfirm(`${source.replace(/\/?$/, "/")}${id}/`, dir, have), T().install, done).open()); + if (!yes) return { path: null }; + } + const got = await downloadPack(async (url) => (await requestUrl({ url })).text, source, id, (t) => splitNote(t, parseYaml).frontmatter); + if (!got.ok) { + new Notice(T().packDownloadFailed(id, got.detail)); + return { path: null }; + } + const vault = this.app.vault; + try { + for (const [rel, text] of Object.entries(got.files)) { + const path = normalizePath(`${dir}/${rel}`); + let at = ""; + for (const part of path.split("/").slice(0, -1)) { + at = at === "" ? part : `${at}/${part}`; + if (!vault.getAbstractFileByPath(at)) await vault.createFolder(at); + } + const file = vault.getAbstractFileByPath(path); + if (file instanceof TFile) await vault.modify(file, text); + else await vault.create(path, text); + } + } catch (e) { + new Notice(T().packDownloadFailed(id, e instanceof Error ? e.message : String(e))); + return { path: null }; + } + new Notice(T().packInstalled(dir, got.version)); + return { path: dir }; + } + + /** The install picker: the packs on offer, each with the version installed (if any), then the confirmation. */ + private async pickPackToInstall(): Promise { + const index = await this.availablePacks(); + if (!index) { + new Notice(T().packIndexFailed); + return; + } + const lang = getLanguage(); + const options = await Promise.all(index.map(async (e) => { + const dir = this.installedPackDir(e.id); + const sys = dir ? await this.readFile(`${dir}/system.md`).catch(() => null) : null; + const v = sys === null ? undefined : (splitNote(sys, parseYaml).frontmatter as { version?: unknown } | null)?.version; + const { name, description } = indexText(e, lang); + return { id: e.id, text: `${name} ${e.version}${sys === null ? "" : ` (${T().packHave(typeof v === "string" || typeof v === "number" ? String(v) : "?")})`}${description ? ` — ${description}` : ""}` }; + })); + new PackPickModal(this.app, options, (id) => void this.installPack(id)).open(); + } + /** * Makes a game in a new folder from `folder` (numbered when taken): `plan(dir)` gives every file to write (vault * paths, the game's `game.md` and `main.ink` among them); the engine is generated from the game note as written, its @@ -512,12 +621,12 @@ export default class InkwrightPlugin extends Plugin implements PlayController, G return { path: `${dir}/main.ink` }; } - /** The new-game picker: the journal template or a bundled pack, then the folder. */ - private pickNewGame(): void { + /** The new-game picker: the journal template or a pack (bundled or installed), then the folder. */ + private async pickNewGame(): Promise { const lang = getLanguage(); const options: NewGameOption[] = [ { pack: null, name: T().newGameJournal, description: T().newGameJournalDesc, folder: T().templateFolder }, - ...packList(PACKS, lang, (t) => splitNote(t, parseYaml).frontmatter).map((p) => ({ pack: p.id, name: p.name, description: p.description, folder: p.name })), + ...packList(await this.packBundle(), lang, (t) => splitNote(t, parseYaml).frontmatter).map((p) => ({ pack: p.id, name: p.name, description: p.description, folder: p.name })), ]; new NewGameModal(this.app, options, (o) => new FolderModal(this.app, o.folder, (f) => void this.newGame(o.pack, f)).open()).open(); } @@ -1159,6 +1268,52 @@ class NewGameModal extends FuzzySuggestModal { } } +/** Picks a pack to install (id + the line shown). */ +class PackPickModal extends FuzzySuggestModal<{ id: string; text: string }> { + constructor(app: App, private readonly options: { id: string; text: string }[], private readonly onPick: (id: string) => void) { + super(app); + this.setPlaceholder(T().packPick); + } + + getItems(): { id: string; text: string }[] { + return this.options; + } + + getItemText(o: { id: string; text: string }): string { + return o.text; + } + + onChooseItem(o: { id: string; text: string }): void { + this.onPick(o.id); + } +} + +/** Asks before something is done: `done(true)` on the button, `done(false)` when closed any other way. */ +class ConfirmModal extends Modal { + private answered = false; + + constructor(app: App, private readonly heading: string, private readonly text: string, private readonly button: string, private readonly done: (yes: boolean) => void) { + super(app); + } + + onOpen(): void { + this.setTitle(this.heading); + this.contentEl.createEl("p", { text: this.text }); + new Setting(this.contentEl) + .addButton((b) => b.setButtonText(T().cancel).onClick(() => this.close())) + .addButton((b) => b.setButtonText(this.button).setCta().onClick(() => { + this.answered = true; + this.close(); + this.done(true); + })); + } + + onClose(): void { + this.contentEl.empty(); + if (!this.answered) this.done(false); + } +} + /** Picks an exported run file to import. */ class RunFileModal extends FuzzySuggestModal { constructor(app: App, private readonly files: TFile[], private readonly onPick: (f: TFile) => void) { diff --git a/src/templates/install.ts b/src/templates/install.ts new file mode 100644 index 0000000..be4b49e --- /dev/null +++ b/src/templates/install.ts @@ -0,0 +1,109 @@ +/** + * Installing a rule-system pack from the web (RPG PRD §5, question 5): the public games repo keeps each pack in + * `systems//` and lists them in `systems/index.json`; a pack's `system.md` names its files (`files:`, paths in the + * pack). The plugin fetches the index, then `system.md`, then every file it names, and writes them into the vault's + * packs folder. Pure: `fetchText` is injected (Obsidian's requestUrl in the plugin, a map in tests). + */ +import { localize, type LocalizedText } from "../game/config"; + +export const PACK_SOURCE = "https://raw.githubusercontent.com/luoxin9510/ink-games/main/systems/"; + +export interface IndexEntry { + id: string; + version: string; + name: LocalizedText | undefined; + description: LocalizedText | undefined; +} + +/** A pack id: lower-case letters, digits and dashes (it becomes a folder name and a URL segment). */ +export function isPackId(id: unknown): id is string { + return typeof id === "string" && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id); +} + +/** The packs `systems/index.json` lists (`{ packs: [{ id, version, name, description }] }`); bad entries are left out. */ +export function parseIndex(text: string): IndexEntry[] { + let data: unknown; + try { + data = JSON.parse(text); + } catch { + return []; + } + const packs = typeof data === "object" && data !== null ? (data as { packs?: unknown }).packs : undefined; + if (!Array.isArray(packs)) return []; + const out: IndexEntry[] = []; + for (const p of packs) { + if (typeof p !== "object" || p === null) continue; + const e = p as Record; + if (!isPackId(e.id) || out.some((o) => o.id === e.id)) continue; + out.push({ + id: e.id, + version: typeof e.version === "string" || typeof e.version === "number" ? String(e.version) : "", + name: e.name as LocalizedText | undefined, + description: e.description as LocalizedText | undefined, + }); + } + return out; +} + +/** An entry's name and description in `lang`. */ +export function indexText(e: IndexEntry, lang: string): { name: string; description: string } { + return { name: localize(e.name, lang, e.id), description: localize(e.description, lang, "") }; +} + +/** + * A path inside a pack that is safe to fetch and write: relative, `/`-separated, no `.`/`..`/empty parts, no + * characters a file system or a URL would trip on, no hidden files. + */ +export function isPackPath(p: unknown): p is string { + if (typeof p !== "string" || p === "" || p.length > 200) return false; + const plain = (part: string) => [...part].every((c) => c.charCodeAt(0) >= 0x20 && !'\\:*?"<>|#%'.includes(c)); + return p.split("/").every((part) => part !== "" && part !== "." && part !== ".." && !part.startsWith(".") && plain(part)); +} + +/** + * The files a pack's `system.md` frontmatter names (`files:`), `system.md` first and once. Null when the list is + * missing, empty or names a path that is not safe. + */ +export function packFiles(frontmatter: unknown): string[] | null { + const files = typeof frontmatter === "object" && frontmatter !== null ? (frontmatter as { files?: unknown }).files : undefined; + if (!Array.isArray(files) || files.length === 0 || !files.every(isPackPath)) return null; + return ["system.md", ...new Set(files.filter((f) => f !== "system.md"))]; +} + +/** The URL of a file in pack `id` under `source` (a folder URL; each path segment encoded). */ +export function packUrl(source: string, id: string, path: string): string { + const base = source.endsWith("/") ? source : `${source}/`; + return `${base}${encodeURIComponent(id)}/${path.split("/").map(encodeURIComponent).join("/")}`; +} + +export type FetchText = (url: string) => Promise; + +export type Download = { ok: true; files: Record; version: string } | { ok: false; error: "id" | "fetch" | "files"; detail: string }; + +/** + * Fetches pack `id`: its `system.md`, then every file that names. `files` maps paths in the pack to text. Nothing is + * written here; a failed fetch or a bad file list fails the whole download. + */ +export async function downloadPack(fetchText: FetchText, source: string, id: string, frontmatter: (text: string) => unknown): Promise { + if (!isPackId(id)) return { ok: false, error: "id", detail: id }; + const get = async (path: string): Promise => { + try { + return await fetchText(packUrl(source, id, path)); + } catch (e) { + return e instanceof Error ? e : new Error(String(e)); + } + }; + const system = await get("system.md"); + if (system instanceof Error) return { ok: false, error: "fetch", detail: `system.md: ${system.message}` }; + const fm = frontmatter(system); + const list = packFiles(fm); + if (!list) return { ok: false, error: "files", detail: "system.md" }; + const files: Record = { "system.md": system }; + for (const path of list.slice(1)) { + const text = await get(path); + if (text instanceof Error) return { ok: false, error: "fetch", detail: `${path}: ${text.message}` }; + files[path] = text; + } + const v = typeof fm === "object" && fm !== null ? (fm as { version?: unknown }).version : undefined; + return { ok: true, files, version: typeof v === "string" || typeof v === "number" ? String(v) : "" }; +} diff --git a/tests/install.test.ts b/tests/install.test.ts new file mode 100644 index 0000000..49757ac --- /dev/null +++ b/tests/install.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, test } from "vitest"; +import { parse as parseYaml } from "yaml"; +import packs from "virtual:packs"; +import { splitNote } from "../src/game/frontmatter"; +import { downloadPack, indexText, isPackPath, packFiles, packUrl, parseIndex, PACK_SOURCE } from "../src/templates/install"; + +const fm = (t: string) => splitNote(t, parseYaml).frontmatter; + +describe("installing a rule pack from the web", () => { + test("every bundled pack names exactly its files (the template's generated engine aside)", () => { + for (const [id, files] of Object.entries(packs)) { + const listed = packFiles(fm(files["system.md"])); + expect(listed, id).not.toBeNull(); + expect([...listed!].sort(), id).toEqual(Object.keys(files).sort()); + } + }); + + test("the index: packs with good ids, once each; names in the reader's language", () => { + const index = parseIndex(JSON.stringify({ packs: [ + { id: "turn-battle", version: "1.0", name: { zh: "回合战斗", en: "Turn battle" }, description: { zh: "三对三", en: "Three on three" } }, + { id: "turn-battle", version: "9" }, + { id: "../etc", version: "1" }, + { id: "Bad Id" }, + { id: "dice", version: 2 }, + "junk", + ] })); + expect(index.map((e) => [e.id, e.version])).toEqual([["turn-battle", "1.0"], ["dice", "2"]]); + expect(indexText(index[0], "en")).toEqual({ name: "Turn battle", description: "Three on three" }); + expect(indexText(index[1], "zh")).toEqual({ name: "dice", description: "" }); + expect(parseIndex("not json")).toEqual([]); + expect(parseIndex("{}")).toEqual([]); + }); + + test("paths: relative, inside the pack, nothing hidden or odd", () => { + for (const p of ["rules.ink", "说明.md", "template/game.md", "表/房间.md"]) expect(isPackPath(p), p).toBe(true); + for (const p of ["", "/etc/passwd", "../x", "a/../b", "a//b", "./a", ".obsidian/x", "a\\b", "c:x", "a#b", "a?b", 3]) expect(isPackPath(p), String(p)).toBe(false); + expect(packFiles({ files: ["rules.ink", "system.md", "rules.ink"] })).toEqual(["system.md", "rules.ink"]); + expect(packFiles({ files: ["../evil"] })).toBeNull(); + expect(packFiles({ files: [] })).toBeNull(); + expect(packFiles({})).toBeNull(); + expect(packUrl(PACK_SOURCE, "turn-battle", "template/说明 1.md")).toBe(`${PACK_SOURCE}turn-battle/template/${encodeURIComponent("说明 1.md")}`); + expect(packUrl("https://x.test/s", "a", "b")).toBe("https://x.test/s/a/b"); + }); + + test("a download fetches system.md, then each file it names; any failure fails the whole download", async () => { + const site: Record = { + "https://x.test/p/system.md": "---\nversion: \"1.2\"\nfiles: [rules.ink, template/main.ink]\n---\n", + "https://x.test/p/rules.ink": "=== fight ===\n->->\n", + "https://x.test/p/template/main.ink": "Hi.\n", + }; + const asked: string[] = []; + const fetchText = async (url: string) => { + asked.push(url); + if (site[url] === undefined) throw new Error("404"); + return site[url]; + }; + const ok = await downloadPack(fetchText, "https://x.test/", "p", fm); + expect(ok).toEqual({ ok: true, version: "1.2", files: { "system.md": site["https://x.test/p/system.md"], "rules.ink": site["https://x.test/p/rules.ink"], "template/main.ink": "Hi.\n" } }); + expect(asked).toEqual(["https://x.test/p/system.md", "https://x.test/p/rules.ink", "https://x.test/p/template/main.ink"]); + delete site["https://x.test/p/rules.ink"]; + expect(await downloadPack(fetchText, "https://x.test/", "p", fm)).toEqual({ ok: false, error: "fetch", detail: "rules.ink: 404" }); + site["https://x.test/p/system.md"] = "---\nfiles: [../../.obsidian/plugins/x/main.js]\n---\n"; + expect(await downloadPack(fetchText, "https://x.test/", "p", fm)).toEqual({ ok: false, error: "files", detail: "system.md" }); + expect(await downloadPack(fetchText, "https://x.test/", "../p", fm)).toMatchObject({ ok: false, error: "id" }); + expect(await downloadPack(fetchText, "https://x.test/", "none", fm)).toMatchObject({ ok: false, error: "fetch" }); + }); +}); diff --git a/tests/system.test.ts b/tests/system.test.ts index 7dcd21b..91880b1 100644 --- a/tests/system.test.ts +++ b/tests/system.test.ts @@ -27,6 +27,7 @@ describe("rule-system packs", () => { test("the pack goes under the game: lists joined by id (the game's entry wins), anything else the game sets replaces the pack's", () => { const pack = { version: "2.1", + files: ["rules.ink"], rules: { kind: "sum", dice: [6, 6] }, languages: ["zh", "en"], skills: [{ id: "might" }, { id: "wits" }], @@ -38,6 +39,7 @@ describe("rule-system packs", () => { const game = { system: "../../packs/crawl", skills: [{ id: "wits", name: "Brains" }, { id: "luck" }], rules: { kind: "rollUnder" }, languages: ["en"] }; const out = layerSystem(pack, game, "../../packs/crawl"); expect(out.version).toBeUndefined(); + expect(out.files).toBeUndefined(); expect(out.system).toBe("../../packs/crawl"); expect(out.skills).toEqual([{ id: "might" }, { id: "wits", name: "Brains" }, { id: "luck" }]); expect(out.rules).toEqual({ kind: "rollUnder" }); From bb9ef8b3862f44f988dc66ea40406ef62b86f49a Mon Sep 17 00:00:00 2001 From: nukcole Date: Wed, 11 Nov 2026 02:12:21 +0800 Subject: [PATCH 2/3] export-web: layer the rule pack and resolve from: notes like check-ink Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vdVgYTb9jm7MRdePSgs8B --- CHANGELOG.md | 1 + scripts/export-web.ts | 17 ++++++++--------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 317ac23..b14d6e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Release notes for each version; the GitHub release carries the same text and the ## Unreleased +- `export-web` (the command line) reads a game note the way `check-ink` and the plugin do: a `system:` pack is layered under it and `from:` tables, decks, maps and characters are read. Pages exported from a game on a rule pack had lost the pack's rules, party and foes. - New command "Install rule pack (download)": lists the rule packs published in the public games repo (luoxin9510/ink-games, `systems/`), asks before downloading, then writes the chosen pack into `规则包//` / `Rule packs//` (files of the same names are overwritten, others kept; nothing is written when a download fails). "New game" also offers packs installed in the vault, not only the bundled ones. A pack's `system.md` now lists its files (`files:`). `api.availablePacks()`, `api.installPack(id)`. - Two more rule packs (RPG R6), both in "New game". **Turn battle**: a knight, a mage and a cleric against a band of foes, everyone acting once a round by speed; attacks, arts (shield bash stuns, fireball hits every foe, mend heals and cures), guarding, potions, poison and stun; the story spawns the foes and calls `-> battle ->`, then reads `battle_result`. **Narrative checks**: the rules of the dorm horror game *302* (2d6 checks on choices, six difficulties, five skills that speak as inner voices, fear and stamina, companions' fear and trust, fear lowering reason) plus `clamp()`; a game adds its own characters, resources and items. - Levels and campaigns (RPG R5). `levels: { resource: xp, at: [0, 4, 10] }` gives the story `level`, `next_level_at()`, `level_up_ready()` and `level_up()`; the status bar shows the level and marks when one can be taken. Perks are ordinary items. A line tagged `#sheet` (or the command "Save character sheet", `api.saveSheet()`) writes the character being played as a note in the game's `sheets:` folder: its frontmatter is a `characters` entry (skills, items, what is worn, counts, level, resources, statuses), its body gets the adventure's epilogue. The next adventure reads such notes with `characters: { from: ../角色 }`. Characters written in `game.md` can also set `equipped`, `level`, `resources` and `statuses`. diff --git a/scripts/export-web.ts b/scripts/export-web.ts index 9fa0ac0..edfb0f9 100644 --- a/scripts/export-web.ts +++ b/scripts/export-web.ts @@ -6,11 +6,10 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import { basename, dirname, join } from "node:path"; import { compileStory } from "../src/compile/compile"; import { buildWebPage, storyTitle } from "../src/export/web"; -import { readConfig } from "../src/game/config"; import { setLanguage, T } from "../src/i18n"; import { findLanguageVar } from "../src/play/session"; import { engineBundle } from "./engine-bundle.mjs"; -import { gameNote } from "./game-note"; +import { loadGameConfig } from "./game-note"; const [file, out] = process.argv.slice(2).filter((a, i, all) => !a.startsWith("--") && !all[i - 1]?.startsWith("--")); const option = (name: string) => { @@ -28,14 +27,14 @@ const r = await compileStory(basename(file), (p) => readFile(join(dir, p), "utf8 for (const d of r.diagnostics) console.error(`[${d.severity}] ${d.file}:${d.line ?? "?"} ${d.message}`); if (!r.story) process.exit(1); -// Game mode when a usable game note sits next to the story. -const note = await gameNote(file); +// Game mode when a usable game note sits next to the story: its pack layered under it and its from: notes read, as +// check-ink and the plugin do. +const loaded = await loadGameConfig(file); let game = undefined; -if (note?.error) console.error(`[warning] ${note.name}: ${note.error}`); -else if (note) { - const read = readConfig(note.frontmatter); - for (const p of read.problems) console.error(`[warning] ${note.name}: ${T().configProblem(p)}`); - game = read.config ?? undefined; +if (loaded?.note.error) console.error(`[warning] ${loaded.note.name}: ${loaded.note.error}`); +else if (loaded) { + for (const p of loaded.problems) console.error(`[warning] ${loaded.note.name}: ${T().configProblem(p)}`); + game = loaded.config ?? undefined; } // Same fallback as the plugin: main.ink is named after its folder. From dc6c496587c05ba8506bd69de597acf8167def32 Mon Sep 17 00:00:00 2001 From: nukcole Date: Wed, 11 Nov 2026 02:15:32 +0800 Subject: [PATCH 3/3] PRD: R7 status Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vdVgYTb9jm7MRdePSgs8B --- docs/rpg-engine-prd.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/rpg-engine-prd.md b/docs/rpg-engine-prd.md index 6bf2db9..d9bce9a 100644 --- a/docs/rpg-engine-prd.md +++ b/docs/rpg-engine-prd.md @@ -186,7 +186,7 @@ entities: # 开局就有的(固定的) | R4 | 背包数量、装备栏、状态效果 | 地城包用上:箭会用完、中毒每回合扣血。已做(2026-11-10):地城爬行 1.1,教程 10.4 | | R5 | 成长和战役:经验、升级、天赋;角色卡笔记、`characters.from`、营地 | 一个英雄连续打两次冒险,升级和装备都带过去。已做(2026-11-10):教程 10.5 | | R6 | 回合战斗包和示例;叙事检定包(宿舍游戏的规则整理出来) | 一场 3 对 3 的回合战斗;宿舍游戏改用这个包后行为不变。已做(2026-11-10):`packs/turn-battle`、`packs/narrative-check`,教程 10.6 | -| R7 | 公开:教程第十章、ink-games 上的包和示例、"安装系统包" | 一个没写过 Inkwright 的人照着教程做出一个能玩的小游戏(找人试) | +| R7 | 公开:教程第十章、ink-games 上的包和示例、"安装系统包" | 一个没写过 Inkwright 的人照着教程做出一个能玩的小游戏(找人试)。已做(2026-11-11):命令「安装规则包」;ink-games 的 `systems/`、`tutorial/rpg/` 和 10 个网页示例。还差找人试 | **4AD 不改用实体(2026-11-10 决定)。** 读了 4AD 的代码以后,原定的 R1 验收不成立:4AD 一场遭遇是"一群同样的怪"——一个数量,按"每满几点打死几只"成批地杀——不是一只只有自己生命的个体,拆成实体只会更重、不会更短;那 43 个 `foe_*` 大多是这场遭遇的开关(不死、厌恶某职业、免疫魔法……),战斗里反复读,改成外部函数读取会更慢,正好和 R2 反着来;`foe_hates` 是职业的 LIST 值,实体只存数字;掷骰的先后也会变,没法和旧结果按种子对比。所以 4AD 保持扁平变量,改作 R2 性能的基准;动态实体的真实验收挪到 R6 的 3 对 3 回合战斗(那里每个敌人确实各有各的生命和行动)。