rpg-engine 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/README.md +1 -1
  2. package/dist/campaign/settings.d.ts +1 -0
  3. package/dist/campaign/settings.js +6 -5
  4. package/dist/command-line.js +12 -5
  5. package/dist/commands/advance.js +1 -1
  6. package/dist/commands/ask.d.ts +37 -2
  7. package/dist/commands/ask.js +106 -35
  8. package/dist/commands/change.js +28 -17
  9. package/dist/commands/config.d.ts +1 -1
  10. package/dist/commands/config.js +69 -21
  11. package/dist/commands/effect.js +42 -23
  12. package/dist/commands/find.js +1 -1
  13. package/dist/commands/game-adventures.js +2 -2
  14. package/dist/commands/game-catalog.d.ts +13 -0
  15. package/dist/commands/game-catalog.js +26 -2
  16. package/dist/commands/game-checks.js +23 -21
  17. package/dist/commands/{game-hit-dice.d.ts → game-dice-pool.d.ts} +3 -3
  18. package/dist/commands/{game-hit-dice.js → game-dice-pool.js} +7 -7
  19. package/dist/commands/game-effects.d.ts +12 -4
  20. package/dist/commands/game-effects.js +21 -13
  21. package/dist/commands/game-examples.d.ts +22 -0
  22. package/dist/commands/game-examples.js +72 -0
  23. package/dist/commands/game-extension-list.d.ts +31 -3
  24. package/dist/commands/game-extension-list.js +94 -6
  25. package/dist/commands/game-images.d.ts +1 -1
  26. package/dist/commands/game-images.js +3 -2
  27. package/dist/commands/game-library.d.ts +3 -0
  28. package/dist/commands/game-library.js +2 -2
  29. package/dist/commands/game-mode.js +1 -1
  30. package/dist/commands/game-package-code.d.ts +87 -0
  31. package/dist/commands/game-package-code.js +648 -0
  32. package/dist/commands/game-package-hooks.d.ts +37 -0
  33. package/dist/commands/game-package-hooks.js +116 -0
  34. package/dist/commands/game-recipes.js +2 -2
  35. package/dist/commands/game-reminders.d.ts +5 -2
  36. package/dist/commands/game-reminders.js +7 -4
  37. package/dist/commands/game-rules.d.ts +4 -1
  38. package/dist/commands/game-rules.js +7 -1
  39. package/dist/commands/game-upkeep.js +3 -3
  40. package/dist/commands/game-view-place.d.ts +8 -20
  41. package/dist/commands/game-view-place.js +16 -35
  42. package/dist/commands/game-widgets.d.ts +42 -8
  43. package/dist/commands/game-widgets.js +182 -31
  44. package/dist/commands/game-world.d.ts +32 -3
  45. package/dist/commands/game-world.js +113 -24
  46. package/dist/commands/image.js +1 -1
  47. package/dist/commands/init.js +2 -2
  48. package/dist/commands/mode.d.ts +1 -1
  49. package/dist/commands/package.d.ts +15 -1
  50. package/dist/commands/package.js +96 -24
  51. package/dist/commands/progression.d.ts +2 -0
  52. package/dist/commands/progression.js +7 -2
  53. package/dist/commands/roll.d.ts +2 -0
  54. package/dist/commands/roll.js +50 -24
  55. package/dist/commands/rules.js +6 -4
  56. package/dist/commands/scene.d.ts +2 -2
  57. package/dist/commands/scene.js +13 -10
  58. package/dist/commands/sheet.js +10 -1
  59. package/dist/commands/status.d.ts +1 -0
  60. package/dist/commands/status.js +14 -4
  61. package/dist/commands/trade.js +6 -4
  62. package/dist/commands/translate.js +2 -2
  63. package/dist/commands/travel.js +1 -1
  64. package/dist/commands/validate.js +2 -2
  65. package/dist/commands/view.d.ts +12 -4
  66. package/dist/commands/view.js +11 -8
  67. package/dist/commands/worked-out.js +11 -5
  68. package/dist/commands/write.d.ts +8 -1
  69. package/dist/commands/write.js +84 -25
  70. package/dist/core/command-reference.js +3 -2
  71. package/dist/core/consents.d.ts +18 -0
  72. package/dist/core/consents.js +93 -0
  73. package/dist/core/context.d.ts +68 -27
  74. package/dist/core/context.js +3 -1
  75. package/dist/core/examples.d.ts +25 -0
  76. package/dist/core/examples.js +19 -0
  77. package/dist/core/files.d.ts +2 -0
  78. package/dist/core/files.js +10 -1
  79. package/dist/core/package-api.d.ts +388 -0
  80. package/dist/core/package-declarations.d.ts +102 -0
  81. package/dist/core/package-declarations.js +81 -0
  82. package/dist/core/registry.d.ts +4 -0
  83. package/dist/core/text.d.ts +5 -0
  84. package/dist/core/text.js +12 -0
  85. package/dist/dashboard/acts.js +31 -24
  86. package/dist/dashboard/address.js +4 -1
  87. package/dist/dashboard/api.js +65 -3
  88. package/dist/dashboard/app.js +222 -98
  89. package/dist/dashboard/ask-card.js +169 -0
  90. package/dist/dashboard/asked-dice.js +57 -0
  91. package/dist/dashboard/dice/tray.js +6 -4
  92. package/dist/dashboard/extension-widgets.js +136 -16
  93. package/dist/dashboard/faces.js +6 -4
  94. package/dist/dashboard/help.js +10 -3
  95. package/dist/dashboard/i18n/ar.json +34 -29
  96. package/dist/dashboard/i18n/cs.json +34 -29
  97. package/dist/dashboard/i18n/da.json +34 -29
  98. package/dist/dashboard/i18n/de.json +34 -29
  99. package/dist/dashboard/i18n/el.json +34 -29
  100. package/dist/dashboard/i18n/es.json +34 -29
  101. package/dist/dashboard/i18n/fi.json +34 -29
  102. package/dist/dashboard/i18n/fr.json +34 -29
  103. package/dist/dashboard/i18n/he.json +34 -29
  104. package/dist/dashboard/i18n/hi.json +34 -29
  105. package/dist/dashboard/i18n/hu.json +34 -29
  106. package/dist/dashboard/i18n/is.json +34 -29
  107. package/dist/dashboard/i18n/it.json +34 -29
  108. package/dist/dashboard/i18n/ja.json +34 -29
  109. package/dist/dashboard/i18n/ko.json +34 -29
  110. package/dist/dashboard/i18n/nb.json +34 -29
  111. package/dist/dashboard/i18n/nl.json +34 -29
  112. package/dist/dashboard/i18n/pl.json +34 -29
  113. package/dist/dashboard/i18n/pt.json +34 -29
  114. package/dist/dashboard/i18n/ro.json +34 -29
  115. package/dist/dashboard/i18n/ru.json +34 -29
  116. package/dist/dashboard/i18n/sv.json +34 -29
  117. package/dist/dashboard/i18n/tr.json +34 -29
  118. package/dist/dashboard/i18n/uk.json +34 -29
  119. package/dist/dashboard/i18n/zh.json +34 -29
  120. package/dist/dashboard/icons.js +4 -1
  121. package/dist/dashboard/kit.js +35 -0
  122. package/dist/dashboard/labels.js +1 -0
  123. package/dist/dashboard/pack-card.js +97 -0
  124. package/dist/dashboard/package-page.js +50 -0
  125. package/dist/dashboard/packages.js +180 -24
  126. package/dist/dashboard/page-code.js +248 -0
  127. package/dist/dashboard/party.js +13 -14
  128. package/dist/dashboard/people.js +4 -0
  129. package/dist/dashboard/person-panel.js +110 -0
  130. package/dist/dashboard/place-map-view.js +11 -6
  131. package/dist/dashboard/rolls.js +2 -2
  132. package/dist/dashboard/scene.js +12 -9
  133. package/dist/dashboard/settings.js +55 -9
  134. package/dist/dashboard/sheet.js +21 -13
  135. package/dist/dashboard/status.js +69 -15
  136. package/dist/dashboard/style.css +859 -574
  137. package/dist/dashboard/top.js +75 -25
  138. package/dist/dashboard/turns.js +34 -13
  139. package/dist/dashboard/widgets.js +9 -2
  140. package/dist/dashboard-server.js +246 -11
  141. package/dist/dice/roll-dice.js +1 -1
  142. package/dist/effects/effect.d.ts +7 -4
  143. package/dist/effects/effect.js +12 -9
  144. package/dist/extensions/engine.d.ts +4 -0
  145. package/dist/extensions/engine.js +74 -0
  146. package/dist/extensions/extension.d.ts +28 -33
  147. package/dist/extensions/extension.js +37 -46
  148. package/dist/extensions/index.d.ts +4 -3
  149. package/dist/extensions/index.js +5 -2
  150. package/dist/extensions/packages.d.ts +14 -0
  151. package/dist/extensions/packages.js +148 -12
  152. package/dist/extensions/words.d.ts +2 -1
  153. package/dist/extensions/words.js +5 -4
  154. package/dist/index.d.ts +1 -3
  155. package/dist/mcp-server.js +52 -15
  156. package/dist/page-words.d.ts +4 -0
  157. package/dist/page-words.js +4 -4
  158. package/dist/page.d.ts +218 -0
  159. package/dist/page.js +2 -0
  160. package/dist/pages/index.d.ts +1 -1
  161. package/dist/pages/index.js +1 -1
  162. package/dist/pages/load.d.ts +7 -1
  163. package/dist/pages/load.js +10 -5
  164. package/dist/pages/page-file.js +1 -1
  165. package/dist/pages/stack-writes.js +5 -4
  166. package/dist/pages/standard-fields.d.ts +2 -0
  167. package/dist/pages/standard-fields.js +8 -1
  168. package/dist/pages/world.d.ts +8 -0
  169. package/dist/pages/world.js +9 -2
  170. package/dist/systems/game-system.d.ts +61 -30
  171. package/dist/systems/game-system.js +159 -50
  172. package/dist/systems/index.d.ts +3 -3
  173. package/dist/systems/index.js +3 -3
  174. package/dist/systems/system-code.d.ts +29 -88
  175. package/dist/systems/system-code.js +68 -23
  176. package/dist/systems/words.d.ts +2 -0
  177. package/dist/systems/words.js +11 -0
  178. package/dist/testing.d.ts +76 -0
  179. package/dist/testing.js +197 -0
  180. package/instructions/combat.md +2 -2
  181. package/instructions/core.md +2 -2
  182. package/instructions/dashboard.md +1 -1
  183. package/instructions/mentor-tutorial.md +1 -1
  184. package/instructions/play.md +2 -2
  185. package/instructions/setup.md +1 -1
  186. package/package.json +15 -2
  187. package/systems/5e/LICENSE.md +13 -3
  188. package/systems/5e/dist/dying.js +83 -16
  189. package/systems/5e/dist/index.js +2 -2
  190. package/systems/5e/dist/page-style.js +634 -0
  191. package/systems/5e/dist/page.js +166 -0
  192. package/systems/5e/dist/shown.js +23 -0
  193. package/systems/5e/instructions/combat.md +1 -0
  194. package/systems/5e/package.json +4 -2
  195. package/systems/5e/system.yaml +35 -7
  196. package/systems/5e/versions/srd-5.1/system.yaml +2 -0
  197. package/systems/5e/words/ar.yaml +30 -0
  198. package/systems/5e/words/cs.yaml +30 -0
  199. package/systems/5e/words/da.yaml +30 -0
  200. package/systems/5e/words/de.yaml +30 -0
  201. package/systems/5e/words/el.yaml +30 -0
  202. package/systems/5e/words/es.yaml +30 -0
  203. package/systems/5e/words/fi.yaml +30 -0
  204. package/systems/5e/words/fr.yaml +30 -0
  205. package/systems/5e/words/he.yaml +30 -0
  206. package/systems/5e/words/hi.yaml +30 -0
  207. package/systems/5e/words/hu.yaml +30 -0
  208. package/systems/5e/words/is.yaml +30 -0
  209. package/systems/5e/words/it.yaml +30 -0
  210. package/systems/5e/words/ja.yaml +30 -0
  211. package/systems/5e/words/ko.yaml +30 -0
  212. package/systems/5e/words/nb.yaml +30 -0
  213. package/systems/5e/words/nl.yaml +30 -0
  214. package/systems/5e/words/pl.yaml +30 -0
  215. package/systems/5e/words/pt.yaml +30 -0
  216. package/systems/5e/words/ro.yaml +30 -0
  217. package/systems/5e/words/ru.yaml +30 -0
  218. package/systems/5e/words/sv.yaml +30 -0
  219. package/systems/5e/words/tr.yaml +30 -0
  220. package/systems/5e/words/uk.yaml +30 -0
  221. package/systems/5e/words/zh.yaml +30 -0
  222. package/dist/commands/game-extensions.d.ts +0 -34
  223. package/dist/commands/game-extensions.js +0 -182
  224. package/dist/commands/game-system-code.d.ts +0 -25
  225. package/dist/commands/game-system-code.js +0 -172
  226. package/dist/dashboard/death-save.js +0 -67
  227. package/dist/dashboard/dying.js +0 -46
  228. package/dist/dashboard/save-outcome.js +0 -42
  229. package/dist/dashboard/spend.js +0 -115
  230. package/dist/extensions/api.d.ts +0 -155
  231. /package/dist/{extensions/api.js → core/package-api.js} +0 -0
