Skip to content

Author game rules as formulas, with pause and color markers in text - #53

Merged
lagergren merged 16 commits into
mainfrom
lagergren/rules-as-formulas
Oct 29, 2026
Merged

lagergren merged 16 commits into
mainfrom
lagergren/rules-as-formulas

Conversation

@lagergren

@lagergren lagergren commented Oct 29, 2026 •

Copy link
Copy Markdown
Owner

Follow-up to #52, one commit per step. Game rules the runtime computed in code are formulas in the game DSL now, and more text is written with inline markers and placeholders instead of helper calls and copied values.

Rules are formulas

The runtime only binds variables and evaluates what the game declares under formulas { }:

  • Spell cost: value = spellBaseCost + level, referenced as realm { spellCost }. The priest spells' withCurrentCasterCost(8) repeated a number that the baseCost in the spell header already set; it is withCurrentCasterCost { caster, cost -> } now.
  • Battle: playerHitChance, playerDamage, defendHealing, monsterHitChance, monsterDamage, monsterSpellChance, encounterWeaponSkill and encounterFoeCountMax.
  • Upkeep and tax: foodUpkeep and townEntryTax. The runtime never checked that a party could pay the tax, so a tax above the party's gold would have been paid down to 0 and let it in. A party that can't pay now sees the new town { entryTaxShortfall } prompt and stays outside: "There is a tax of 7% to enter Thord. You need 500 additional au to be able to pay." The game's tax is a share of the gold carried, so today it is always payable.
  • Shop prices: rationPrice, healingPotionPrice and sellPrice, through ShopPrices.formula(...). A sell section must name its price.

Formulas gain atLeast and atMost, and a plain number can stand on the left of an expression, so the game has no lit() left. The runtime draws the same random numbers in the same order as before, so replays play out unchanged. The test autopilot evaluates the combat formulas at their average instead of copying the rules. The runtime systems schema is 14, so the server needs a redeploy.

