Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Release notes for each version; the GitHub release carries the same text and the

## Unreleased

- Rule-system packs (RPG R3): a game note can name a pack with `system: <folder>` or `system: { path: <folder>, version: 1 }`. The pack's `system.md` frontmatter goes under the game's (lists joined by id, the game's entry wins; anything else the game sets replaces the pack's), its `from:` notes are read relative to the pack, and the generated engine INCLUDEs the pack's `rules.ink`. A pack that is missing, or of another major version than the game asks for, is reported. Markdown tables take `spawn`/`生成` and `count`/`数量` columns. First pack: **Dungeon crawl** (original rules): a crew of four goes down room by room, 2d6 fights, torches, potions, traps, shrines, a warlord in the last room; the story only calls `-> crawl ->` and reads `crawl_result`. New command "New game" (pick a rule pack or the journal template): it installs the pack into `规则包/` / `Rule packs/` unless it is there already, copies its template into a new folder with `system:` pointing at the pack, and generates the engine. `api.newGame(pack, folder?)`.
- Faster long games (RPG R2): the engine looks table rows up itself (`table_text`/`table_id`; the generated ink stays as the fallback and gives the same text), a session parses the story JSON once instead of on every restart, back and load, and one of inkjs's per-step checks is done without a helper call per output item. New engine-side reads for parties: `member_get(who, "var")` (by number or id, any per-member variable; nobody gives the zero of the variable's type) and `party_count("var", value)`. On the 4AD port, with its helpers rewritten on top of these, a random run takes half the ink steps and half the time. Writing advice in `docs/ink-performance.md`. Games with tables or a party need their engine file regenerated.
- Entities (the RPG engine's first piece): `kinds:` in the game note declares kinds of things that come and go during play (monsters, summons), with stats and templates. The story spawns and fights them with `spawn("foe", "goblin")`, `stat(id, "life")`, `set_stat`, `add_stat`, `despawn`, `alive("foe")`, `pick_one("foe", "random" | "lowest:life" | …)`, `nth_one`, `name_of`. A kind's `remove` stat takes an entity out at 0. They are kept in the run like everything else (back, saves, replays). The panel shows them as cards above the choices, one foldable row per kind; the web page lists them in its status lines. A table row can spawn them (`spawn: goblin`, `count: d3`, `stats:`), rolled with `spawn_from("lair")`. With kinds, party members answer the same functions by id, and `alive`/`pick_one`/`nth_one` take `"party"` for the standing members. `check-ink --random` and `api.simulate` count each kind: how many of each template came, how many were taken out and after how many choices, how many were left, the most at once, and stats pushed past their max (a warning).
- `[[note]]` links in a story's text are links in the play panel: a click opens the note, hovering previews it (desktop). The exported page shows the text only; journals keep the links. In ink a bare `|` does not compile, so an alias is written `[[note\|shown]]`.
Expand Down
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ PRD: `docs/game-engine-prd.md` — TTRPG-style rules engine on top of Inkwright
- General RPG engine PRD: `docs/rpg-engine-prd.md` (2026-11-10, replaces the "no general RPG framework" non-goal): entities (fixed and dynamic), stacks and slots, statuses, progression, engine-side helpers, campaigns, rule-system packs; slices R1–R7, R1 = entities. Read it before adding any of those.
- RPG R1 entities: `kinds:` (`KindDef`: id, name, `stats` like party stats, `templates` with starting stats, `down`, `remove`), validated (`kindStat`, ids and `<kind>_n` in the namespace; the entity InkNames are reserved only with kinds). `src/game/entities.ts` (pure, tested in `tests/entities.test.ts`): a kind's store is `id|template|stat=v,…;…`; `entSpawn/Has/Get/Set/Drop/Count/At/Pick/Label`. `inkgen entityInk`: `VAR <kind> = ""`, `VAR <kind>_n`, pure EXTERNALs (`ent_*`; fallbacks keep stores empty, so no fight happens without the engine), wrappers `spawn(kind, template)` (id = `<template>_<serial>`, so ids never collide; template ids are unique across kinds), `stat`, `set_stat` (passes the kind's `remove`), `add_stat`, `despawn`, `alive`, `pick_one(kind, how)` (random rolls `roll_dice("1d"+n, "pick:<kind>")`, else `ent_pick`: first/last/lowest:<stat>/highest:<stat>), `nth_one`, `name_of`. `GameEngine.bindEntities`, `hud().kinds` (`EntityView`: name numbered among the same template), drawn by `status.ts renderKinds` above the choices (`details.inkwright-kind` per kind, folded ones kept in `PlayView.foldedKinds`) and as lines in the web page's `renderHud`. Table rows that spawn: `TableRow.spawn` (a template; it names its kind, since templates are unique across kinds), `count` (number or formula), `stats` (set after spawning); problem `rowSpawn`; `inkgen spawnRowInk` (plain ink: `spawn_from(table)` → the total, `spawn_row`, `spawn_row_one`, `spawn_times`), the lookup branches shared with the table lookups (`rowBranches`). Party as fixed entities (only with kinds): `partyEntity` adds branches to the wrappers, member ids read/write `<stat>_<id>`, `despawn` zeroes `present`, the kind name `party` (`InkNames.partyKind`, zh `小队`) counts/picks the standing members (present and not down) in order; member ids that read like `<template>_<n>` and a kind named like the party are reported as duplicates. Random runs: `SimulateResult.kinds` (`KindTally` diffs `hud().kinds` after each step; an entity spawned and gone within one step is not seen), printed by check-ink, `overMax` a warning. Tests: `tests/game-entities.test.ts`, the web rats test.
- RPG R2 performance (`docs/ink-performance.md`: how to measure, costly ink patterns, numbers): `GameEngine.bindTables` answers `table_text`/`table_id` (declared EXTERNAL; the generated chains are the fallback) through `tables.ts lookupOrder`/`lookupRow`, shared with inkgen's `rowBranches`, and `inkText`/`inkId` (the same escaping); `tests/table-lookup-engine.test.ts` compares both for every total and language. Party: `member_get(who, var)` / `party_count(var, value)` (`InkNames.memberGet/partyCount`, reserved only with a party; `bindParty`; nobody → the zero of the variable's type; ink fallbacks over stats, title and gear). `PlaySession` keeps the story JSON parsed (`parsed`) for new Stories; `src/play/inkjs-speed.ts` replaces StoryState's `inStringEvaluation` getter with an equivalent one (tested step by step against the original). Reusing a Story with `ResetState` for restart was tried and dropped: inkjs keeps `_prevContainers` on the Story, so the next run's visit counts differ.
- RPG R3 rule-system packs: `src/game/system.ts` (`systemRef`, `layerSystem`: lists keyed by id joined, the game's entry wins, other values replaced, the pack's `from`/image paths moved relative to the game, `version` and `pack` dropped; `withSystem` reads `<pack>/system.md`, problems `systemMissing`/`systemVersion` (major version), finds `rules.ink` → `GameConfig.systemRules`, which `generateInk` INCLUDEs as line 2; `joinPath` keeps leading `..`, as does `normalizePath` in compile/paths). Loaded by `scripts/game-note.ts loadGameConfig` and `obsidian.ts loadGameNote` (returns the pack files as dependencies). `check-ink` skips the ink of a folder holding `system.md` (its `template/` is checked). First-party packs live in `packs/<id>/` (`system.md` with a quoted `version` and `pack: { name, description }`, `rules.ink`, `template/` with a committed `_engine.ink`, `说明.md`); `tests/system.test.ts` keeps each template's engine current and plays it. `scripts/packs-bundle.mjs` → `virtual:packs` (template engines left out); `src/templates/packs.ts` (pure: `packList`, `relativePath`, `packGame`); `main.ts createGame` (shared with the journal template) / `newGame(pack, folder?)`, command `new-game` (`NewGameModal` → `FolderModal`), `api.newGame`. The dungeon-crawl pack: `-> crawl ->`, `crawl_result` won/left/fallen, `crawl_rooms`, `depth`; balance measured with a fixed-strategy bot (always strike, potion at life ≤ 2): 68% wins.
- 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 `<id>_pile`). The generated ink declares `LIST <deck>` with the cards and `VAR <deck>_pile` holding what is left; `draw(deck)` asks `roll_dice(LIST_COUNT(pile), "<deck>")` 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.
Expand Down
3 changes: 2 additions & 1 deletion docs/rpg-engine-prd.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ entities: # 开局就有的(固定的)
- 游戏的 `game.md` 写 `system: ../../系统/地城爬行`。引擎先读系统的配置,再叠上游戏自己的(同 id 的以游戏的为准)。生成的 `_engine.ink` 会 INCLUDE 系统的 `rules.ink`。
- **版本**:`system.md` 带 `version`。游戏可以写上自己要的版本;版本对不上时,面板和 `check-ink` 给出提示。
- **分发**:先是复制文件夹;之后在 ink-games 公开仓库放第一方的包,再做"安装系统包"命令(从网址下载到 vault,下载前要用户确认)。
- **R3 落地的做法(2026-11-10)**:第一方的包放在 inkwright 仓库的 `packs/<id>/`,随插件打包(`virtual:packs`)。"新建游戏"把包装进 vault 的 `规则包/<id>/`(已有的不覆盖,作者可能改过),把包的 `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/` 照常检查,仓库里有测试保证模板的引擎是最新的、两种语言都能玩到结局。
- **第一方的包**(原创):
- **叙事检定**:把宿舍游戏的检定、心声、恐惧整理出来;
- **地城爬行**:原创规则,不抄 4AD;
Expand All @@ -175,7 +176,7 @@ entities: # 开局就有的(固定的)
|---|---|---|
| R1 | 实体:固定和动态、种类、`spawn`/`stat`/`set_stat`/`alive`/`pick`、表格的行带属性、敌人区、网页、`check-ink` 和随机对局的统计;`party` 改成实体的简写 | 一个公开的原创小地城示例(教程 10.2,队伍 + 敌人 + 表里刷怪,没有一行战斗代码在引擎里)。原定的"4AD 改用实体"取消,见下 |
| R2 | 引擎侧计算和性能写法文档 | 4AD `--random 300` 的耗时降到现在的一半以下 |
| R3 | 规则系统包的格式、叠加、版本、"新建游戏"按系统选模板;第一个包:地城爬行(原创) | 用这个包从零做一个小地城,不写战斗代码 |
| R3 | 规则系统包的格式、叠加、版本、"新建游戏"按系统选模板;第一个包:地城爬行(原创) | 用这个包从零做一个小地城,不写战斗代码。已做(2026-11-10):`packs/dungeon-crawl`,"新建游戏"命令,教程 10.3 |
| R4 | 背包数量、装备栏、状态效果 | 地城包用上:箭会用完、中毒每回合扣血 |
| R5 | 成长和战役:经验、升级、天赋;角色卡笔记、`characters.from`、营地 | 一个英雄连续打两次冒险,升级和装备都带过去 |
| R6 | 回合战斗包和示例;叙事检定包(宿舍游戏的规则整理出来) | 一场 3 对 3 的回合战斗;宿舍游戏改用这个包后行为不变 |
Expand Down
12 changes: 11 additions & 1 deletion esbuild.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { builtinModules } from "node:module";
import { copyFileSync, mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { engineBundle } from "./scripts/engine-bundle.mjs";
import { packsBundle } from "./scripts/packs-bundle.mjs";

const production = process.argv[2] === "production";
const outDir = process.env.OBSIDIAN_PLUGIN_DIR || ".";
Expand All @@ -28,9 +29,18 @@ const gameEngine = {
},
};

// The first-party rule-system packs (packs/) for the new-game command (src/templates/packs.ts).
const packs = {
name: "packs",
setup(build) {
build.onResolve({ filter: /^virtual:packs$/ }, () => ({ path: "packs", namespace: "packs" }));
build.onLoad({ filter: /.*/, namespace: "packs" }, () => ({ contents: JSON.stringify(packsBundle()), loader: "json", watchDirs: ["packs"] }));
},
};

const ctx = await esbuild.context({
entryPoints: ["src/main.ts"],
plugins: [inkRuntime, gameEngine],
plugins: [inkRuntime, gameEngine, packs],
bundle: true,
external: ["obsidian", "electron", "@codemirror/*", "@lezer/*", ...builtinModules, ...builtinModules.map((m) => `node:${m}`)],
format: "cjs",
Expand Down
Loading
Loading