package/README.md CHANGED
@@ -85,7 +85,7 @@ The code is under the [MIT](https://github.com/stefanocaronia/rpg-engine/blob/ma
85
85
 
86
86
  The 5e system, in `systems/5e/`, is under the Creative Commons Attribution 4.0 International License ([its license](https://github.com/stefanocaronia/rpg-engine/blob/main/systems/5e/LICENSE.md)): This work includes material taken from the System Reference Document 5.1 ("SRD 5.1") by Wizards of the Coast LLC and available at https://dnd.wizards.com/resources/systems-reference-document. The SRD 5.1 is licensed under the Creative Commons Attribution 4.0 International License available at https://creativecommons.org/licenses/by/4.0/legalcode. Its creatures' icons are from game-icons.net, under the Creative Commons Attribution 3.0 Unported License, by the authors its license names. rpg-engine is compatible with fifth edition.
87
87
 
88
- The weather extension, in `extensions/weather/` and published apart as `@rpgengine/weather`, is Weather by the climate score, by Stefano Caronia, CC BY 4.0, with its code under MIT ([its license](https://github.com/stefanocaronia/rpg-engine/blob/main/extensions/weather/LICENSE.md)).
88
+ Our extensions are packages of their own, installed only when a campaign wants them: [weather](https://github.com/stefanocaronia/rpg-engine-weather) (`@rpgengine/weather`), Weather by the climate score, and [lockpicking](https://github.com/stefanocaronia/rpg-engine-lockpicking) (`@rpgengine/lockpicking`), Lockpicking by complexity, both by Stefano Caronia under CC BY 4.0, with their code under MIT; each repo has its license.
89
89
 
90
90
  rpg-engine ships only original or open-licensed content: for fifth edition, the SRD 5.1 under CC BY 4.0. Anything else that appears in your game is written by your AI or by you, as pages of your campaign on your computer: it is not part of rpg-engine, and we do not distribute it.
91
91
 
@@ -156,6 +156,7 @@ export declare const settingsSchema: z.ZodObject<{
156
156
  "status-line": z.ZodOptional<z.ZodUnknown>;
157
157
  travel: z.ZodOptional<z.ZodUnknown>;
158
158
  values: z.ZodOptional<z.ZodUnknown>;
159
+ "condition-icons": z.ZodOptional<z.ZodUnknown>;
159
160
  widgets: z.ZodOptional<z.ZodUnknown>;
160
161
  }, z.core.$loose>;
161
162
  export type CampaignSettings = z.infer<typeof settingsSchema>;
@@ -117,7 +117,7 @@ function oneLine(most) {
117
117
  export const settingsSchema = z.object({
118
118
  name: z.string().min(1).describe("name of the campaign"),
119
119
  language: z.string().regex(/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/, "use a language code such as it, en or pt-BR").optional().describe("language of the game, as a code such as it or en"),
120
- system: z.string().min(1).optional().describe("game system of the campaign: one of those installed, such as 5e"),
120
+ system: z.string().min(1).optional().describe("game system of the campaign: one of those installed"),
121
121
  mentor: z.enum(mentorWays).optional().describe("how much the master teaches the game, out of the story: off, hints or tutorial; asked as how well the player knows the game: never played (tutorial), a little (hints), well (off)"),
122
122
  premise: z.string().min(1).optional().describe("without a written campaign: the genre, the tone and a few elements of the world, in the player's words"),
123
123
  preparation: z.enum(preparations).optional().describe("without a written campaign: on the fly (the master makes the world just before it is needed) or all at the start"),
@@ -156,14 +156,15 @@ export const settingsSchema = z.object({
156
156
  calendar: z.unknown().optional().describe("the months of the campaign's own calendar, in place of the real ones and an extension's: months: [{name: January, days: 31, season: winter}, ...]"),
157
157
  // What the campaign adds to its game system (CAM-1): checked by the systems module when it reads the system with them, so that a mistake there never hides the
158
158
  // other settings.
159
- fields: z.unknown().optional().describe("fields the campaign adds to its game system, by name with their kind, such as portent: rolls"),
159
+ fields: z.unknown().optional().describe("fields the campaign adds to its game system, by name with their kind, such as omens: rolls"),
160
160
  tables: z.unknown().optional().describe("tables the campaign adds to its game system, by name, such as bulwark-dice-by-level: {3: 4, 7: 5, 15: 6}"),
161
161
  computed: z.unknown().optional().describe("formulas the campaign adds to its game system or puts in place of its own, as a house rule, by field"),
162
162
  counters: z.unknown().optional().describe("counters the campaign adds to its game system or changes: their limits and what comes back with a rest, by name"),
163
- recipes: z.unknown().optional().describe("what the campaign adds to the rests of its game system, by recipe, such as short rest: {set: {bulwark-dice: max}}"),
164
- "status-line": z.unknown().optional().describe("fields the campaign adds to the line of the player character and the companions, such as portent?"),
163
+ recipes: z.unknown().optional().describe("what the campaign adds to the rests of its game system, by recipe, such as rest: {set: {bulwark-dice: max}}"),
164
+ "status-line": z.unknown().optional().describe("fields the campaign adds to the line of the player character and the companions, such as omens?"),
165
165
  travel: z.unknown().optional().describe("what the campaign adds to how its game system travels, by key: paces, hours, terrain and kinds of road, such as kinds: {canal: {}}"),
166
166
  values: z.unknown().optional().describe("names the campaign adds to the closed lists of its game system, by field, such as languages: [Lingua dei Guadi]"),
167
+ "condition-icons": z.unknown().optional().describe("the drawings of effects on the dashboard by their names, over the game system's: the d of an SVG path on a grid of 24, such as Benedizione: M12 3v18"),
167
168
  // Checked against the campaign's extensions when it is written (D-502): one written wrongly by hand leaves the extension's place.
168
169
  widgets: z.unknown().optional().describe("where the dashboard shows the extensions' widgets, by extension.widget: top, side, scene, sheet, world, journal or off, such as weather.today: side"),
169
170
  }).loose();
@@ -172,7 +173,7 @@ export const settingNames = Object.keys(settingsSchema.shape);
172
173
  /** The settings that hold a list, changed one item at a time; none of them is ever missing in play. */
173
174
  export const listSettingNames = ["lines", "veils", "table", "precedents", "learned", "library", "status-line"];
174
175
  /** The settings that hold entries by name, what the campaign adds to its game system (CAM-1): given or removed one entry at a time. */
175
- export const mapSettingNames = ["fields", "tables", "computed", "counters", "recipes", "travel", "values"];
176
+ export const mapSettingNames = ["fields", "tables", "computed", "counters", "recipes", "travel", "values", "condition-icons"];
176
177
  /** The settings that hold entries by name: what the campaign adds to its game system, and where the dashboard shows the extensions' widgets (D-502). */
177
178
  export const entrySettingNames = [...mapSettingNames, "widgets"];
178
179
  /**
@@ -1,11 +1,12 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { z } from "zod";
3
3
  import { findCampaign } from "./campaign/index.js";
4
- import { extensionCommands } from "./commands/game-extensions.js";
4
+ import { loadCampaignCode, packageCommands } from "./commands/game-package-code.js";
5
5
  import { commands } from "./commands/index.js";
6
6
  import { systemConfirm } from "./confirm/index.js";
7
7
  import { defaultContext, packagesFolder } from "./core/context.js";
8
8
  import { downloadBytes } from "./core/download.js";
9
+ import { withExamples } from "./core/examples.js";
9
10
  import { baseType, isBoolean, isList } from "./core/registry.js";
10
11
  import { FileStore, withFiles } from "./core/store.js";
11
12
  import { firstSentence } from "./core/text.js";
@@ -17,6 +18,8 @@ import { hostPictures, hostReader } from "./pictures/index.js";
17
18
  import { loadSystemCode } from "./systems/index.js";
18
19
  // The one command that exists only on the command line: cli.ts starts the server when it comes alone.
19
20
  const mcpDescription = "Start the MCP server for an AI host. Through it the host uses these commands as tools; the host starts it, with no options.";
21
+ /** The core's commands that call the hooks of the campaign's packages after their writes (D-514). */
22
+ const hookCommands = new Set(["ask", "change", "effect", "roll", "scene"]);
20
23
  /** The `rpg` command line: finds the command, validates its input, runs it and renders the result. */
21
24
  export async function runCommandLine(argv, context = {
22
25
  ...defaultContext(),
@@ -33,6 +36,10 @@ export async function runCommandLine(argv, context = {
33
36
  // The systems' code, loaded once, before any command may call its hooks (D-448).
34
37
  context.systemCode ??= await loadSystemCode(context.systemFolders);
35
38
  const [commandName, ...args] = argv;
39
+ // And the campaign's extensions', for the commands that call their hooks at once (D-514); never for package, which may take them away.
40
+ if (hookCommands.has(commandName ?? "")) {
41
+ await withFiles(context.files ?? new FileStore(context.systemFolders), () => loadCampaignCode(context));
42
+ }
36
43
  if (commandName === undefined || commandName === "--help" || commandName === "-h") {
37
44
  return success(generalHelp(await campaignCommands(context)));
38
45
  }
@@ -136,7 +143,7 @@ async function campaignCommands(context) {
136
143
  try {
137
144
  return await withFiles(context.files ?? new FileStore(context.systemFolders), async () => {
138
145
  const root = findCampaign(context.folder);
139
- return root === undefined ? [] : (await extensionCommands(root, context, commands.map((command) => command.name))).commands;
146
+ return root === undefined ? [] : (await packageCommands(root, context, commands.map((command) => command.name))).commands;
140
147
  });
141
148
  }
142
149
  catch {
@@ -146,7 +153,7 @@ async function campaignCommands(context) {
146
153
  /** The commands in two groups, each with the first sentence of its description, and those of the campaign's extensions. */
147
154
  function generalHelp(own) {
148
155
  const width = Math.max(...[...commands, ...own].map((command) => command.name.length));
149
- const line = (name, description) => ` ${name.padEnd(width)} ${firstSentence(description)}`;
156
+ const line = (name, description) => ` ${name.padEnd(width)} ${firstSentence(withExamples(description))}`;
150
157
  const groupLines = (group) => commands.filter((command) => command.group === group && !command.needsPlayer).map((command) => line(command.name, command.description));
151
158
  return [
152
159
  `rpg-engine ${getVersion()}`,
@@ -166,9 +173,9 @@ function commandHelp(command) {
166
173
  const positionals = command.positionals ?? [];
167
174
  const optionLines = inputFields(command).map(([name, field]) => {
168
175
  const flag = positionals.includes(name) ? `<${name}>${isList(field) ? "..." : ""}` : `--${name}${isBoolean(field) ? "" : " <value>"}${isList(field) ? "..." : ""}`;
169
- return ` ${flag.padEnd(20)} ${field.description ?? ""}`;
176
+ return ` ${flag.padEnd(20)} ${withExamples(field.description ?? "")}`;
170
177
  });
171
- return [usage(command), "", command.description, "", ...optionLines, ` ${"--json".padEnd(20)} print the result as JSON`].join("\n");
178
+ return [usage(command), "", withExamples(command.description), "", ...optionLines, ` ${"--json".padEnd(20)} print the result as JSON`].join("\n");
172
179
  }
173
180
  function usage(command) {
174
181
  return ["rpg", command.name, ...(command.positionals ?? []).map((name) => `<${name}>${isList(command.input.shape[name]) ? "..." : ""}`), "[options]"].join(" ");
@@ -6,7 +6,7 @@ import { addDuration, formatDuration, formatGameDate, lastGameDay, minutesBetwee
6
6
  import { calendarText, nextAfter, passedLines, passTime, unreadNotes } from "./game-advance.js";
7
7
  import { newStateChecks } from "./game-checks.js";
8
8
  import { dueEvents, dueText, isDated, plannedEvents } from "./game-events.js";
9
- import { timePassedLines } from "./game-extensions.js";
9
+ import { timePassedLines } from "./game-package-code.js";
10
10
  import { newDatedLogEntry, presentDate } from "./game-time.js";
11
11
  import { campaignWorld } from "./game-world.js";
12
12
  export const advance = defineCommand({
@@ -1,16 +1,18 @@
1
1
  import { z } from "zod";
2
- import type { Context, Rows, Said } from "../core/context.ts";
2
+ import type { CardAsked, Context, Rows, Said } from "../core/context.ts";
3
3
  type InWords = {
4
4
  kind: "unanswered" | "unavailable" | "absent" | "physical" | "dice in words";
5
5
  asked: string;
6
6
  };
7
- type AskResult = {
7
+ /** What the player answered, or the question to ask them in words. */
8
+ export type AskResult = {
8
9
  kind: "roll";
9
10
  id: string;
10
11
  who: string;
11
12
  check: string;
12
13
  text: string;
13
14
  total: number;
15
+ faces: number[];
14
16
  notes?: string[];
15
17
  } | {
16
18
  kind: "changed";
@@ -36,6 +38,39 @@ export declare const ask: import("../core/registry.ts").Command<z.ZodObject<{
36
38
  square: z.ZodOptional<z.ZodBoolean>;
37
39
  recipe: z.ZodOptional<z.ZodString>;
38
40
  }, z.core.$strip>, AskResult>;
41
+ /**
42
+ * A roll of the player's character asked with buttons (ASK-3, ASK-8, ASK-12): for ask, and for an extension's code (D-505). With physical dice it is the question
43
+ * to ask in words; a call stopped logs nothing (ASK-9).
44
+ */
45
+ export declare function askedRoll(root: string, context: Context, question: string, checks: {
46
+ label: string;
47
+ notation?: string;
48
+ }[], given: string | undefined, told?: Told): Promise<AskResult>;
49
+ /** What a package's roll asked tells in its own words (D-505, D-507): the button that turns it down, and what the faces mean, logged in place of the total. */
50
+ export interface Told {
51
+ /** The roll's button in place of the core's words, with a note under it. */
52
+ roll?: Button;
53
+ /** The button that turns it down, renamed; false for none, when the roll is forced (D-507). */
54
+ decline?: Button | false;
55
+ /** The rule under the buttons, in a line. */
56
+ rule?: string;
57
+ /** The card of a widget the page asks it in (D-507). */
58
+ card?: CardAsked;
59
+ says?: (faces: number[]) => string;
60
+ /** How each die turned out, by its face in order: kept in the roll's line only when there is one for each, good, bad or none. */
61
+ tones?: (faces: number[]) => unknown[];
62
+ }
63
+ /** A button's name, and the note under it. */
64
+ export interface Button {
65
+ name: string;
66
+ note?: string;
67
+ }
68
+ /** How the dice turned out, for the roll's line: one for each face, good, bad or none; nothing for any other list, which a package gave wrong. */
69
+ export declare function tonesOf(given: unknown[] | undefined, faces: number[]): {
70
+ tones?: ("good" | "bad" | null)[];
71
+ };
72
+ /** Whether a text is the dice of a check, as 1d20+5 or 1d20+athletics (ASK-2, ASK-12). */
73
+ export declare function isCheckDice(text: string): boolean;
39
74
  /**
40
75
  * The player's answer, on the dashboard's page and in the host's form at once, where both are (ASK-13, D-455): the first answer wins and takes the other
41
76
  * away; one that never showed, a page not open or a form the host does not show, leaves the other to answer. Neither shown is absent: the master asks in words.
@@ -9,14 +9,14 @@ import { closedSquare, readSquare } from "../grid/index.js";
9
9
  import { findPage, loadWorld, locate, playerCharacters } from "../pages/index.js";
10
10
  import { rollName } from "../systems/index.js";
11
11
  import { effectiveFields } from "./effect-layer.js";
12
+ import { restDice, spendDice } from "./game-dice-pool.js";
12
13
  import { placeGrid } from "./game-grids.js";
13
- import { restDice, spendDice } from "./game-hit-dice.js";
14
+ import { allSaid, packagesAsking, packagesRolled } from "./game-package-hooks.js";
14
15
  import { recipeNamed } from "./game-recipes.js";
15
- import { allSaid, systemAsking, systemRolled } from "./game-system-code.js";
16
16
  import { newDatedLogEntry } from "./game-time.js";
17
17
  import { campaignSystem, campaignWorld, systemWordsOf } from "./game-world.js";
18
18
  import { placeOnMap } from "./move.js";
19
- import { hasNames, namesAsZero, rollerOf, withSheetValues } from "./roll.js";
19
+ import { hasNames, namesAsZero, rollerOf, sheetDiceOf, withSheetValues } from "./roll.js";
20
20
  // The words of the buttons, in the campaign's language, as the dashboard's languages (playtest 15); English for the others (ASK-7).
21
21
  const buttonWords = {
22
22
  en: { roll: "Roll", change: "Change my mind", choice: "Choice", square: "Move", rest: "Rest", done: "Done" },
@@ -57,17 +57,17 @@ export const ask = defineCommand({
57
57
  + "In a fight, each roll the player's character makes is its own ask, in the order the game's rules give them. "
58
58
  + "For a choice the rules or the story force (a reaction, a fork): give the answers. Never to offer actions, which are the player's to say, and never for hidden rolls. "
59
59
  + "square, without options, once the player says their character moves on the map of its place but not to which square: the engine moves them to the square the player touches and gives you the way. "
60
- + "recipe, without options, when change with a rest's recipe says so: the player spends their character's dice, as hit dice, one at a time, and you get what they gave. "
60
+ + "recipe, without options, when change with a rest's recipe says so: the player spends their character's dice one at a time, and you get what they gave. "
61
61
  + "Write nothing before the call: the question carries what is at stake, and the story goes on after the click. "
62
- + 'Example: question "Scavalcare il muro prima della ronda: se fallisci, cadi e ti sentono", options ["Atletica 1d20+athletics", "Acrobazia 1d20+acrobatics"], who Bruna.',
62
+ + 'Example: question "Scavalcare il muro prima della ronda: se fallisci, cadi e ti sentono", options ["{{check}}", "{{otherCheck}}"], who Bruna.',
63
63
  group: "game",
64
64
  needsPlayer: true,
65
65
  input: z.object({
66
66
  question: z.string().describe("what is at stake either way, or the choice, in one line, in the player's language"),
67
- options: textList.optional().describe("for a roll, the checks that fit with their dice, such as Atletica 1d20+athletics; for a choice, the answers, such as Sì and No; from 1 to 4"),
67
+ options: textList.optional().describe("for a roll, the checks that fit with their dice, such as {{check}}; for a choice, the answers, such as Sì and No; from 1 to 4"),
68
68
  who: z.string().optional().describe("for a roll or a square, the player's character, such as Bruna; the only one there is, if left out"),
69
69
  square: z.boolean().optional().describe("true to ask where the player's character moves on its place's map"),
70
- recipe: z.string().optional().describe("the rest's recipe, such as short rest"),
70
+ recipe: z.string().optional().describe("the rest's recipe that change named"),
71
71
  }),
72
72
  async run(input, context) {
73
73
  const root = requireCampaign(context.folder);
@@ -75,7 +75,7 @@ export const ask = defineCommand({
75
75
  throw new Error("The player cannot be asked with buttons here: ask them in words, without a word about buttons, and stop.");
76
76
  }
77
77
  const question = input.question.trim();
78
- const words = buttonWords[(readSettings(root).language ?? "en").split("-")[0]] ?? buttonWords.en;
78
+ const words = buttonWordsOf(root);
79
79
  if (question === "") {
80
80
  throw new Error("Give the question: for a roll, what is at stake either way; for a choice, what the player chooses.");
81
81
  }
@@ -95,21 +95,15 @@ export const ask = defineCommand({
95
95
  const checks = options.filter((option) => option.notation !== undefined);
96
96
  // One answer alone is no choice: a roll whose dice are not at the end would become one, and nothing would be rolled (ASK-2, D-266).
97
97
  if (checks.length === 0 && options.length === 1) {
98
- throw new Error(`"${options[0].label}" alone is no choice: a roll ends with its dice, such as Danni radianti 1d8; a choice gives two answers or more.`);
98
+ throw new Error(`"${options[0].label}" alone is no choice: a roll ends with its dice, such as ${diceAtTheEnd(options[0].label)}; a choice gives two answers or more.`);
99
99
  }
100
100
  if (checks.length === 0) {
101
101
  return answer(root, context, question, options, words);
102
102
  }
103
103
  if (checks.length < options.length) {
104
- throw new Error(`Give every check its dice, such as Atletica 1d20+5; for a choice, give only the answers, such as Sì and No. A roll already has its button to change one's mind (${words.change}): leave out an answer such as No.`);
104
+ throw new Error(`Give every check its dice, such as Atletica ${sheetDiceOf(campaignSystem(root, context))}+5; for a choice, give only the answers, such as Sì and No. A roll already has its button to change one's mind (${words.change}): leave out an answer such as No.`);
105
105
  }
106
- const who = playerCharacter(loadWorld(root), input.who);
107
- const worked = sheetChecks(root, context, checks, who);
108
- // The player rolls their own dice: a roll is asked in words, and they tell the values (ASK-8).
109
- if (readSettings(root).dice === "physical") {
110
- return { kind: "physical", asked: askedText(question, "checks", worked) };
111
- }
112
- return rollChosen(root, context, question, worked, who, words);
106
+ return askedRoll(root, context, question, checks, input.who);
113
107
  },
114
108
  format(result) {
115
109
  switch (result.kind) {
@@ -141,17 +135,77 @@ export const ask = defineCommand({
141
135
  },
142
136
  });
143
137
  /**
144
- * The buttons of a roll: the checks and a change of mind (ASK-3, ASK-4); a death save, only its check, as no one turns it down (D-460). The chosen check is
145
- * rolled with the engine's dice and logged as the player's roll.
138
+ * A roll of the player's character asked with buttons (ASK-3, ASK-8, ASK-12): for ask, and for an extension's code (D-505). With physical dice it is the question
139
+ * to ask in words; a call stopped logs nothing (ASK-9).
140
+ */
141
+ export async function askedRoll(root, context, question, checks, given, told) {
142
+ const who = playerCharacter(loadWorld(root), given);
143
+ const worked = sheetChecks(root, context, checks, who);
144
+ // The player rolls their own dice: a roll is asked in words, and they tell the values (ASK-8).
145
+ if (readSettings(root).dice === "physical") {
146
+ return { kind: "physical", asked: askedText(question, "checks", worked) };
147
+ }
148
+ return rollWorded(root, context, question, worked, who, told);
149
+ }
150
+ /** How the dice turned out, for the roll's line: one for each face, good, bad or none; nothing for any other list, which a package gave wrong. */
151
+ export function tonesOf(given, faces) {
152
+ const known = (tone) => tone === "good" || tone === "bad" || tone === undefined || tone === null;
153
+ return given === undefined || !Array.isArray(given) || given.length !== faces.length || !given.every(known) || given.every((tone) => tone === undefined || tone === null)
154
+ ? {}
155
+ : { tones: given.map((tone) => (tone === "good" || tone === "bad" ? tone : null)) };
156
+ }
157
+ /**
158
+ * A label with its dice in the middle written as a check, for a refusal: words after the dice go before them, as Danni radianti 1d8; what is in brackets,
159
+ * as (CD 13), goes in the question (D-518). A label without dice gets an example.
146
160
  */
147
- async function rollChosen(root, context, question, checks, who, words) {
161
+ function diceAtTheEnd(label) {
162
+ const found = /^(.*?)\s*(\d*d(?:\d+|%|F)\S*)\s+(.+)$/i.exec(label.trim());
163
+ if (found === null) {
164
+ return "Danni 1d8";
165
+ }
166
+ const [, name, dice, after] = found;
167
+ const named = (...parts) => parts.filter((part) => part !== "").join(" ");
168
+ return after.startsWith("(") ? `${named(name, dice)}, and ${after} goes in the question` : named(name, after, dice);
169
+ }
170
+ /** Whether a text is the dice of a check, as 1d20+5 or 1d20+athletics (ASK-2, ASK-12). */
171
+ export function isCheckDice(text) {
172
+ return isDice(namesAsZero(text));
173
+ }
174
+ /** The words of the buttons in the campaign's language (ASK-7). */
175
+ function buttonWordsOf(root) {
176
+ return buttonWords[(readSettings(root).language ?? "en").split("-")[0]] ?? buttonWords.en;
177
+ }
178
+ /**
179
+ * A roll asked in a package's words: a package's own ask in its own (D-505), the core's in the game system's, when its code words it (D-507, D-514); the
180
+ * system's card as it is after the last dice, once the call ends, however it ends.
181
+ */
182
+ async function rollWorded(root, context, question, checks, who, given) {
183
+ const told = given ?? packagesAsking(root, context, { who, checks: checks.map((check) => check.label), notations: checks.map((check) => check.notation ?? "") }) ?? {};
184
+ try {
185
+ return await rollChosen(root, context, question, checks, who, buttonWordsOf(root), told);
186
+ }
187
+ finally {
188
+ if (given === undefined && told.card !== undefined) {
189
+ context.page?.cardEnded?.(told.card);
190
+ }
191
+ }
192
+ }
193
+ /**
194
+ * The buttons of a roll: the checks and a change of mind (ASK-3, ASK-4); a forced roll, as a death save, only its checks, as no one turns it down (D-460,
195
+ * D-507). The chosen check is rolled with the engine's dice and logged as the player's roll.
196
+ */
197
+ async function rollChosen(root, context, question, checks, who, words, told) {
148
198
  const system = campaignSystem(root, context);
149
- const save = systemAsking(root, context, { who, notations: checks.map((check) => check.notation ?? "") });
150
- const change = save === undefined ? [words.change] : [];
199
+ const decline = told.decline === false ? undefined : told.decline?.name ?? words.change;
200
+ const change = decline === undefined ? [] : [decline];
151
201
  const labels = [...checks.map((check) => `${words.roll}: ${check.label} (${check.notation})`), ...change];
152
202
  const language = readSettings(root).language ?? system?.language ?? "en";
153
- const shown = [...checks.map((check) => formLabel(check, (dice) => (system === undefined ? undefined : rollName(system, dice, language)))), ...change];
154
- const rows = { who, fields: [...checks.map((check) => check.field ?? null), ...change.map(() => null)], ...(save === undefined ? {} : { save }) };
203
+ const formed = (check) => told.roll?.name ?? formLabel(check, (dice) => (system === undefined ? undefined : rollName(system, dice, language)));
204
+ const shown = [...checks.map(formed), ...change];
205
+ // A package's words for its buttons, its rule and its card, for the page (D-507).
206
+ const buttons = told.roll === undefined && typeof told.decline !== "object" ? {} : { buttons: [...checks.map(() => told.roll ?? null), ...change.map(() => (typeof told.decline === "object" ? told.decline : null))] };
207
+ const own = { ...buttons, ...(told.rule === undefined ? {} : { rule: told.rule }), ...(told.card === undefined ? {} : { card: told.card }), ...(decline === undefined ? { forced: true } : {}) };
208
+ const rows = { who, fields: [...checks.map((check) => check.field ?? null), ...change.map(() => null)], ...own };
155
209
  const chosen = await chooseAnswer(context, question, words.roll, labels, rows, shown);
156
210
  const asked = askedText(question, "checks", checks);
157
211
  // A call the user stopped logs nothing (ASK-9).
@@ -167,16 +221,18 @@ async function rollChosen(root, context, question, checks, who, words) {
167
221
  }
168
222
  const check = chosen === undefined ? undefined : checks[chosen];
169
223
  if (check?.notation === undefined) {
170
- logAnswer(root, context, question, labels, chosen === checks.length ? words.change : undefined);
224
+ logAnswer(root, context, question, labels, chosen === checks.length ? decline : undefined);
171
225
  return chosen === checks.length ? { kind: "changed" } : { kind: "unanswered", asked };
172
226
  }
173
227
  const diceRoll = rollDice(check.notation, { random: context.random });
174
- const data = { notation: diceRoll.notation, total: diceRoll.total, result: diceRoll.text, why: `${check.label}: ${question}`, check: check.label, who, physical: false, dice: diceRoll.dice };
228
+ const says = told.says === undefined ? {} : { says: told.says(diceRoll.faces) };
229
+ const tones = tonesOf(told.tones?.(diceRoll.faces), diceRoll.faces);
230
+ const data = { notation: diceRoll.notation, total: diceRoll.total, result: diceRoll.text, ...says, ...tones, why: `${check.label}: ${question}`, check: check.label, who, physical: false, dice: diceRoll.dice };
175
231
  const entry = newDatedLogEntry(root, { ...context, actor: "player" }, "roll", "public", data);
176
232
  appendLogEntry(root, entry);
177
- // A check of a dying character is their death save, which the engine writes (DIE-4, D-460).
178
- const notes = allSaid(systemRolled(root, context, { who, notation: diceRoll.notation, total: diceRoll.total, dice: diceRoll.dice }));
179
- return { kind: "roll", id: entry.id, who, check: check.label, text: diceRoll.text, total: diceRoll.total, ...(notes.length === 0 ? {} : { notes }) };
233
+ // What the packages' code makes of the roll, as the 5e's death save (D-448).
234
+ const notes = allSaid(packagesRolled(root, context, { who, notation: diceRoll.notation, total: diceRoll.total, faces: diceRoll.faces, dice: diceRoll.dice, text: diceRoll.text, id: entry.id }));
235
+ return { kind: "roll", id: entry.id, who, check: check.label, text: diceRoll.text, total: diceRoll.total, faces: diceRoll.faces, ...(notes.length === 0 ? {} : { notes }) };
180
236
  }
181
237
  /**
182
238
  * Where the player's character moves on the map of its place (ASK-11): only the page can show the map; the square touched moves it, as move with at, and the
@@ -250,20 +306,23 @@ async function diceSpent(root, context, question, recipeName, given, words) {
250
306
  if (context.page?.spendDice === undefined) {
251
307
  return { kind: "dice in words", asked: inWords };
252
308
  }
253
- const fieldWords = systemWordsOf(system, settings.language ?? system.language ?? "en", context)?.fields ?? {};
309
+ // The packages may word the dice of a rest, as a roll: the rule under them, the card of a widget they are spent in (D-514).
310
+ const told = packagesAsking(root, context, { who, checks: left.map((dice) => dice.field), notations: left.map((dice) => `1d${dice.sides}`), recipe: recipe.name }) ?? {};
311
+ const worded = told.rule === undefined ? {} : { rule: told.rule };
312
+ const fieldWords = systemWordsOf(root, system, settings.language ?? system.language ?? "en", context)?.fields ?? {};
254
313
  const label = (field) => String(valueNamed(fieldWords, field) ?? field);
255
314
  const from = counterOn(world, who, gives)?.value ?? 0;
256
315
  const rolls = [];
257
316
  const notes = [];
258
317
  // The dice as last read: what the page and the master are told when the campaign does not read for a moment, as while a page is rewritten.
259
- let last = { who, dice: before.map(shownDice), gives: { field: gives, from, value: from }, rolls: [] };
318
+ let last = { who, dice: before.map(shownDice), gives: { field: gives, from, value: from }, rolls: [], ...worded };
260
319
  const page = {
261
320
  shown: () => {
262
321
  try {
263
322
  const now = campaignWorld(root, context);
264
323
  const target = counterOn(now, who, gives);
265
324
  const dice = restDice(now, recipe, pageNamed(now, who)).map(shownDice);
266
- last = { who, dice, gives: { field: gives, from, value: target?.value ?? 0, ...(target?.max === undefined ? {} : { max: target.max }) }, rolls: [...rolls] };
325
+ last = { who, dice, gives: { field: gives, from, value: target?.value ?? 0, ...(target?.max === undefined ? {} : { max: target.max }) }, rolls: [...rolls], ...worded };
267
326
  }
268
327
  catch {
269
328
  last = { ...last, rolls: [...rolls] };
@@ -289,7 +348,8 @@ async function diceSpent(root, context, question, recipeName, given, words) {
289
348
  // A call stopped after some dice: what they gave reaches the master at the next one (ASK-14).
290
349
  spent: () => (rolls.length === 0 ? undefined : [`While your ask was stopped, ${spentText(before, page.shown())}`, ...notes].join("\n")),
291
350
  };
292
- const done = await context.page.spendDice(question, words.rest, words.done, page, context.signal);
351
+ const done = await context.page.spendDice(question, words.rest, words.done, page, context.signal, told.card)
352
+ .finally(() => (told.card === undefined ? undefined : context.page?.cardEnded?.(told.card)));
293
353
  if (done === 0) {
294
354
  logAnswer(root, context, question, [words.done], words.done);
295
355
  }
@@ -386,12 +446,23 @@ function formLabel(check, named) {
386
446
  const name = dice.length === 1 ? named(dice[0].replace(/^\+/, "")) : undefined;
387
447
  const shown = dice.map((term, index) => {
388
448
  const sign = term.startsWith("-") ? "−" : "+";
389
- const body = term.replace(/^[+-]/, "").replace(name === undefined ? /^1(?=d)/i : /^\d*(d(?:\d+|%)).*$/i, name === undefined ? "" : "$1");
449
+ const body = name === undefined ? term.replace(/^[+-]/, "").replace(/^1(?=d)/i, "") : keptDice(term.replace(/^[+-]/, ""));
390
450
  return index === 0 && sign === "+" ? body : `${sign} ${body}`;
391
451
  });
392
452
  const added = modifier === 0 ? "" : ` ${modifier < 0 ? "−" : "+"}${Math.abs(modifier)}`;
393
453
  return `${check.label} · ${shown.join(" ")}${added}${name === undefined ? "" : `, ${name}`}`;
394
454
  }
455
+ /** The dice a named roll keeps, as its name says the rest: 2d20kh1 is d20, 3d6kh2 is 2d6, 4d6dl1 is 3d6. */
456
+ function keptDice(term) {
457
+ const match = /^(\d*)(d(?:\d+|%))([kd][hl])(\d*)/i.exec(term);
458
+ if (match === null) {
459
+ return term.replace(/^\d*(d(?:\d+|%)).*$/i, "$1");
460
+ }
461
+ const [, count, die, rule, number] = match;
462
+ const told = Number(number === "" ? 1 : number);
463
+ const kept = rule.toLowerCase().startsWith("k") ? told : Number(count === "" ? 1 : count) - told;
464
+ return `${kept === 1 ? "" : kept}${die}`;
465
+ }
395
466
  /**
396
467
  * The player's answer, on the dashboard's page and in the host's form at once, where both are (ASK-13, D-455): the first answer wins and takes the other
397
468
  * away; one that never showed, a page not open or a form the host does not show, leaves the other to answer. Neither shown is absent: the master asks in words.
@@ -454,7 +525,7 @@ function readOption(text) {
454
525
  // The dice from the first word that is a die, so that 1d20+athletics - 1 and 1d20 + athletics are dice too; else the last word.
455
526
  const spaced = /^(.+?)\s+(\d*d(?:\d+|%|F)\S*(?:\s*[+-]\s*\S+)*)$/i.exec(text);
456
527
  const last = /^(.+?)\s+(\S+)$/.exec(text);
457
- const match = [spaced, last].find((candidate) => candidate !== null && isDice(namesAsZero(candidate[2])));
528
+ const match = [spaced, last].find((candidate) => candidate !== null && isCheckDice(candidate[2]));
458
529
  return match === undefined || match === null ? { label: text } : { label: match[1].trim(), notation: match[2] };
459
530
  }
460
531
  /**
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { readSettings, requireCampaign } from "../campaign/index.js";
3
+ import { fieldsRead } from "../core/formula.js";
3
4
  import { appendLogEntry } from "../core/log.js";
4
5
  import { defineCommand } from "../core/registry.js";
5
6
  import { comparableText, valueNamed, withArticle } from "../core/text.js";
@@ -9,18 +10,19 @@ import { addCoins, formatAmount, formatTotal, isSafePurse, namesCoins, payCoins,
9
10
  import { baseChain, baseFieldOf, baseValue, concernsPlayer, declaredKind, findPage, followersOf, goodsNamed, inheritedFields, isCounterField, isDeclaredUncounted, isPartyMember, isStandardField, keepersOf, kindNamed, ownField, stackName, stacksOf, systemPageNamed, textsIn, withPage, writePage, } from "../pages/index.js";
10
11
  import { effectGiving, effectiveFields, effectsOf, withValue } from "./effect-layer.js";
11
12
  import { damageLists, damageTaken } from "./game-damage.js";
13
+ import { spendableDice, spendDice } from "./game-dice-pool.js";
12
14
  import { checkEffectsReadable, saveEffects } from "./game-effects.js";
13
15
  import { fireEvents, nowDueNote } from "./game-events.js";
16
+ import { poolExample, restExample } from "./game-examples.js";
14
17
  import { experienceOf, newLevelNotes } from "./game-experience.js";
15
- import { spendableDice, spendDice } from "./game-hit-dice.js";
16
18
  import { screenNote, screenUp, sealHiddenRoll } from "./game-master-rolls.js";
17
19
  import { campaignCoins } from "./game-money.js";
20
+ import { allSaid, packagesCounterChanged } from "./game-package-hooks.js";
18
21
  import { logRecipeApplied, tooSoonNote } from "./game-recipe-pace.js";
19
22
  import { effectsAtRecipe, notBroughtBack, partyPages, recipeChoices, recipeNamed, recipeTargets } from "./game-recipes.js";
20
23
  import { keepingLossNote, restingEffectsNote, shieldNotes } from "./game-reminders.js";
21
24
  import { checkNotCopied, checkNotSystemPage, pageOrCopy, readOpenScene, updateScene } from "./game-scene.js";
22
25
  import { changeStack } from "./game-stacks.js";
23
- import { allSaid, systemCounterChanged } from "./game-system-code.js";
24
26
  import { thresholdNotes } from "./game-thresholds.js";
25
27
  import { newDatedLogEntry, readPresent } from "./game-time.js";
26
28
  import { campaignSystem, campaignWorld, missingSystemHint } from "./game-world.js";
@@ -35,21 +37,21 @@ export const change = defineCommand({
35
37
  name: "change",
36
38
  description: "Change a counter, money or a stack of goods on a page: hit points, uses, a progress track, an event's clock, coins, torches. "
37
39
  + "A counter is a field written as a number (20, from 0 up) or as current/max (12/12, from 0 to the maximum); create it with write, then change it only with this command. "
38
- + 'Money is a field in the campaign\'s coins, such as money: 34 gp 4 sp: spend "5 sp" pays and makes change, by "+20 gp" adds coins, to "10 gp" sets the purse. '
40
+ + 'Money is a field in the campaign\'s coins, such as money: 34 {{coin}} 4 {{smallCoin}}: spend "5 {{smallCoin}}" pays and makes change, by "+20 {{coin}}" adds coins, to "10 {{coin}}" sets the purse. '
39
41
  + "A stack of goods by its kind in place of the field, such as page Ettore, field Torch, spend 1. "
40
42
  + "recipe applies a rest of the game system once you have advanced its hours. "
41
- + 'Example: page Bruna, field hp, by -7, why "bitten by the wolf"; or recipe "long rest".',
43
+ + 'Example: page Bruna, field {{counter}}, by -3, why "bitten by the wolf"; or recipe "{{rest}}".',
42
44
  group: "game",
43
45
  positionals: ["page", "field"],
44
46
  input: z.object({
45
47
  page: z.string().optional().describe("page that holds the counter or the money; with a recipe, left out for the player character and the companions with them"),
46
- field: z.string().optional().describe("the counter or the money, such as hp, or the kind of a stack, such as Torch; none with a recipe"),
48
+ field: z.string().optional().describe("the counter or the money, such as {{counter}}, or the kind of a stack, such as Torch; none with a recipe"),
47
49
  by: z.union([wholeNumber, z.string()]).optional().describe("how much to add, or to take away when negative, or coins; stops at a limit (damage, healing); on the command line write --by=-7. Dice are rolled here: by -(2d6+3) takes away 2d6+3, by -2d6 a die alone, as the game's rules have them rolled; taking away from the party, the master's roll, hidden or shown as master-rolls says"),
48
50
  spend: z.union([wholeNumber, z.string()]).optional().describe("how much is paid or used up, or coins; refused when there is not enough"),
49
51
  to: z.union([z.number().int(), z.string()]).optional().describe("the new value, even outside the limits: a number, max, current/max such as 15/15 (the maximum changes too), or coins; on the command line write --to=-3"),
50
52
  why: z.string().optional().describe("what the change is for"),
51
53
  damage: z.string().optional().describe("the type of the damage, with by negative and as rolled, never halved or doubled by you, such as by -12, damage fire: the page's resistances, immunities and vulnerabilities change it; one call per type"),
52
- recipe: z.string().optional().describe("a recipe of the game system, such as long rest; with a page, field and spend, the dice it lets one spend, such as hit-dice-d8, spend 2, recipe short rest"),
54
+ recipe: z.string().optional().describe("a rest of the game system, by its name; with a page, field and spend, the pool of dice it lets one spend, such as field {{pool}}, spend 2"),
53
55
  values: faceValues.optional().describe("with spend and a recipe, the faces the player rolled with physical dice, one for each die, such as 6,1"),
54
56
  }),
55
57
  run(input, context) {
@@ -59,10 +61,13 @@ export const change = defineCommand({
59
61
  return recipeResult(root, context, world, { ...input, recipe: input.recipe });
60
62
  }
61
63
  if (input.values !== undefined) {
62
- throw new Error('Give values with the dice of a recipe: page, field, spend and recipe, such as page Bruna, field hit-dice-d8, spend 2, recipe "short rest", values 6,1. Nothing changed.');
64
+ const pool = poolExample(campaignSystem(root, context));
65
+ throw new Error(`Give values with the dice of a recipe: page, field, spend and recipe, such as page ${input.page ?? "Bruna"}, field ${pool.field}, spend 2, recipe "${pool.recipe}", values 6,1. Nothing changed.`);
63
66
  }
64
67
  if (input.page === undefined || input.field === undefined) {
65
- throw new Error('Give the page and the field, such as page Bruna, field hp, by -7; or a recipe of the game system, such as recipe "long rest".');
68
+ const system = campaignSystem(root, context);
69
+ const counter = system?.damage?.counter ?? system?.combat?.track ?? "health";
70
+ throw new Error(`Give the page and the field, such as page ${input.page ?? "Bruna"}, field ${counter}, by -3; or a recipe of the game system, such as recipe "${restExample(system)}".`);
66
71
  }
67
72
  // Dice in by are rolled first and logged once the change is made (D-459): one call for a roll and its damage.
68
73
  const roll = diceBy(input.by, context);
@@ -70,7 +75,7 @@ export const change = defineCommand({
70
75
  const { hitCounter, ...result } = changeField(root, context, world, { ...input, page: input.page, field: input.field, ...(roll === undefined ? {} : { by: roll.by }) });
71
76
  const hiddenRoll = roll === undefined ? undefined : logDiceBy(root, context, { ...roll.data, why: input.why ?? `${input.field} of ${input.page}` }, hiding);
72
77
  // The game system's code follows the change, after the roll that made it (D-448): as the 5e's dying point.
73
- const lines = hitCounter === undefined ? [] : allSaid(systemCounterChanged(root, context, hitCounter));
78
+ const lines = hitCounter === undefined ? [] : allSaid(packagesCounterChanged(root, context, hitCounter));
74
79
  const told = lines.length === 0 ? result : { ...result, reminders: [...result.reminders, ...lines] };
75
80
  return roll === undefined ? told : { ...told, rolled: roll.data.result, ...(hiddenRoll === undefined ? {} : { hiddenRoll }) };
76
81
  },
@@ -89,7 +94,7 @@ export const change = defineCommand({
89
94
  });
90
95
  /** Changes a counter, money or a stack on a page as the input asks: by, spend or to, a damage type with its lists, then what the change sets off. */
91
96
  function changeField(root, context, world, input) {
92
- const holder = holderNamed(root, world, input.page);
97
+ const holder = holderNamed(root, world, input.page, input.field);
93
98
  const fields = withDeclaredStart(world, holder, effectiveFields(world, holder.page), input.field);
94
99
  // A name that is no field of the page, nor one the system declares, may be a kind the page holds a stack of (STK-5).
95
100
  const kind = holdsField(world, fields, input.field) ? undefined : kindNamed(world, holder.kind === "page" ? holder.page : undefined, input.field) ?? countable(world, input.field);
@@ -384,7 +389,7 @@ function recipeResult(root, context, world, input) {
384
389
  return { recipe: recipe.name, system: system.name, outcomes: [], rules: [], spent: spendDice(root, context, world, { system, recipe }, page, input.field, input.spend, { why, values: input.values }).text };
385
390
  }
386
391
  if (input.field !== undefined || input.by !== undefined || input.spend !== undefined || input.to !== undefined || input.values !== undefined) {
387
- throw new Error('A recipe changes by itself the fields it names: give it with the page, or alone for the player character and the companions with them, such as recipe "long rest". Nothing changed.');
392
+ throw new Error(`A recipe changes by itself the fields it names: give it with the page, or alone for the player character and the companions with them, such as recipe "${restExample(named)}". Nothing changed.`);
388
393
  }
389
394
  const { system, recipe } = recipeNamed(named, input.recipe);
390
395
  const pages = page === undefined ? partyPages(world) : [recipePage(root, world, page)];
@@ -543,6 +548,7 @@ function counterStep(input, value, page, field, coins, limits = {}) {
543
548
  const raise = limits.hint?.raise === undefined ? "" : `; to raise the maximum, write ${limits.hint.raise}; to change it for a while, as a drain, give an effect that sets ${limits.hint.raise}`;
544
549
  throw new Error(`The maximum of ${field} on ${page} is worked out by the game system: ${limits.hint?.made ?? limits.max}. Give the current value alone, such as to ${Math.min(counterChange.to.value, limits.max)}${raise}. Nothing changed.`);
545
550
  }
551
+ // A value given with to keeps the minimum the system gives, for where it stands: 0 is no limit of a counter that goes below it.
546
552
  const { counter: after, beyond } = changeCounter(before, counterChange);
547
553
  // Above a maximum the game system works out, a value reads as the maximum (FOR-6): what change says it wrote would not be what is read.
548
554
  if ("to" in counterChange && limits.max !== undefined && after.value > limits.max) {
@@ -556,7 +562,7 @@ function counterStep(input, value, page, field, coins, limits = {}) {
556
562
  const counter = readCounter(base);
557
563
  return counter !== undefined && formatCounter(counter) === formatCounter(after);
558
564
  };
559
- return { before: formatCounter(before), after: formatCounter(after), amount: { ...amountOf(counterChange), beyond: beyond === 0 ? undefined : beyond }, note: limitNote(after, beyond), same };
565
+ return { before: formatCounter(before), after: formatCounter(after), amount: { ...amountOf(counterChange), beyond: beyond === 0 ? undefined : beyond }, note: limitNote({ ...after, min: after.min ?? before.min }, beyond), same };
560
566
  }
561
567
  /** A counter as the page keeps it: with the maximum the game system works out from the page without its effects, which the reading puts back (FOR-6). */
562
568
  function storedCounter(world, holder, field, value) {
@@ -643,10 +649,10 @@ function checkClock(page, field, after) {
643
649
  function coinNames(coins) {
644
650
  return coins.map((coin) => coin.names.join("/")).join(", ");
645
651
  }
646
- /** What holds the counter, given by name or as a link: a copy in the open scene first, then a page of the campaign. */
647
- function holderNamed(root, world, name) {
652
+ /** What holds the counter, given by name or as a link: a copy in the open scene first, then a page of the campaign; the field asked names the example. */
653
+ function holderNamed(root, world, name, field) {
648
654
  const open = readOpenScene(root);
649
- const found = pageOrCopy(world, open, name, (page) => `a counter is a field of the page, such as page ${page}, field hp`);
655
+ const found = pageOrCopy(world, open, name, (page) => `a counter is a field of the page, such as page ${page}${field === undefined ? "" : `, field ${field}`}`);
650
656
  const copy = found.copy;
651
657
  if (copy !== undefined) {
652
658
  const write = (fields) => {
@@ -710,7 +716,10 @@ function fieldName(world, holder, fields, name, example, coins, suggested) {
710
716
  const listed = held.length > 0 ? `Its counters${hasMoney ? " and money" : ""}: ${held.join(", ")}.` : "It has no counters.";
711
717
  // A counter the system gives who has what it comes from is not added by hand, as a warlock's spell-slots to a wizard (DAT-9).
712
718
  const given = Object.keys(world.system?.formulas?.counters ?? {}).find((counter) => comparableText(counter) === comparableText(name.trim()));
713
- if (given !== undefined && holder.kind === "page" && hasSheet(world, page)) {
719
+ // A maximum that reads nothing, as a track of 5, is everyone's: it is written by hand as any other counter.
720
+ const max = given === undefined ? undefined : world.system?.formulas?.counters[given]?.max;
721
+ const everyones = max !== undefined && fieldsRead(max).length === 0;
722
+ if (given !== undefined && !everyones && holder.kind === "page" && hasSheet(world, page)) {
714
723
  const sources = maximumSources(world, given, fields);
715
724
  const whence = sources.length === 0 ? `the tables of its ${world.system?.progression?.list ?? "lists"}` : sources.join(", ");
716
725
  throw new Error(`${page.name} has no ${given}: the system ${world.system?.name ?? ""} gives it from ${whence}, and ${page.name} has none from them. ${listed}`);
@@ -719,7 +728,9 @@ function fieldName(world, holder, fields, name, example, coins, suggested) {
719
728
  const stacks = holder.kind === "page" ? stacksOf(world, page).map((stack) => `${stackName(stack)} ${stack.count}`) : [];
720
729
  const goods = goodsNamed(world, name);
721
730
  const counted = stacks.length === 0 ? "" : `Its stacks: ${stacks.join(", ")}. `;
722
- const how = goods === undefined ? howToAdd(world, holder, name, example) : `Goods are a stack, changed by its kind, such as change ${page.name}, ${goods.name}, spend 1.`;
731
+ // Its maximum, everyone's, in the example: the master writes it as the system works it out (FOR-7).
732
+ const shown = everyones && given !== undefined ? `0/${counterLimits(world, fields, given).max ?? 0}` : example;
733
+ const how = goods === undefined ? howToAdd(world, holder, name, shown) : `Goods are a stack, changed by its kind, such as change ${page.name}, ${goods.name}, spend 1.`;
723
734
  throw new Error(`${page.name} has no field "${name}". ${counted}${listed} ${how}`);
724
735
  }
725
736
  /** An item a name means that may be counted though no stack counts it yet, as a kind of the campaign spent to 0 everywhere: change says how to write its stack (STK-5). */