Markers and placeholders in text

  • One flowText: it takes strings and values. In every string a newline is a space, and a blank line or \n\n starts a new paragraph. The single-string form and the flowText { paragraph(...) } builder are gone, along with an unused lines { } overload. The compiled bundle is byte-identical after the change.
  • Trailing {pause}: a marker at the end of a text holds the page instead of showing it again. About a hundred writeText + pause…() pairs are single calls now, and pause600ms()…pause4s() are gone; pause(ms) stays.
  • Colored lines: a line that starts with {red} (or green, yellow, blue, magenta, cyan) is shown in that color. Two monster spells used raw ANSI escapes, which the browser drew as [31m…. The content check rejects raw escapes and markers that don't start a line.
  • Whole messages: battle pages, "Round N" and the castle thief's disarm line are single authored templates (BattleText.roundNumber, CastleText.thiefName) instead of fragments the runtime joined.
  • Placeholders: PartyText.memberCount/memberMax serve every "Who? (1-N)" prompt, a reward's messages can name the item, and mission(Missions.x).coordinates replaces the 6x20 and 42x23 copied into Tybalt's and Ron's speech.

Smaller DSL pieces

  • wound(), kill() and revive() on members and monsters. party.memberCount is read-only.
  • dungeons { randomEvents(...) } sets one event mix for all nine scenarios; level(13..19, …) and level(3, 6, 9, event = …) place an event on several levels.
  • orderDrink builds the inn and tavern menus from a table of drinks.
  • The castle scenes are Scenes.Castle handles; townSystem { image } names the street view.
  • Local collections are buildList/buildMap/buildString or folds instead of filled mutable locals.
  • docs/dsl-authoring.md documents the formulas, the variables each system binds, and the new placeholders.

What players will notice

  • Living count: raising the dead at the church no longer leaves the living count one too high, and the poison potion no longer leaves it one too low.
  • Ron's prompt: with a full pack, Ron says "You can't carry the Admt. Mail." instead of the cut-off "You can't carry all the".
  • "Who?" prompts: these show the actual party size.
  • Ydarg's guardian: the give menu lists the stairs items and leaves on RETURN, instead of a "5. Nothing" row.
  • Tavern drinks: they heal only living members, as the inn's do.
  • Colored lines: "X DIES!" shows in red in the browser.

Tests

  • New tests: a trailing pause holds the page once, colored lines keep their color across wrapped rows and in the bitmap frame, the church raise counts the living once, priest spells charge the formula's cost, the inn lists each drink with its price, a full inventory names the reward, a party short of the town tax is told what it lacks and kept out (the paying path now has a runtime test too), and flow text splits paragraphs at blank lines.
  • Results: ./gradlew check --rerun-tasks --no-build-cache passes at the head: 243 tests, 0 failures, 0 skipped. The dungeon event commit was also built and tested on its own.

Not checked by hand: the colored lines were not looked at in a browser, and the build has not been deployed.

A {pause} at the very end of a text now holds the page that long
instead of showing it a second time, and appendText takes one there.
About a hundred writeText calls followed by a pause became one call,
such as writeText("No money - No drink! {pause 1s}"), and the
pause600ms() to pause4s() aliases are gone. pause(ms) stays for the
one beat between a sound and the line after it.

writeText always starts a fresh page, so the clearText() calls just
before one did nothing and are removed, and writeText, waitInput and
clearText in a row are showTextAndWait. The battle runner's clearText
now also forgets the page, so an appendText after it no longer brings
the cleared text back.
Two monster spells colored "X DIES!" with raw ANSI escapes, which the
browser drew as "[31m...". A line or paragraph that starts with {red},
or green, yellow, blue, magenta or cyan, is now shown in that color:

- Compiled text starts the line with the color's escape, and the line
  wrapper keeps it on every row the line wraps to.
- The terminal resets the color after each colored row.
- The bitmap frame sends the line as plain text and names its color in
  textLineColors, which the browser draws.

The content check rejects raw escape codes, and a color marker anywhere
but the start of a line.
The runtime counts the living members again after every member write,
but the church raise, Rebirth and the poison potion also changed
party.memberCount by hand: the church left it one too high and the
potion one too low. memberCount is read-only now.

Members and monsters get wound(amount), which kills at zero hit
points, kill() and revive(), in place of the hit point and death
bookkeeping each spell and item repeated.
Battle charged a mage spell its base cost plus the caster's level in
code, and each priest spell repeated its cost as
withCurrentCasterCost(8) next to the baseCost in its header, which was
the number actually charged.

The game now declares formula(Formulas.spellCost) with
value = spellBaseCost + level and points realm { spellCost } at it.
Battle and the priest spell runner evaluate it for the caster, and
withCurrentCasterCost { caster, cost -> } hands the result to the
script. The runtime systems schema is 14.
Function-local lists, sets, maps and strings that were filled and then
only read are buildList, buildSet, buildMap, buildString or a plain
functional expression, var accumulators are folds, and the public
MutableList on SwitchBuilder and the flag registry are read-only views.

DSL builders, runtime state machines, RNG threading and test fakes that
record calls keep their mutable state.
The runtime worked out hit chance, damage, a monster's chance to cast,
the healing a defending member gets, how encounters grow with the
leader's level, the food the party eats and the town entry tax in
code, with only some constants authored. They are formulas now:

- playerRound and monsterRound name playerHitChance, playerDamage,
  defendHealing, monsterSpellChance, monsterHitChance and
  monsterDamage.
- standardBattle names encounterFoeCountMax and encounterWeaponSkill.
- upkeep { foodCost } and entryTax { amount } name foodUpkeep and
  townEntryTax.

The runtime binds the same values and draws the same random numbers in
the same order, so replays play out exactly as before. Formulas gain
atLeast and atMost, a plain number can stand on the left of an
expression, and the hunt, disarm and haggle formulas no longer need
lit(). The test autopilot evaluates the combat formulas at their
average instead of copying the rules, and the town street view is
authored as townSystem { image } instead of named in the runtime.
Shops chose prices from schemes coded in the runtime: the leader's
level plus a number, an item's cost plus the level times a number, and
half the cost when the shop buys. A price is now the item's cost, a
fixed amount or ShopPrices.formula(...), and the game declares
rationPrice, healingPotionPrice and sellPrice. A sell section names its
price instead of falling back to half the cost.
The runtime assembled battle pages from fragments, wrote "Round N"
itself, and joined the castle thief's name to a trapTriesDisarmSuffix.
Each message is one authored template now:

- encounter and nextRound replace encounterBanner, youFace,
  foeDisplayName and stillFace; nextRound shows BattleText.roundNumber.
- victoryReward and victoryLoot absorb victoryEachSurvivor and
  victoryFoundObject.
- trapTriesDisarm names the thief with CastleText.thiefName.

The drop message names the item with InventoryText.itemName instead of
a raw TextPart.
The castle's script roots were raw sceneId("castle.ydarg...") strings;
they are Scenes.Castle handles now. The guardian's give menu repeated
the stairs items' names and ended in a "5. Nothing" row that the
runtime knew by its digit. The runtime now lists the stairs items under
the authored givePrompt and leaves on RETURN, as other menus do.
All nine dungeon scenarios repeated the same eight weighted events.
dungeons { randomEvents(...) } now sets the mix of every scenario that
names none of its own, and level(13..19, ...) and
level(3, 6, 9, event = ...) put one event on several levels.
Scripts borrowed HuntText.partyMemberCount and partyMemberMax to write
"Who? (1-4)" in the church, spells and potions, and the equipment
prompt printed "Who? (1-N)" as written. PartyText.memberCount and
memberMax serve every prompt that lists the members.

A reward's messages can name the item with itemName, so Ron's drop
prompt says "You can't carry the Admt. Mail." instead of the cut-off
"You can't carry all the".
Tybalt and Ron gave 6x20 and 42x23 in their speech and in the journal,
copied from their missions' at(xy(...)). mission(Missions.x).coordinates
shows the mission's square, or its location's placement, and the
runtime and the compiler share the coordinate format.
The inn and tavern repeated the same pay-and-heal block for every
drink, each price typed twice. orderDrink takes a table of drinks and
builds the menu rows and their options from it. The tavern's drinks
now heal only living members, as the inn's do.

pay takes a plain number, so the game has no lit() left, and the
clearText() calls before menus that start a fresh page are removed.
The authoring guide gains a Formulas section, listing the rules that
are formulas and the variables each system binds, and covers
PartyText, CastleText, BattleText.roundNumber, mission coordinates,
reward item names, shop prices, the shared dungeon event mix and the
menus the runtime builds.
The runtime never checked that a party could pay the town entry tax. A
tax larger than the party's gold would have been paid down to 0 gold
and let the party in. The game's tax is a share of the gold carried, so
this never happened, but the tax is an authored formula now.

A party that can't pay is shown the new town { entryTaxShortfall }
prompt instead of the pay-or-leave choice, and stays outside.
TownText.taxShortfall names the gold it lacks:

    There is a tax of 7% to enter Thord. You need 500 additional au
    to be able to pay.
flowText had three forms: a single string, whose blank lines started
paragraphs; strings and values, which made one paragraph; and a
flowText { paragraph(...) } builder for several paragraphs with values.
It has one now. flowText(...) takes strings and values, and in every
string a newline is a space and a blank line, or \n\n, starts a new
paragraph:

    flowText(
        townNpcName(NpcJobs.innkeeper),
        ", the Innkeeper welcomes you.",
        "\n\nDo you want supper, travelers?",
    )

The seven builder uses in the game are written this way, and the
compiled bundle is byte for byte the same. The lines { } overload, which
only ran its block, is gone too.
@lagergren
lagergren merged commit efbf304 into main Oct 29, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant