From 2c49b6791bdcb7c7438f4e5179207364ccba526b Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:16 +0100 Subject: [PATCH 01/16] Hold a page with a trailing {pause} marker 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. --- core/src/main/kotlin/rylween/dsl/Dsl.kt | 26 +- core/src/main/kotlin/rylween/dsl/TextDsl.kt | 72 ++- docs/dsl-authoring.md | 19 +- .../main/kotlin/rylween/game/RylweenGame.kt | 536 ++++++------------ .../kotlin/rylween/runtime/BattleRunner.kt | 6 +- .../rylween/runtime/ScriptExecutorTest.kt | 39 +- 6 files changed, 247 insertions(+), 451 deletions(-) diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index 7e8fd894..cc349c34 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -126,11 +126,14 @@ class ScriptScope( * Adds text below what the text window already shows, so a beat such as * "...you reveal nothing but..." can be followed, after a pause, by "dust..." * on the same page. Flow text is a new paragraph and gets a blank line - * above it; literal lines continue directly below, exactly as written. + * above it; literal lines continue directly below, exactly as written. A + * `{pause}` marker at the end holds the page that long. */ fun appendText(text: TextBlock) { - require(text.beats().size == 1) { "appendText cannot hold {pause} markers; put the beats in writeText" } - record(ScriptStatementNode.Screen(text, append = true)) + val beat = text.beats().singleOrNull() + requireNotNull(beat) { "appendText takes a {pause} marker only at the end of its text; put earlier beats in writeText" } + record(ScriptStatementNode.Screen(beat.text, append = true)) + beat.pauseMillis?.let(::pause) } fun appendText(text: String): Unit = appendText(flowText(text)) @@ -164,20 +167,13 @@ class ScriptScope( fun waitInput(reason: String? = null): Unit = record(ScriptStatementNode.WaitInput(reason)) + /** + * Waits [ms] milliseconds. A pause that holds text belongs in the text as a + * `{pause}` marker; this is for a beat between other things, such as a + * sound and the line that follows it. + */ fun pause(ms: Int): Unit = record(ScriptStatementNode.Pause(ms)) - fun pause600ms(): Unit = pause(600) - - fun pause1s(): Unit = pause(1_000) - - fun pause1500ms(): Unit = pause(1_500) - - fun pause2s(): Unit = pause(2_000) - - fun pause3s(): Unit = pause(3_000) - - fun pause4s(): Unit = pause(4_000) - fun clearText(): Unit = view.clearText() fun clearMapWindow(): Unit = view.clearMapWindow() diff --git a/core/src/main/kotlin/rylween/dsl/TextDsl.kt b/core/src/main/kotlin/rylween/dsl/TextDsl.kt index 1cdfe61f..844a9609 100644 --- a/core/src/main/kotlin/rylween/dsl/TextDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/TextDsl.kt @@ -32,7 +32,8 @@ sealed interface TextPart { * A beat in script text, written `{pause}`, `{pause 1.5s}` or `{pause 600ms}` * inside a string. [ScriptScope.writeText] and [ScriptScope.showTextAndWait] * show the text up to the beat, pause, then show the page again with more of - * it; no other text accepts one. + * it; a beat at the very end holds the page that long. [ScriptScope.appendText] + * takes a beat only at the end; no other text accepts one. */ data class Pause( val millis: Int, @@ -329,16 +330,11 @@ private val pauseMarker = Regex("""\{pause(?:\s+(\d+(?:\.\d+)?)\s*(ms|s))?\}""") /** Splits literal text at its `{pause}` markers; text without one stays a single literal. */ private fun literalParts(text: String): List { - if (!pauseMarker.containsMatchIn(text)) return listOf(TextPart.Literal(text)) - val parts = mutableListOf() - var rest = 0 - pauseMarker.findAll(text).forEach { marker -> - text.substring(rest, marker.range.first).takeIf(String::isNotEmpty)?.let { before -> parts += TextPart.Literal(before) } - parts += TextPart.Pause(marker.pauseMillis()) - rest = marker.range.last + 1 + val pauses = pauseMarker.findAll(text).map { marker -> TextPart.Pause(marker.pauseMillis()) }.toList() + if (pauses.isEmpty()) return listOf(TextPart.Literal(text)) + return text.split(pauseMarker).flatMapIndexed { index, piece -> + listOfNotNull(piece.takeIf(String::isNotEmpty)?.let { literal -> TextPart.Literal(literal) }, pauses.getOrNull(index)) } - text.substring(rest).takeIf(String::isNotEmpty)?.let { after -> parts += TextPart.Literal(after) } - return parts } private fun MatchResult.pauseMillis(): Int { @@ -346,7 +342,7 @@ private fun MatchResult.pauseMillis(): Int { return if (groupValues[2] == "s") (amount * 1_000).toInt() else amount.toInt() } -/** One step of text shown with `{pause}` beats: the text so far, then the pause after it; the last step has none. */ +/** One step of text shown with `{pause}` beats: the text so far, then the pause after it, if any. */ internal data class TextBeat( val text: TextBlock, val pauseMillis: Int?, @@ -355,7 +351,8 @@ internal data class TextBeat( /** * The steps [ScriptScope.writeText] shows this text in: one per `{pause}` * marker, each with everything up to that marker, and a last one with the - * whole text. Text without markers is a single step. + * whole text. A marker at the very end holds the whole text, so it adds no + * step of its own. Text without markers is a single step. */ internal fun TextBlock.beats(): List { val rows = @@ -365,17 +362,18 @@ internal fun TextBlock.beats(): List { is TextBlock.Flow -> paragraphs } if (rows.none { row -> row.parts.any { part -> part is TextPart.Pause } }) return listOf(TextBeat(this, null)) - val beats = mutableListOf() - rows.forEachIndexed { rowIndex, row -> - row.parts.forEachIndexed { partIndex, part -> - if (part is TextPart.Pause) { - val partial = TextLine(row.parts.take(partIndex)).withoutPauses() - val shown = rows.take(rowIndex).map(TextLine::withoutPauses) + listOfNotNull(partial.takeIf { it.parts.isNotEmpty() }) - beats += TextBeat(withRows(shown), part.millis) + val beats = + rows.flatMapIndexed { rowIndex, row -> + row.parts.mapIndexedNotNull { partIndex, part -> + (part as? TextPart.Pause)?.let { pause -> + val partial = TextLine(row.parts.take(partIndex)).withoutPauses() + val shown = rows.take(rowIndex).map(TextLine::withoutPauses) + listOfNotNull(partial.takeIf { it.parts.isNotEmpty() }) + TextBeat(withRows(shown), pause.millis) + } } } - } - return beats + TextBeat(withRows(rows.map(TextLine::withoutPauses)), null) + val whole = withRows(rows.map(TextLine::withoutPauses)) + return if (beats.last().text == whole) beats else beats + TextBeat(whole, null) } /** @@ -384,26 +382,22 @@ internal fun TextBlock.beats(): List { * "but... dust..."; a line that ends at a beat drops the space before it. */ private fun TextLine.withoutPauses(): TextLine { - val joined = mutableListOf() - var afterPause = false - parts.forEach { part -> - val previous = joined.lastOrNull() as? TextPart.Literal - when { - part is TextPart.Pause -> afterPause = true - afterPause && previous != null && part is TextPart.Literal -> { - val spaced = previous.text.endsWith(' ') || part.text.startsWith(' ') - joined[joined.lastIndex] = TextPart.Literal(previous.text.trimEnd() + (if (spaced) " " else "") + part.text.trimStart()) - afterPause = false - } - else -> { - joined += part - afterPause = false + val (joined, _) = + parts.fold(emptyList() to false) { (joined, afterPause), part -> + val previous = joined.lastOrNull() as? TextPart.Literal + when { + part is TextPart.Pause -> joined to true + afterPause && previous != null && part is TextPart.Literal -> joined.dropLast(1) + previous.joinedAcrossPause(part) to false + else -> joined + part to false } } - } - val last = joined.lastOrNull() as? TextPart.Literal - if (last != null) joined[joined.lastIndex] = TextPart.Literal(last.text.trimEnd()) - return TextLine(joined) + val last = joined.lastOrNull() as? TextPart.Literal ?: return TextLine(joined) + return TextLine(joined.dropLast(1) + TextPart.Literal(last.text.trimEnd())) +} + +private fun TextPart.Literal.joinedAcrossPause(next: TextPart.Literal): TextPart.Literal { + val spaced = text.endsWith(' ') || next.text.startsWith(' ') + return TextPart.Literal(text.trimEnd() + (if (spaced) " " else "") + next.text.trimStart()) } private fun TextBlock.withRows(rows: List): TextBlock = diff --git a/docs/dsl-authoring.md b/docs/dsl-authoring.md index b77c41c8..b1fd6695 100644 --- a/docs/dsl-authoring.md +++ b/docs/dsl-authoring.md @@ -172,11 +172,11 @@ scene(Scenes.Missions.bandits) { } ``` -`writeText(...)` starts a fresh page in the text window, and `appendText(...)` -adds below what the page already shows; appended flow text gets a blank line -above it, appended literal lines continue directly below. `showTextAndWait(...)` -is the read-and-dismiss page verb: it writes text, waits for Return/Enter, and -clears the text window. +`writeText(...)` starts a fresh page in the text window, so it needs no +`clearText()` before it, and `appendText(...)` adds below what the page already +shows; appended flow text gets a blank line above it, appended literal lines +continue directly below. `showTextAndWait(...)` is the read-and-dismiss page +verb: it writes text, waits for Return/Enter, and clears the text window. Text must stay on screen until something holds it: a `waitInput()`, a pause, or a menu whose prompt only lists its choices (such a menu keeps the page above @@ -205,10 +205,11 @@ writeText( writeText(flowText(partyName(caster), " utters three syllables in an archaic tongue... {pause 2s} and the ground cracks open!")) ``` -Markers work only in those two verbs; any other text that holds one, such as a -menu prompt, a journal entry or `appendText`, is rejected. Keep a separate -`pause(...)` where something else happens at the beat, such as a sound cue or a -new page. +A marker at the very end of the text holds the page that long, so a short +notice is one call: `writeText("No money - No drink! {pause 1s}")`. That is +also the only place `appendText` takes one. Any other text that holds a marker, +such as a menu prompt or a journal entry, is rejected. `pause(ms)` is left for a +beat between two other things, such as a sound cue and the line after it. Literal lines are rows, not hand-wrapped prose: put each sentence on one line and let the renderer wrap it to the window, and break the line only where a new diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 49b60542..1f2f8afb 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -1700,9 +1700,7 @@ val authoredRylween: RylweenModel = localInt(0) { thiefFound -> forEachMember { whenever((thiefFound eq 0) and it.isClass(PcClass.Thief)) { - clearText() - writeText(flowText(partyName(it), " checks the chest for traps.")) - pause1s() + writeText(flowText(partyName(it), " checks the chest for traps. {pause 1s}")) trapChance set lit(40) - it.dexterity * 2 / 5 whenever(trapChance lt 4) { trapChance set 4 @@ -1712,10 +1710,8 @@ val authoredRylween: RylweenModel = } whenever(random(0..99) lt trapChance) { - clearText() showBackdrop(Images.Dungeon.trap) - writeText("A TRAP!") - pause600ms() + writeText("A TRAP! {pause 600ms}") choose(random(0..2)) { case(0) { playSound(Sounds.Explore.trapGas) @@ -1759,7 +1755,6 @@ val authoredRylween: RylweenModel = waitInput("after chest trap") } - clearText() localInt(random(0..99) + 320 + (party.leader.experience / 500)) { goldAmount -> writeText(flowText("The chest contained ", goldAmount, " pieces of gold.")) gainGold(goldAmount) @@ -2154,10 +2149,9 @@ val authoredRylween: RylweenModel = """ - GUARDS! GUARDS! - (Hobgoblin guards rush to confront you.) + (Hobgoblin guards rush to confront you.) {pause 2s} """, ) - pause2s() encounter(Monsters.hobgoblin, mandatory = true) encounter(Monsters.hobgoblinChief, mandatory = true) }, @@ -2750,8 +2744,7 @@ val authoredRylween: RylweenModel = pay( price, broke = { - writeText("- No money, eh? Don't bother to come back!") - pause2s() + writeText("- No money, eh? Don't bother to come back! {pause 2s}") }, ok = { forEachMember { @@ -2763,10 +2756,9 @@ val authoredRylween: RylweenModel = """ You spend a very exhausting hour upstairs. - (PERVERT!) ;-) + (PERVERT!) ;-) {pause 2s} """, ) - pause2s() }, ) }, @@ -3922,10 +3914,9 @@ val authoredRylween: RylweenModel = ) writeText( """ - A glowing energy sphere appears, and at a gesture from Ydarg's stick, it hurtles towards you!!! + A glowing energy sphere appears, and at a gesture from Ydarg's stick, it hurtles towards you!!! {pause 3s} """, ) - pause3s() showTextAndWait( """ Suddenly! You feel someone else near. The four gray-clad mages raise their hands, and the sphere is absorbed by their hands! @@ -3962,10 +3953,9 @@ val authoredRylween: RylweenModel = """, ) playSound(Sounds.Combat.monsterDissolve) - pause2s() + pause(2_000) appendText(literalText("dust...")) waitInput("after Ydarg turns to dust") - clearText() writeText( """ CONGRATULATIONS! @@ -4032,32 +4022,32 @@ val authoredRylween: RylweenModel = ) { m -> whenever(m.dead) { playSound(Sounds.Town.thrownOut) - writeText("- GET THAT CORPSE OUTTA HERE! (You are thrown out).") - pause1500ms() + writeText("- GET THAT CORPSE OUTTA HERE! (You are thrown out). {pause}") breakLoop("corpse exits the church service") } otherwise { whenever(m.hp eq m.maxHp) { writeText { - line(partyName(m), " needs no healing.") + line(partyName(m), " needs no healing. {pause 1s}") } - pause1s() } otherwise { localInt((m.maxHp - m.hp) * 7) { price -> - clearText() writeText(flowText("- That'll be ", price, " gold coins, please.")) choice.payNoThanks( price, broke = { - writeText("You don't have enough gold!") - pause1s() + writeText("You don't have enough gold! {pause 1s}") }, paid = { - clearText() m.hp set m.maxHp playSound(Sounds.Spell.heal) - writeText(flowText("The priestess heals ", pronoun(m, PronounCase.Object), " fully.")) - pause1s() + writeText( + flowText( + "The priestess heals ", + pronoun(m, PronounCase.Object), + " fully. {pause 1s}", + ), + ) }, ) } @@ -4074,34 +4064,29 @@ val authoredRylween: RylweenModel = accepting = MemberChoiceFilter.Any, ) { m -> whenever(!m.spellcaster) { - clearText() - writeText("Not a spellcaster!") - pause1s() + writeText("Not a spellcaster! {pause 1s}") } otherwise { whenever(m.mp eq m.wisdom) { - clearText() - writeText("That character needs no spell points to be restored.") - pause2s() + writeText("That character needs no spell points to be restored. {pause 2s}") } otherwise { - clearText() localInt(m.level * (m.wisdom - m.mp) * 2) { price -> writeText(flowText("- That will be ", price, " gold coins, please.")) choice.payNoThanks( price, broke = { - clearText() - writeText("You don't have the gold!") - pause1s() + writeText("You don't have the gold! {pause 1s}") }, paid = { m.mp set m.wisdom - clearText() playSound(Sounds.Spell.mana) writeText( - flowText("The priestess restores ", pronoun(m, PronounCase.Possessive), " energy."), + flowText( + "The priestess restores ", + pronoun(m, PronounCase.Possessive), + " energy. {pause 1s}", + ), ) - pause1s() }, ) } @@ -4118,29 +4103,22 @@ val authoredRylween: RylweenModel = accepting = MemberChoiceFilter.Any, ) { m -> whenever(!m.dead) { - clearText() - writeText(flowText("- ", partyName(m), " seems very alive at the moment.")) - pause1500ms() + writeText(flowText("- ", partyName(m), " seems very alive at the moment. {pause}")) } otherwise { - clearText() localInt(m.level * 650) { price -> writeText(flowText("- That will be ", price, " gold coins, please.")) choice.payNoThanks( price, broke = { - clearText() - writeText("You don't have the gold!") - pause1s() + writeText("You don't have the gold! {pause 1s}") }, paid = { m.hp set 1 m.dead set false party.memberCount += 1 - clearText() playSound(Sounds.Spell.rebirth) - writeText(flowText("The priestess raises ", pronoun(m, PronounCase.Object), ".")) - pause1s() + writeText(flowText("The priestess raises ", pronoun(m, PronounCase.Object), ". {pause 1s}")) }, ) } @@ -4283,7 +4261,6 @@ val authoredRylween: RylweenModel = loop { localInt((party.leader.level * party.leader.level) * 15) { cost -> - clearText() writeText( flowText { paragraph(townNpcName(NpcJobs.innkeeper), ", the Innkeeper welcomes you.") @@ -4297,21 +4274,18 @@ val authoredRylween: RylweenModel = pay( cost, broke = { - clearText() - writeText(flowText("Sorry, supper is ", cost, " gold.")) - pause1s() + writeText(flowText("Sorry, supper is ", cost, " gold. {pause 1s}")) }, ok = { clearText() playSound(Sounds.Town.meal) + healLivingMembers(6) writeText( """ You are served a tasty dinner. - Some of your health returns. + Some of your health returns. {pause 2s} """, ) - healLivingMembers(6) - pause2s() }, ) }, @@ -4339,15 +4313,11 @@ val authoredRylween: RylweenModel = pay( lit(2), broke = { - clearText() - writeText("No money - No drink!") - pause1s() + writeText("No money - No drink! {pause 1s}") }, ok = { - clearText() playSound(Sounds.Town.drink) - writeText("Ahh...!") - pause1s() + writeText("Ahh...! {pause 1s}") healLivingMembers((lit(2) / 2) + 1) }, ) @@ -4356,15 +4326,11 @@ val authoredRylween: RylweenModel = pay( lit(3), broke = { - clearText() - writeText("No money - No drink!") - pause1s() + writeText("No money - No drink! {pause 1s}") }, ok = { - clearText() playSound(Sounds.Town.drink) - writeText("Ahh...!") - pause1s() + writeText("Ahh...! {pause 1s}") healLivingMembers((lit(3) / 2) + 1) }, ) @@ -4373,15 +4339,11 @@ val authoredRylween: RylweenModel = pay( lit(5), broke = { - clearText() - writeText("No money - No drink!") - pause1s() + writeText("No money - No drink! {pause 1s}") }, ok = { - clearText() playSound(Sounds.Town.drink) - writeText("Ahh...!") - pause1s() + writeText("Ahh...! {pause 1s}") healLivingMembers((lit(5) / 2) + 1) }, ) @@ -4390,15 +4352,11 @@ val authoredRylween: RylweenModel = pay( lit(7), broke = { - clearText() - writeText("No money - No drink!") - pause1s() + writeText("No money - No drink! {pause 1s}") }, ok = { - clearText() playSound(Sounds.Town.drink) - writeText("Ahh...!") - pause1s() + writeText("Ahh...! {pause 1s}") healLivingMembers((lit(7) / 2) + 1) }, ) @@ -4407,14 +4365,10 @@ val authoredRylween: RylweenModel = pay( lit(1), broke = { - clearText() - writeText("No money - No drink!") - pause1s() + writeText("No money - No drink! {pause 1s}") }, ok = { - clearText() - writeText("The other guests giggle.") - pause1s() + writeText("The other guests giggle. {pause 1s}") healLivingMembers((lit(1) / 2) + 1) }, ) @@ -4430,7 +4384,6 @@ val authoredRylween: RylweenModel = "(Y)es", "(N)o", yes = { - clearText() writeText { line("A room is ", cost, " gold/night.") line("") @@ -4442,21 +4395,16 @@ val authoredRylween: RylweenModel = pay( cost, broke = { - clearText() playSound(Sounds.Town.thrownOut) - writeText("- AHA! No gold! You are thrown out.") - pause2s() + writeText("- AHA! No gold! You are thrown out. {pause 2s}") clearMapWindow() breakLoop("thrown out of inn") }, ok = { - clearText() - writeText("You go to bed...") - pause1s() + writeText("You go to bed... {pause 1s}") playSound(Sounds.Explore.rest) - writeText("Zzzz...") party.restedHours set 14 - pause1500ms() + writeText("Zzzz... {pause}") writeText( flowText( """ @@ -4485,7 +4433,6 @@ val authoredRylween: RylweenModel = }, no = { loop { - clearText() writeText("The innkeeper leaves.") menu("(C)hitchat with guests", "(L)eave") { option('C') { @@ -4596,9 +4543,7 @@ val authoredRylween: RylweenModel = scene(Scenes.Towne.tavern) { whenever((realm.hour lt 6) and (realm.hour gt 1)) { - clearText() - writeText("Tavern Closed.") - pause1s() + writeText("Tavern Closed. {pause 1s}") stop("tavern closed") } @@ -4613,17 +4558,15 @@ val authoredRylween: RylweenModel = } whenever(chance(priestBonus + 5)) { - clearText() writeText( """ Just as you are about to sit down at a table, a scruffy little man pulls at your sleeve... {pause 3s} - Hey, hey, hey! You! Yes... you! I have an offer - that may interest you... + that may interest you... {pause 3s} """, ) - pause3s() clearText() choice.randomItemOffer(ItemPools.tavernScruffySpecials) { offer { @@ -4640,7 +4583,6 @@ val authoredRylween: RylweenModel = localInt(0) { rumors -> loop { - clearText() writeText( flowText( "- Welcome! Have a seat ", @@ -4676,22 +4618,17 @@ val authoredRylween: RylweenModel = accepting = MemberChoiceFilter.Any, ) { storyteller -> whenever(storyteller.dead) { - clearText() - writeText("Dead men tell no stories...") - pause2s() + writeText("Dead men tell no stories... {pause 2s}") } otherwise { - clearText() writeText( flowText { paragraph(partyName(storyteller), " stands up and screams:") - paragraph("- ANYONE WHO WANNA HEAR A TRAVELER'S STORY?") + paragraph("- ANYONE WHO WANNA HEAR A TRAVELER'S STORY? {pause 2s}") }, ) - pause2s() playSound(Sounds.Town.crowdCheer) - writeText("- YEAAH! Roars the crowd!") - pause2s() + writeText("- YEAAH! Roars the crowd! {pause 2s}") localInt(0) { isBoast -> menu("(T)rue story", "(B)oast") { @@ -4718,12 +4655,9 @@ val authoredRylween: RylweenModel = whenever(isBoast eq 1) { whenever(random(0..99) gt storyteller.charisma) { - clearText() - writeText("- Out with the liar!") - pause2s() + writeText("- Out with the liar! {pause 2s}") playSound(Sounds.Town.thrownOut) - appendText("You are thrown out.") - pause1500ms() + appendText("You are thrown out. {pause}") whenever(storyteller.charisma gte 10) { storyteller.charisma -= 10 } otherwise { @@ -4738,24 +4672,20 @@ val authoredRylween: RylweenModel = whenever(score gt 400) { writeText( flowText( - "Superb Story! Let's give 'em some ale, lads! You are given a whole tray of ale!", + "Superb Story! Let's give 'em some ale, lads! You are given a whole tray of ale! {pause 2s}", ), ) - pause2s() storyteller.charisma += 3 } whenever((score gt 300) and (score lt 401)) { - writeText("Very good! You've been through much!") - pause2s() + writeText("Very good! You've been through much! {pause 2s}") storyteller.charisma += 1 } whenever((score gt 150) and (score lt 301)) { - writeText("Nice story, sir!") - pause2s() + writeText("Nice story, sir! {pause 2s}") } whenever((score gt 100) and (score lt 151)) { - writeText("The mob is bored.") - pause2s() + writeText("The mob is bored. {pause 2s}") whenever(storyteller.charisma gt 0) { storyteller.charisma -= 1 } @@ -4764,10 +4694,9 @@ val authoredRylween: RylweenModel = writeText( """ Most of the crowd falls asleep. - The rest beg you to stop. + The rest beg you to stop. {pause 2s} """, ) - pause2s() whenever(storyteller.charisma gte 3) { storyteller.charisma -= 3 } @@ -4792,29 +4721,28 @@ val authoredRylween: RylweenModel = writeText( """ After listening a while you hear an old - man say to another: + man say to another: {pause 600ms} """, ) } case(1) { - writeText("A drunken bard bellows:") + writeText("A drunken bard bellows: {pause 600ms}") } case(2) { - writeText("A halfling you rescued from a brawl whispers:") + writeText("A halfling you rescued from a brawl whispers: {pause 600ms}") } case(3) { writeText( """ The tavern keeper motions to you to come - closer, and whispers: + closer, and whispers: {pause 600ms} """, ) } case(4) { - writeText("A bargirl tells you:") + writeText("A bargirl tells you: {pause 600ms}") } } - pause600ms() tellRumor() waitInput("after tavern rumor") } @@ -4835,15 +4763,11 @@ val authoredRylween: RylweenModel = pay( lit(2), broke = { - clearText() - writeText("No money - No drink!") - pause1s() + writeText("No money - No drink! {pause 1s}") }, ok = { - clearText() playSound(Sounds.Town.drink) - writeText("AAH! (your health returns).") - pause1s() + writeText("AAH! (your health returns). {pause 1s}") forEachMember(includeDead = true) { it.hp.addClamped((lit(2) / 2) + 1, it.maxHp) } @@ -4854,15 +4778,11 @@ val authoredRylween: RylweenModel = pay( lit(3), broke = { - clearText() - writeText("No money - No drink!") - pause1s() + writeText("No money - No drink! {pause 1s}") }, ok = { - clearText() playSound(Sounds.Town.drink) - writeText("AAH! (your health returns).") - pause1s() + writeText("AAH! (your health returns). {pause 1s}") forEachMember(includeDead = true) { it.hp.addClamped((lit(3) / 2) + 1, it.maxHp) } @@ -4873,15 +4793,11 @@ val authoredRylween: RylweenModel = pay( lit(4), broke = { - clearText() - writeText("No money - No drink!") - pause1s() + writeText("No money - No drink! {pause 1s}") }, ok = { - clearText() playSound(Sounds.Town.drink) - writeText("AAH! (your health returns).") - pause1s() + writeText("AAH! (your health returns). {pause 1s}") forEachMember(includeDead = true) { it.hp.addClamped((lit(4) / 2) + 1, it.maxHp) } @@ -4892,14 +4808,10 @@ val authoredRylween: RylweenModel = pay( lit(1), broke = { - clearText() - writeText("No money - No drink!") - pause1s() + writeText("No money - No drink! {pause 1s}") }, ok = { - clearText() - writeText("You are the laughing stock of the entire tavern...") - pause2s() + writeText("You are the laughing stock of the entire tavern... {pause 2s}") forEachMember(includeDead = true) { it.hp.addClamped((lit(1) / 2) + 1, it.maxHp) } @@ -4948,10 +4860,8 @@ val authoredRylween: RylweenModel = scene(Scenes.Towne.hut) { clearMapWindow() showBackdrop(Images.Scene.hut) - clearText() playSound(Sounds.Explore.doorOpen) - writeText("You enter the hut.") - pause600ms() + writeText("You enter the hut. {pause 600ms}") loop { clearText() @@ -4976,17 +4886,14 @@ val authoredRylween: RylweenModel = withCurrentCaster { caster -> ask.monsterAlive(literalText("Who?", "")) { target -> localInt(caster.level * random(2..8)) { damage -> - clearText() - writeText(flowText(partyName(caster), " chills the opponent for ", damage, " damage pts.")) - pause2s() + writeText(flowText(partyName(caster), " chills the opponent for ", damage, " damage pts. {pause 2s}")) target.hp -= damage whenever(target.hp lte 0) { target.hp set 0 target.dead set true - writeText("...KILLED!") - pause600ms() + writeText("...KILLED! {pause 600ms}") } } } @@ -5001,12 +4908,10 @@ val authoredRylween: RylweenModel = spell(Spells.Mage.confusion, slot = 3, baseCost = 17, name = "Confusion") { withCurrentCaster { caster -> - clearText() writeText { line(partyName(caster), " utters a word.") } - appendText("Your images waver and blur in front of your enemies") - pause2s() + appendText("Your images waver and blur in front of your enemies {pause 2s}") battle.monsterWeaponSkill /= 2 battle.monsterConfused set true } @@ -5019,18 +4924,16 @@ val authoredRylween: RylweenModel = writeText( """ Through INCREDIBLE resistance, the enemy is still - alive, badly wounded. + alive, badly wounded. {pause 2s} """, ) - pause2s() target.hp set 1 } otherwise { writeText( """ - The enemy is wiped straight off the surface of the earth! + The enemy is wiped straight off the surface of the earth! {pause 2s} """, ) - pause2s() target.dead set true target.hp set 0 } @@ -5039,28 +4942,24 @@ val authoredRylween: RylweenModel = spell(Spells.Mage.hold, slot = 5, baseCost = 43, name = "Hold Enemies") { withCurrentCaster { caster -> - clearText() writeText { line(partyName(caster), " utters a word.") } - appendText("The enemies freeze dead in their tracks.") - pause2s() + appendText("The enemies freeze dead in their tracks. {pause 2s}") battle.monstersHeld set true } } spell(Spells.Mage.antimagic, slot = 6, baseCost = 28, name = "Anti Magic") { withCurrentCaster { caster -> - clearText() writeText { line(partyName(caster), " utters a word.") } appendText( """ - The enemy is now stopped from using magic against you this round. + The enemy is now stopped from using magic against you this round. {pause 3s} """, ) - pause3s() battle.antimagic set true } } @@ -5070,38 +4969,32 @@ val authoredRylween: RylweenModel = localInt((battle.encounterHitPointMax / 5) + random(0..3)) { damage -> writeText { line("Frost Finger on ", partyName(target), "! {pause 1s}") - line("and does ", damage, " pts of damage!") + line("and does ", damage, " pts of damage! {pause 1s}") } - pause1s() target.hp -= damage whenever(target.hp lte 0) { target.hp set 0 target.dead set true appendText { - line("\u001B[31m", partyName(target), " DIES!\u001B[37m") + line("\u001B[31m", partyName(target), " DIES!\u001B[37m {pause 1s}") } - pause1s() } } } } spell(Spells.Monster.fire, slot = 2, baseCost = 0, name = "Cloud of Fire") { - writeText("Cloud of Fire!") - pause1s() + writeText("Cloud of Fire! {pause 1s}") forEachMember { target -> localInt((battle.encounterHitPointMax / 5) + random(0..4)) { damage -> - clearText() - writeText(flowText(partyName(target), " is burnt for ", damage, " damage pts!")) - pause1s() + writeText(flowText(partyName(target), " is burnt for ", damage, " damage pts! {pause 1s}")) target.hp -= damage whenever(target.hp lte 0) { target.hp set 0 target.dead set true writeText { - line("\u001B[31m", partyName(target), " DIES!\u001B[37m") + line("\u001B[31m", partyName(target), " DIES!\u001B[37m {pause 1s}") } - pause1s() } } } @@ -5112,10 +5005,9 @@ val authoredRylween: RylweenModel = """ Hold Creature! {pause 600ms} - You realize with horror that you cannot move! + You realize with horror that you cannot move! {pause} """, ) - pause1500ms() battle.partyHeld set true } @@ -5124,10 +5016,9 @@ val authoredRylween: RylweenModel = """ Confusion! {pause 600ms} - You are almost blinded by a colorful haze. + You are almost blinded by a colorful haze. {pause} """, ) - pause1500ms() battle.partyConfused set true } @@ -5147,22 +5038,26 @@ val authoredRylween: RylweenModel = ) { target -> localInt(random(10..19) + (caster.level * 2)) { healing -> whenever(target.dead) { - clearText() - writeText("Dead.") - pause600ms() + writeText("Dead. {pause 600ms}") clearText() } otherwise { target.hp.addClamped(healing, target.maxHp) - clearText() - writeText(flowText(partyName(caster), " heals ", partyName(target), " for ", healing, " hit points...")) - pause1500ms() + writeText( + flowText( + partyName(caster), + " heals ", + partyName(target), + " for ", + healing, + " hit points... {pause}", + ), + ) clearText() } } } } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } @@ -5180,14 +5075,11 @@ val authoredRylween: RylweenModel = filter = MemberChoiceFilter.Any, ) { target -> target.fullHeal() - clearText() - writeText(flowText(partyName(caster), " heals ", partyName(target), " fully...")) - pause1500ms() + writeText(flowText(partyName(caster), " heals ", partyName(target), " fully... {pause}")) clearText() } } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } @@ -5208,7 +5100,6 @@ val authoredRylween: RylweenModel = target.dead set false party.memberCount += 1 target.hp set 1 - clearText() writeText( flowText( partyName(target), @@ -5216,19 +5107,16 @@ val authoredRylween: RylweenModel = pronoun(target, PronounCase.Subject), " opens ", pronoun(target, PronounCase.Possessive), - " eyes!", + " eyes! {pause 2s}", ), ) - pause2s() clearText() } otherwise { - writeText(flowText(partyName(target), " is alive and healthy.")) - pause1500ms() + writeText(flowText(partyName(target), " is alive and healthy. {pause}")) } } } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } @@ -5240,7 +5128,6 @@ val authoredRylween: RylweenModel = whenever(caster.mp gte cost) { whenever(context.inDungeon) { caster.mp -= cost - clearText() writeText( flowText( partyName(caster), @@ -5252,11 +5139,10 @@ val authoredRylween: RylweenModel = pronoun(caster, PronounCase.Possessive), " palms, and suddenly clasps them together over ", pronoun(caster, PronounCase.Possessive), - " head.", + " head. {pause 2s}", ), ) - pause2s() - writeText( + showTextAndWait( flowText( """ There is a deafening clap of thunder, and you hear @@ -5264,11 +5150,9 @@ val authoredRylween: RylweenModel = """, ), ) - waitInput("after banish evil") - clearText() realm.banished set true } otherwise { - writeText( + showTextAndWait( flowText( """ There is no particular target for this banishing. @@ -5276,12 +5160,9 @@ val authoredRylween: RylweenModel = """, ), ) - waitInput("after banish no target") - clearText() } } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } @@ -5294,14 +5175,9 @@ val authoredRylween: RylweenModel = whenever(context.inDungeon) { caster.mp -= cost whenever(chance(59)) { - clearText() - writeText("There is nothing special near.") - waitInput("after revelation nothing near") - clearText() + showTextAndWait("There is nothing special near.") } otherwise { - clearText() - writeText("Something special is near!") - pause1500ms() + writeText("Something special is near! {pause}") clearText() choose(random(0..2)) { case(0) { dungeonItemFind(ItemPools.dungeonWeaponFinds) } @@ -5310,7 +5186,7 @@ val authoredRylween: RylweenModel = } } } otherwise { - writeText( + showTextAndWait( flowText( """ This spell can be used in dungeons only, where there @@ -5318,12 +5194,9 @@ val authoredRylween: RylweenModel = """, ), ) - waitInput("after revelation dungeon-only") - clearText() } } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } @@ -5333,7 +5206,6 @@ val authoredRylween: RylweenModel = withCurrentCasterCost(35) { caster, cost -> whenever(caster.mp gte cost) { caster.mp -= cost - clearText() writeText( flowText( partyName(caster), @@ -5344,8 +5216,7 @@ val authoredRylween: RylweenModel = ) realm.hour += 1 waitInput("after teleport ritual") - clearText() - writeText( + showTextAndWait( flowText( pronoun(caster, PronounCase.Subject), " picks up a stone slab from ", @@ -5355,8 +5226,6 @@ val authoredRylween: RylweenModel = " wants you to teleport to.", ), ) - waitInput("after teleport slab") - clearText() ask.wildernessDirection( literalText( "Teleport :", @@ -5371,15 +5240,13 @@ val authoredRylween: RylweenModel = clearText() ask.digit(flowText("How many miles do you want to travel? (1-9)"), 1..9) { distance -> teleportParty(direction, distance) - writeText("You appear to be somewhere else.") renderMap() - pause1500ms() + writeText("You appear to be somewhere else. {pause}") clearText() } } } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } @@ -5389,19 +5256,16 @@ val authoredRylween: RylweenModel = withCurrentCasterCost(55) { caster, cost -> clearText() whenever(context.inDungeon or context.inCastle) { - writeText("The roof would cave in on you!") - waitInput("after earthquake dungeon warning") - clearText() + showTextAndWait("The roof would cave in on you!") } otherwise { whenever(caster.mp gte cost) { caster.mp -= cost writeText( flowText( partyName(caster), - " utters three syllables in an archaic tongue... {pause 2s} and the ground cracks open!", + " utters three syllables in an archaic tongue... {pause 2s} and the ground cracks open! {pause 3s}", ), ) - pause3s() clearMapWindow() showBackdrop(Images.Backdrop.cave) clearText() @@ -5411,7 +5275,6 @@ val authoredRylween: RylweenModel = whenever(party.timeLeft gt 10) { discoverCave(random(5..18), Dungeons.randomCave, lit(10)) } otherwise { - clearText() writeText( flowText( """ @@ -5432,8 +5295,7 @@ val authoredRylween: RylweenModel = }, ) } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } @@ -5454,9 +5316,8 @@ val authoredRylween: RylweenModel = consumeActiveItem() localInt(potionPoints(target)) { points -> target.hp.addClamped(points, target.maxHp) - writeText(flowText(partyName(target), " recovers ", points, " hit points.")) + writeText(flowText(partyName(target), " recovers ", points, " hit points. {pause 1s}")) } - pause1s() } } } @@ -5475,14 +5336,13 @@ val authoredRylween: RylweenModel = consumeActiveItem() localInt(potionPoints(target)) { points -> target.hp -= points - writeText(flowText(partyName(target), " is poisoned for ", points, " hit points.")) + writeText(flowText(partyName(target), " is poisoned for ", points, " hit points. {pause 1s}")) } whenever(target.hp lte 0) { target.hp set 0 target.dead set true party.memberCount -= 1 } - pause1s() } } } @@ -5502,9 +5362,8 @@ val authoredRylween: RylweenModel = consumeActiveItem() localInt(potionPoints(target)) { points -> target.mp.addClamped(points, target.maxMp) - writeText(flowText(partyName(target), " recovers ", points, " spell points.")) + writeText(flowText(partyName(target), " recovers ", points, " spell points. {pause 1s}")) } - pause1s() } } } @@ -5517,16 +5376,22 @@ val authoredRylween: RylweenModel = withCurrentCaster { caster -> battle.firstAliveMonster { target -> localInt(random(5..11) + caster.level) { damage -> - clearText() - writeText(flowText(partyName(caster), " chills ", monsterName(target), " for ", damage, " damage pts.")) - pause1s() + writeText( + flowText( + partyName(caster), + " chills ", + monsterName(target), + " for ", + damage, + " damage pts. {pause 1s}", + ), + ) target.hp -= damage whenever(target.hp lte 0) { target.hp set 0 - writeText("...KILLED!") - pause600ms() + writeText("...KILLED! {pause 600ms}") target.dead set true } } @@ -5553,16 +5418,13 @@ val authoredRylween: RylweenModel = effect { withCurrentCaster { caster -> - clearText() - writeText( + showTextAndWait( flowText( partyName(caster), " throws the gem at the enemy. It breaks before them in a rain of sparks.", " They bump into each other as they try to see you.", ), ) - waitInput("after gem of confusion") - clearText() battle.monsterWeaponSkill /= 2 } } @@ -5574,16 +5436,13 @@ val authoredRylween: RylweenModel = effect { withCurrentCaster { caster -> - clearText() - writeText( + showTextAndWait( flowText( partyName(caster), " throws the gem at the enemy. It breaks, releasing a brilliant cloud of light which completely surrounds them.", " As the light fades, your enemies are blind.", ), ) - waitInput("after gem of blindness") - clearText() battle.monsterWeaponSkill set 5 } } @@ -5596,11 +5455,8 @@ val authoredRylween: RylweenModel = effect { withCurrentCaster { caster -> battle.firstAliveMonster { target -> - clearText() - writeText(flowText(partyName(caster), " summons death to take a ", monsterName(target), " away...")) - pause2s() - writeText("...KILLED!") - pause600ms() + writeText(flowText(partyName(caster), " summons death to take a ", monsterName(target), " away... {pause 2s}")) + writeText("...KILLED! {pause 600ms}") target.dead set true target.hp set 0 clearText() @@ -5624,8 +5480,7 @@ val authoredRylween: RylweenModel = whenever(!target.dead) { target.fullHeal() } - writeText(flowText(partyName(target), " is fully healed.")) - pause1s() + writeText(flowText(partyName(target), " is fully healed. {pause 1s}")) clearText() } } @@ -5636,15 +5491,12 @@ val authoredRylween: RylweenModel = consume = ItemConsumePolicy.BeforeUse effect { - clearText() - writeText( + showTextAndWait( """ The party feels their spirits grow. You are all stronger than before. """, ) - waitInput("after blessing scroll") - clearText() forEachMember(includeDead = true) { member -> member.weaponSkill += 3 @@ -5660,10 +5512,7 @@ val authoredRylween: RylweenModel = consume = ItemConsumePolicy.BeforeUse effect { - clearText() - writeText("The party is fully healed!") - waitInput("after staff of curing") - clearText() + showTextAndWait("The party is fully healed!") forEachMember(includeDead = true) { member -> whenever(!member.dead) { @@ -5688,17 +5537,15 @@ val authoredRylween: RylweenModel = clearText() whenever(target.dead) { writeText { - line(partyName(target), " opens ", pronoun(target, PronounCase.Possessive), " eyes!") + line(partyName(target), " opens ", pronoun(target, PronounCase.Possessive), " eyes! {pause 1s}") } - pause1s() target.dead set false target.hp set 1 consumeActiveItem() } otherwise { writeText { - line(partyName(target), " is not dead.") + line(partyName(target), " is not dead. {pause 1s}") } - pause1s() battle.actionRetry set true } } @@ -5711,24 +5558,19 @@ val authoredRylween: RylweenModel = effect { withCurrentCaster { caster -> - clearText() - writeText(flowText(partyName(caster), " throws Kael's axe at the enemy!")) - pause1500ms() + writeText(flowText(partyName(caster), " throws Kael's axe at the enemy! {pause}")) writeText( """ It wounds them severely as it spins around, wielded by - hands you cannot see! + hands you cannot see! {pause 4s} """, ) - pause4s() - clearText() writeText( """ With a raging battle cry, you attack the mortally - wounded foes! + wounded foes! {pause 3s} """, ) - pause3s() forEachMonster { foe -> foe.hp set random(1..3) @@ -5743,11 +5585,10 @@ val authoredRylween: RylweenModel = effect { withCurrentCaster { caster -> - clearText() - writeText(flowText(partyName(caster), " pulls the holy pin, and lobbeth the holy hand grenade at the foes...")) - pause3s() - writeText("KA-BLAM!") - pause1500ms() + writeText( + flowText(partyName(caster), " pulls the holy pin, and lobbeth the holy hand grenade at the foes... {pause 3s}"), + ) + writeText("KA-BLAM! {pause}") clearText() forEachMonster { foe -> @@ -5764,15 +5605,12 @@ val authoredRylween: RylweenModel = effect { withCurrentCaster { caster -> - clearText() - writeText( + showTextAndWait( flowText( partyName(caster), " plays the Flute of Madness. It produces a shrill, fragile sound, and breaks. Nothing happens.", ), ) - waitInput("after flute of madness") - clearText() } } } @@ -5804,7 +5642,6 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.bandits) { - clearText() showTextAndWait( """ You come across the camp of the bandits. One of them spots you @@ -5813,7 +5650,6 @@ val authoredRylween: RylweenModel = ) encounter(Monsters.bandit, mandatory = true) renderMap() - clearText() showTextAndWait(flowText("You find the cargo the ", character(Roles.banditsQuestGiver).job, " wanted you to bring him.")) mark(Story.garth.bandits.recovered) } @@ -5821,16 +5657,13 @@ val authoredRylween: RylweenModel = scene(Scenes.Missions.trollTooth) { encounter(Monsters.troll, mandatory = true) renderMap() - clearText() - writeText( + showTextAndWait( flowText( "You break off a troll tooth to give the ", character(Roles.hermitTrollTooth).job, ". After wiping the slime off it, you put it in your backpack.", ), ) - waitInput("after troll tooth") - clearText() mark(Story.hermit.trollTooth.extracted) } @@ -5845,7 +5678,6 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.thunTemple) { - clearText() showTextAndWait( """ You stand before the ancient temple of Thun. Around you are @@ -5868,11 +5700,9 @@ val authoredRylween: RylweenModel = ) { defaultOption('Y') { whenever(party.inventory.count(ItemPools.thunAltarGems) lt 5) { - clearText() showTextAndWait("You don't have five different gems.") } otherwise { party.inventory.consume(ItemPools.thunAltarGems, 5) - clearText() showTextAndWait( """ With a resounding 'CRUNG' the altar slides away to @@ -5904,18 +5734,14 @@ val authoredRylween: RylweenModel = }, ) { option('A') { - clearText() - writeText( + showTextAndWait( """ You run screaming into a large celebration of some sort. There are about forty kobolds here. At first, they are very surprised, and you manage to slay many, before they attack... """, ) - waitInput() - clearText() encounter(Monsters.koboldHorde, mandatory = true) - clearText() writeText( """ Piles of dead kobolds are lying all around. Still, they @@ -5924,7 +5750,6 @@ val authoredRylween: RylweenModel = ) waitInput() encounter(Monsters.koboldHorde, mandatory = true) - clearText() writeText( """ You have annihilated most of the village. You pause to wipe @@ -5935,7 +5760,6 @@ val authoredRylween: RylweenModel = waitInput() encounter(Monsters.orc, mandatory = true) renderMap() - clearText() showTextAndWait( """ The entire village is wiped out. You snatch an ugly pendant @@ -5949,21 +5773,17 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.skullweed) { - clearText() showBackdrop(Images.Mission.skullweedSwamp) - writeText( + showTextAndWait( """ On the ground before you grows the skullweed plant. You break off a few plants and put them in your backpack. """, ) - waitInput("after skullweed pickup") - clearText() mark(Story.masterCrown.task2Done) } scene(Scenes.Missions.borinMeet) { - clearText() showTextAndWait( """ You arrive at a village which looks typically dwarfish. As you @@ -6042,7 +5862,6 @@ val authoredRylween: RylweenModel = line("(L)eave") }, enter = { - clearText() writeText( """ You enter the cave. Piles of treasure are thrown all around. @@ -6053,7 +5872,6 @@ val authoredRylween: RylweenModel = waitInput() encounter(Monsters.ogre, mandatory = true) renderMap() - clearText() writeText( """ You defeat the ogres and start searching for the fabled @@ -6065,7 +5883,6 @@ val authoredRylween: RylweenModel = waitInput() encounter(Monsters.ogreLord, mandatory = true) renderMap() - clearText() showTextAndWait( """ You defeat the Ogre Lord. You take all the gold you find, @@ -6110,8 +5927,7 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.jazzyFoot) { - clearText() - writeText( + showTextAndWait( """ Something about this whole area is weird. The air seems to be loaded with electricity. Suddenly you spot an object on the ground. @@ -6119,8 +5935,6 @@ val authoredRylween: RylweenModel = THIS IS THE FOOT OF JAZZY! """, ) - waitInput("after finding the foot") - clearText() writeText( """ Just as you touch it, the sky splits open and amid the wailing @@ -6131,16 +5945,13 @@ val authoredRylween: RylweenModel = waitInput("before Jazzy minions") encounter(Monsters.wingedThing, mandatory = true) renderMap() - clearText() - writeText( + showTextAndWait( """ Quiet settles again, as you destroy the foul creatures, one by one. You reach for the foot again, when suddenly, something EVEN MORE horrible happens... """, ) - waitInput("after Jazzy minions") - clearText() writeText( """ A twenty-foot-tall being materializes in front of you! You will @@ -6150,16 +5961,13 @@ val authoredRylween: RylweenModel = waitInput("before Jazzy") encounter(Monsters.jazzy, mandatory = true) renderMap() - clearText() - writeText( + showTextAndWait( """ Today, you have killed a god. You watch silently as the huge body starts to melt. It fades away into Nothingness. This time, when you pick up the foot, nothing happens. """, ) - waitInput("after Jazzy defeat") - clearText() mark(Story.jazzy.ogre.jazzyDefeated) achieve(Milestones.footOfJazzy) } @@ -6175,7 +5983,6 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.hobgoblinCaravan) { - clearText() showTextAndWait( "Just before you is a caravan of hobgoblins on white, well-bred horses.", ) @@ -6188,7 +5995,6 @@ val authoredRylween: RylweenModel = ) encounter(Monsters.ridingHobgoblin, mandatory = true) renderMap() - clearText() showTextAndWait( flowText { paragraph("Before you kill the last hobgoblin you ask him about the key. The foul creature blurts:") @@ -6224,7 +6030,6 @@ val authoredRylween: RylweenModel = // Script rewards use semantic item ids and placement policy, not // numeric inventory ids or runtime-specific reward shortcuts. scene(Scenes.Missions.borinGift) { - clearText() showTextAndWait( """ Borin greets you. He can hardly believe his eyes when you show @@ -6250,45 +6055,37 @@ val authoredRylween: RylweenModel = dialogue { npc(Npcs.garth) { whenState(Story.garth.bandits.none) { - writeText( + showTextAndWait( """ In fact, I have a mission for you. It will bring you much gold! """, ) - waitInput("after Garth mission offer") - clearText() - writeText( + showTextAndWait( """ I was robbed by bandits just to the east of here. If you find these bandits, kill them, and return my cargo here, I'll pay you 2,000 gold and a ruby my grandfather gave me. """, ) - waitInput("after Garth bandits story") - clearText() mark(Story.garth.bandits.accepted) } whenState(Story.garth.bandits.accepted) { - writeText( + showTextAndWait( """ Find those bandits and bring my cargo back here. Then I'll pay you. """, ) - waitInput("after Garth accepted reminder") - clearText() } whenState(Story.garth.bandits.recovered) { - writeText( + showTextAndWait( flowText( "The ", character(Roles.banditsQuestGiver).job, " is GRATEFUL! He pays you 2,000 gold and hands you a red gem.", ), ) - waitInput("after Garth reward intro") - clearText() reward { gold(2_000) items(Items.redGem) @@ -6428,8 +6225,7 @@ val authoredRylween: RylweenModel = npc(Npcs.bernak) { whenState(Story.silverKey.none) { - writeText("- There is an item of great power, he hisses.") - pause2s() + writeText("- There is an item of great power, he hisses. {pause 2s}") showTextAndWait( """ - It is called the SILVER KEY. It has taken me many years @@ -6524,8 +6320,7 @@ val authoredRylween: RylweenModel = } whenState(Story.erethor.lute.luteTaken) { - writeText("You hand him the golden lute...") - pause1500ms() + writeText("You hand him the golden lute... {pause}") showTextAndWait( """ - I can't believe you actually made it!!! @@ -6781,11 +6576,8 @@ val authoredRylween: RylweenModel = ) ask.inventorySlot(literalText("Offer what?"), filter = InventorySlotChoiceFilter.NonEmpty) { slot -> whenever(party.inventory.itemCost(slot) lt 35) { - clearText() - writeText("- NAH, THINK NOT!") - pause1s() + writeText("- NAH, THINK NOT! {pause 1s}") } otherwise { - clearText() writeText( flowText( "- YEEES! NICE NIICE! GO TO CAVE AT ", @@ -6905,10 +6697,9 @@ val authoredRylween: RylweenModel = writeText( """ You ask him if he still has the Key, prepared for the - worst... + worst... {pause 2s} """, ) - pause2s() showTextAndWait( """ - Nah, sorry. I kinda studied it enough and was gonna bring @@ -6989,16 +6780,13 @@ private fun ScriptScope.burnEveryLivingMonster( forEachMonster(includeDead = true) { foe -> localInt(caster.level * random(damageRoll)) { damage -> whenever(!foe.dead) { - clearText() - writeText(flowText(partyName(caster), " burns ", monsterName(foe), " for ", damage, " pts!")) - pause1s() + writeText(flowText(partyName(caster), " burns ", monsterName(foe), " for ", damage, " pts! {pause 1s}")) foe.hp -= damage whenever(foe.hp lte 0) { foe.hp set 0 - writeText("...KILLED!") - pause600ms() + writeText("...KILLED! {pause 600ms}") foe.dead set true } } diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt index d9afe576..49d353ab 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt @@ -1207,9 +1207,9 @@ internal class BattleRunner( } CompiledOpcode.View -> false.also { - screen.writeViewCommand( - instruction.viewOperand(0).toRuntimeViewCommand(), - ) + val command = instruction.viewOperand(0).toRuntimeViewCommand() + if (command == RuntimeViewCommand.ClearText) currentTextLines = emptyList() + screen.writeViewCommand(command) } CompiledOpcode.LetInt -> diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt index 59fcec84..888da091 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt @@ -97,6 +97,31 @@ class ScriptExecutorTest { @Test fun aPauseMarkerShowsThePageUpToItThenTheRest() { + val events = pagesAndPauses(scriptRoot(ScriptRootKind.DialogueBranch, "dialogue.tybalt.erethor.lute.none"), "AAAA") + + val beat = events.indexOf("pause 1500") + assertTrue(beat > 0, "the rumor pauses at its {pause} marker: $events") + assertTrue("Erethor is a mighty" !in events[beat - 1], "the page before the beat stops at the marker: ${events[beat - 1]}") + assertTrue( + events[beat + 1].startsWith(events[beat - 1]) && "- Erethor is a mighty" in events[beat + 1], + "after the beat the same page shows the rest below it: ${events[beat + 1]}", + ) + } + + @Test + fun aPauseMarkerAtTheEndHoldsThePageOnce() { + val events = pagesAndPauses(scriptRoot(ScriptRootKind.Scene, "towne.hut"), "L") + + val shown = events.indexOf("You enter the hut.") + assertEquals("pause 600", events.getOrNull(shown + 1), "the trailing marker holds the page: $events") + assertEquals(1, events.count { event -> event == "You enter the hut." }, "the held page is not shown again: $events") + } + + // Every page the script writes, joined into one string, and every pause, in order. + private fun pagesAndPauses( + program: CompiledScriptProgram, + commands: String, + ): List { val events = mutableListOf() val screen = object : NoOpRuntimeScreen(textColumns = CLASSIC_TEXT_WINDOW_COLUMNS) { @@ -104,25 +129,17 @@ class ScriptExecutorTest { events += lines.joinToString(" / ") } } - val scripted = ScriptedInput("AAAA") + val scripted = ScriptedInput(commands) val input = object : RuntimeInputPort by scripted { override fun pause(ms: Int) { events += "pause $ms" } } - val program = scriptRoot(ScriptRootKind.DialogueBranch, "dialogue.tybalt.erethor.lute.none") - RuntimeLog.open(testTmp.resolve("tybalt-beat.log")).use { log -> + RuntimeLog.open(testTmp.resolve("${program.root.slug}-beats.log")).use { log -> ScriptExecutor(bundle.content, systems, input, screen, thordRuntime(), log = log).execute(program) } - - val beat = events.indexOf("pause 1500") - assertTrue(beat > 0, "the rumor pauses at its {pause} marker: $events") - assertTrue("Erethor is a mighty" !in events[beat - 1], "the page before the beat stops at the marker: ${events[beat - 1]}") - assertTrue( - events[beat + 1].startsWith(events[beat - 1]) && "- Erethor is a mighty" in events[beat + 1], - "after the beat the same page shows the rest below it: ${events[beat + 1]}", - ) + return events } private fun pausePromptIn(lines: List): Boolean = lines.lastOrNull()?.startsWith("(") == true From 47fced5a34450da80e982c5fba0aeb18588cea9a Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:16 +0100 Subject: [PATCH 02/16] Color text lines with {red} markers instead of escape codes 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. --- .../kotlin/rylween/compiled/CompiledBundle.kt | 1 + .../compiled/ExternalBundleArtifact.kt | 1 + .../main/kotlin/rylween/dsl/DslValidation.kt | 23 +++++++- .../rylween/dsl/ScriptSourceAnalysis.kt | 1 + core/src/main/kotlin/rylween/dsl/TextDsl.kt | 56 +++++++++++++++---- docs/dsl-authoring.md | 6 ++ .../main/kotlin/rylween/game/RylweenGame.kt | 4 +- .../src/test/kotlin/rylween/TextMarkerTest.kt | 50 +++++++++++++++++ .../kotlin/rylween/bitmapweb/BitmapFrame.kt | 13 ++++- .../src/main/resources/bitmap-web/client.ts | 33 ++++++++--- .../rylween/bitmapweb/BitmapFrameTest.kt | 32 +++++++++++ .../kotlin/rylween/runtime/RuntimeScreen.kt | 3 +- .../rylween/runtime/RylweenRuntimeMain.kt | 11 ++++ .../rylween/runtime/RuntimeScreenTest.kt | 11 ++++ 14 files changed, 223 insertions(+), 22 deletions(-) create mode 100644 game/src/test/kotlin/rylween/TextMarkerTest.kt create mode 100644 runtimes/runtime-bitmap-web/src/test/kotlin/rylween/bitmapweb/BitmapFrameTest.kt diff --git a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt index 1cc8ddf6..25c50a16 100644 --- a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt +++ b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt @@ -2177,6 +2177,7 @@ private class CompiledBundleCompiler( is TextPart.IntValue -> CompiledTextPart.IntValue(intExpr(part.value)) is TextPart.StringValue -> CompiledTextPart.StringValue(stringExpr(part.value)) is TextPart.Pause -> error("{pause} markers only work in writeText and showTextAndWait") + is TextPart.LineColor -> CompiledTextPart.Literal(strings.id(part.color.escape)) is TextPart.RoleName -> CompiledTextPart.RoleName(roleRef(part.role)) is TextPart.RoleJob -> CompiledTextPart.RoleJob(roleRef(part.role)) is TextPart.RoleLocation -> CompiledTextPart.RoleLocation(roleRef(part.role)) diff --git a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index 3c246c34..5ccca327 100644 --- a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt +++ b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt @@ -2548,6 +2548,7 @@ private class ExternalBundleArtifactWriter { is TextPart.IntValue -> jsonObject("kind" to JsonString("intExpr"), "expr" to intAstJson(part.value)) is TextPart.StringValue -> jsonObject("kind" to JsonString("stringExpr"), "expr" to strAstJson(part.value)) is TextPart.Pause -> error("{pause} markers only work in writeText and showTextAndWait") + is TextPart.LineColor -> jsonObject("kind" to JsonString("literal"), "text" to JsonString(part.color.escape)) is TextPart.RoleName -> jsonObject("kind" to JsonString("roleName"), "role" to JsonString(part.role.slug)) is TextPart.RoleJob -> jsonObject("kind" to JsonString("roleJob"), "role" to JsonString(part.role.slug)) is TextPart.RoleLocation -> diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 1346d82d..6b33ef16 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -1214,6 +1214,18 @@ private fun validateRandomNpcWildernessRect( } } +private const val TERMINAL_ESCAPE = '\u001B' + +// A color marker colors its whole line, so it can only start one. +private fun checkLineColorStartsLine( + line: TextLine, + label: String, +) { + check(line.parts.drop(1).none { part -> part is TextPart.LineColor }) { + "$label has a color marker after its start; {red} and the other colors go at the start of a line or paragraph" + } +} + private fun validateTextBlock( block: TextBlock, label: String, @@ -1224,10 +1236,14 @@ private fun validateTextBlock( ) { fun validatePart(part: TextPart) { when (part) { - is TextPart.Literal -> Unit + is TextPart.Literal -> + check( + TERMINAL_ESCAPE !in part.text, + ) { "$label has a terminal escape code; color a line with {red} or another color at its start" } is TextPart.IntValue -> Unit is TextPart.StringValue -> Unit is TextPart.Pause -> error("$label has a {pause} marker, but only writeText and showTextAndWait show text in beats") + is TextPart.LineColor -> Unit is TextPart.RoleName -> { check(part.role.slug.isNotBlank()) { "$label references blank character role" } check(knownRoles == null || part.role in knownRoles) { @@ -1330,6 +1346,9 @@ private fun validateTextBlock( is TextBlock.Inline -> { check(block.lines.isNotEmpty()) { "$label inline text has no lines" } check(block.lines.any { it.isNotBlank() }) { "$label inline text is blank" } + check(block.lines.none { line -> TERMINAL_ESCAPE in line }) { + "$label has a terminal escape code; color a line with {red} or another color at its start" + } } is TextBlock.Structured -> { check(block.lines.isNotEmpty()) { "$label structured text has no lines" } @@ -1342,6 +1361,7 @@ private fun validateTextBlock( } block.lines.forEachIndexed { index, line -> check(line.parts.isNotEmpty()) { "$label line $index has no parts" } + checkLineColorStartsLine(line, "$label line $index") line.parts.forEach(::validatePart) } } @@ -1356,6 +1376,7 @@ private fun validateTextBlock( } block.paragraphs.forEachIndexed { index, line -> check(line.parts.isNotEmpty()) { "$label paragraph $index has no parts" } + checkLineColorStartsLine(line, "$label paragraph $index") line.parts.forEach(::validatePart) } } diff --git a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt index 98f5bc3d..660949e8 100644 --- a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt +++ b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt @@ -455,6 +455,7 @@ private class NativePathCollector { is TextPart.StringValue -> collect(part.value) is TextPart.Pause -> Unit is TextPart.Literal, + is TextPart.LineColor, is TextPart.RoleName, is TextPart.RoleJob, is TextPart.RoleLocation, diff --git a/core/src/main/kotlin/rylween/dsl/TextDsl.kt b/core/src/main/kotlin/rylween/dsl/TextDsl.kt index 844a9609..cda6a889 100644 --- a/core/src/main/kotlin/rylween/dsl/TextDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/TextDsl.kt @@ -39,6 +39,14 @@ sealed interface TextPart { val millis: Int, ) : TextPart + /** + * The color of a whole line or paragraph, written `{red}` (or another + * [TextColor]) at its start. It can only start a line. + */ + data class LineColor( + val color: TextColor, + ) : TextPart + data class RoleName( val role: NpcRole, ) : TextPart @@ -160,6 +168,7 @@ fun TextPart.fallbackText(): String = is TextPart.IntValue -> "{int}" is TextPart.StringValue -> "{string}" is TextPart.Pause -> "" + is TextPart.LineColor -> "" is TextPart.RoleName -> "{${role.slug}.name}" is TextPart.RoleJob -> "{${role.slug}.job}" is TextPart.RoleLocation -> "{${role.slug}.location}" @@ -241,7 +250,7 @@ sealed interface TextBlock { */ fun literalText(vararg lines: String): TextBlock { val rows = expandMultiline(lines) - return if (rows.none(pauseMarker::containsMatchIn)) { + return if (rows.none(textMarker::containsMatchIn)) { TextBlock.Inline(rows) } else { TextBlock.Structured(rows.map { row -> TextLine(literalParts(row)) }) @@ -326,22 +335,49 @@ private fun textParts(part: Any): List = } private const val DEFAULT_PAUSE_MILLIS = 1_500 -private val pauseMarker = Regex("""\{pause(?:\s+(\d+(?:\.\d+)?)\s*(ms|s))?\}""") +private val textMarker = + Regex("""\{(?:pause(?:\s+(\d+(?:\.\d+)?)\s*(ms|s))?|(${TextColor.entries.joinToString("|") { color -> color.marker }}))\}""") -/** Splits literal text at its `{pause}` markers; text without one stays a single literal. */ +/** Splits literal text at its `{pause}` and color markers; text without one stays a single literal. */ private fun literalParts(text: String): List { - val pauses = pauseMarker.findAll(text).map { marker -> TextPart.Pause(marker.pauseMillis()) }.toList() - if (pauses.isEmpty()) return listOf(TextPart.Literal(text)) - return text.split(pauseMarker).flatMapIndexed { index, piece -> - listOfNotNull(piece.takeIf(String::isNotEmpty)?.let { literal -> TextPart.Literal(literal) }, pauses.getOrNull(index)) + val markers = textMarker.findAll(text).map { marker -> marker.textPart() }.toList() + if (markers.isEmpty()) return listOf(TextPart.Literal(text)) + return text.split(textMarker).flatMapIndexed { index, piece -> + listOfNotNull(piece.takeIf(String::isNotEmpty)?.let { literal -> TextPart.Literal(literal) }, markers.getOrNull(index)) } } -private fun MatchResult.pauseMillis(): Int { - val amount = groupValues[1].takeIf(String::isNotEmpty)?.toDouble() ?: return DEFAULT_PAUSE_MILLIS - return if (groupValues[2] == "s") (amount * 1_000).toInt() else amount.toInt() +private fun MatchResult.textPart(): TextPart { + val color = groupValues[3].takeIf(String::isNotEmpty) + if (color != null) return TextPart.LineColor(TextColor.entries.single { entry -> entry.marker == color }) + val amount = groupValues[1].takeIf(String::isNotEmpty)?.toDouble() ?: return TextPart.Pause(DEFAULT_PAUSE_MILLIS) + return TextPart.Pause(if (groupValues[2] == "s") (amount * 1_000).toInt() else amount.toInt()) } +/** + * A color for a whole line of text-window text, written `{red}`, `{green}` and + * so on at the start of the line. Compiled text starts the line with the + * color's ANSI [escape]; every renderer reads it back with [lineColor], so the + * terminal shows the line in that color and the browser draws it so. + */ +enum class TextColor( + val marker: String, + val escape: String, +) { + Red("red", "\u001B[31m"), + Green("green", "\u001B[32m"), + Yellow("yellow", "\u001B[33m"), + Blue("blue", "\u001B[34m"), + Magenta("magenta", "\u001B[35m"), + Cyan("cyan", "\u001B[36m"), +} + +/** The color a rendered text-window line starts with, if it has one. */ +fun String.lineColor(): TextColor? = TextColor.entries.firstOrNull { color -> startsWith(color.escape) } + +/** The line without its leading color escape. */ +fun String.withoutLineColor(): String = lineColor()?.let { color -> removePrefix(color.escape) } ?: this + /** One step of text shown with `{pause}` beats: the text so far, then the pause after it, if any. */ internal data class TextBeat( val text: TextBlock, diff --git a/docs/dsl-authoring.md b/docs/dsl-authoring.md index b1fd6695..579732aa 100644 --- a/docs/dsl-authoring.md +++ b/docs/dsl-authoring.md @@ -211,6 +211,12 @@ also the only place `appendText` takes one. Any other text that holds a marker, such as a menu prompt or a journal entry, is rejected. `pause(ms)` is left for a beat between two other things, such as a sound cue and the line after it. +A line or paragraph that starts with `{red}` is shown in red, in the terminal +and in the browser alike; `{green}`, `{yellow}`, `{blue}`, `{magenta}` and +`{cyan}` work the same way. The color covers the whole line, so the marker can +only start one: `line("{red}", partyName(target), " DIES!")`. Text never holds +terminal escape codes itself; the content check rejects them. + Literal lines are rows, not hand-wrapped prose: put each sentence on one line and let the renderer wrap it to the window, and break the line only where a new sentence, speech or option row starts. Historical script aliases such as diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 1f2f8afb..710b0264 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -4976,7 +4976,7 @@ val authoredRylween: RylweenModel = target.hp set 0 target.dead set true appendText { - line("\u001B[31m", partyName(target), " DIES!\u001B[37m {pause 1s}") + line("{red}", partyName(target), " DIES! {pause 1s}") } } } @@ -4993,7 +4993,7 @@ val authoredRylween: RylweenModel = target.hp set 0 target.dead set true writeText { - line("\u001B[31m", partyName(target), " DIES!\u001B[37m {pause 1s}") + line("{red}", partyName(target), " DIES! {pause 1s}") } } } diff --git a/game/src/test/kotlin/rylween/TextMarkerTest.kt b/game/src/test/kotlin/rylween/TextMarkerTest.kt new file mode 100644 index 00000000..c47f1e2c --- /dev/null +++ b/game/src/test/kotlin/rylween/TextMarkerTest.kt @@ -0,0 +1,50 @@ +package rylween + +import rylween.dsl.TextBlock +import rylween.dsl.TextColor +import rylween.dsl.TextLine +import rylween.dsl.TextPart +import rylween.dsl.flowText +import rylween.dsl.literalText +import kotlin.test.Test +import kotlin.test.assertEquals + +/** Markers written inside game text: `{pause}` beats and `{red}`-style line colors. */ +class TextMarkerTest { + @Test + fun aColorMarkerStartsItsLine() { + assertEquals( + TextBlock.Structured(listOf(TextLine(listOf(TextPart.LineColor(TextColor.Red), TextPart.Literal("Walter DIES!"))))), + literalText("{red}Walter DIES!"), + ) + } + + @Test + fun aPauseMarkerSetsItsLength() { + assertEquals( + TextBlock.Flow(listOf(TextLine(listOf(TextPart.Literal("Ahh...! "), TextPart.Pause(1_000))))), + flowText("Ahh...! {pause 1s}"), + ) + assertEquals( + TextPart.Pause(1_500), + (flowText("{pause}") as TextBlock.Flow) + .paragraphs + .single() + .parts + .single(), + ) + assertEquals( + TextPart.Pause(600), + (flowText("{pause 600ms}") as TextBlock.Flow) + .paragraphs + .single() + .parts + .single(), + ) + } + + @Test + fun textWithoutMarkersStaysOneLiteral() { + assertEquals(TextBlock.Inline(listOf("No {marker} here.")), literalText("No {marker} here.")) + } +} diff --git a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapFrame.kt b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapFrame.kt index 746cbc32..d4f2f1ce 100644 --- a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapFrame.kt +++ b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapFrame.kt @@ -5,6 +5,9 @@ package rylween.bitmapweb +import rylween.dsl.lineColor +import rylween.dsl.withoutLineColor + private const val VIRTUAL_WIDTH = 1280 private const val VIRTUAL_HEIGHT = 720 @@ -66,7 +69,8 @@ internal data class BitmapFrame( "subtitle" to subtitle.json(), "status" to (status?.toJson() ?: "null"), "statusLines" to statusLines.jsonArray(), - "textLines" to textLines.jsonArray(), + "textLines" to textLines.map(String::withoutLineColor).jsonArray(), + "textLineColors" to textLineColors().jsonArray(), "textInput" to (textInput?.toJson() ?: "null"), "textEffect" to textEffect.name.json(), "portrait" to (portrait?.toJson() ?: "null"), @@ -82,6 +86,13 @@ internal data class BitmapFrame( ) } +// The color each text line starts with, "" for plain ones; empty when no line has one. +private fun BitmapFrame.textLineColors(): List = + textLines + .map { line -> line.lineColor()?.marker.orEmpty() } + .takeIf { colors -> colors.any(String::isNotEmpty) } + .orEmpty() + internal data class BitmapImageAsset( val id: String, val resource: String, diff --git a/runtimes/runtime-bitmap-web/src/main/resources/bitmap-web/client.ts b/runtimes/runtime-bitmap-web/src/main/resources/bitmap-web/client.ts index a3f6e183..eed9d996 100644 --- a/runtimes/runtime-bitmap-web/src/main/resources/bitmap-web/client.ts +++ b/runtimes/runtime-bitmap-web/src/main/resources/bitmap-web/client.ts @@ -228,6 +228,7 @@ type BitmapFrame = { subtitle?: string; title?: string; textLines?: string[]; + textLineColors?: string[]; textInput?: BitmapTextInput | null; textEffect?: TextEffect; status?: BitmapStatus | null; @@ -3963,7 +3964,7 @@ function drawTextPanel(frame: BitmapFrame): void { const bitmapScale = currentFantasyTextScale(); const fantasy = textDisplaySettings.bitmapFont; ctx.font = textPanelFont; - const rows = textPanelRows(frame.textLines || [], maxWidth, bitmapScale); + const rows = textPanelRows(frame.textLines || [], maxWidth, bitmapScale, frame.textLineColors || []); const lineHeight = fittedLineHeight( fantasy ? currentFantasyLineHeight(bitmapScale) : Math.ceil(24 * textDisplaySettings.bitmapLineSpacing), fantasy ? Math.ceil(fantasyFontHeight * bitmapScale) + 3 : 19, @@ -3986,10 +3987,10 @@ function drawTextPanel(frame: BitmapFrame): void { } else if (row.kind === "columns") { drawTextPanelColumns(row.cells, x, ty, rowTop, lineHeight, columnWidths.get(row.cells.length) || [maxWidth], reveal, bitmapScale); } else if (fantasy) { - drawFantasyRevealText(row.text, x, ty, textPanelLineColor(row.line), textPanelLineDimColor(row.line), reveal, bitmapScale); + drawFantasyRevealText(row.text, x, ty, textPanelRowColor(row), textPanelRowDimColor(row), reveal, bitmapScale); } else { ctx.font = textPanelFont; - drawRevealText(row.text, x, ty, textPanelLineColor(row.line), textPanelLineDimColor(row.line), reveal); + drawRevealText(row.text, x, ty, textPanelRowColor(row), textPanelRowDimColor(row), reveal); } ty += lineHeight; } @@ -4002,16 +4003,16 @@ type CreationStatLine = { label: string; value: string }; // One drawn row of the text panel: a wrapped piece of a prose line, a row of // aligned choice columns (cells separated by a tab), or a creation stat line. type TextPanelRow = - | { kind: "text"; line: string; text: string } + | { kind: "text"; line: string; text: string; color: string } | { kind: "columns"; line: string; cells: string[] } | { kind: "stat"; line: string; stat: CreationStatLine }; const textPanelFont = "17px Georgia, 'Times New Roman', serif"; const textPanelColumnGap = 20; -function textPanelRows(lines: string[], maxWidth: number, scale: number): TextPanelRow[] { +function textPanelRows(lines: string[], maxWidth: number, scale: number, colors: string[]): TextPanelRow[] { const rows: TextPanelRow[] = []; - for (const line of lines) { + for (const [index, line] of lines.entries()) { const stat = creationStatLine(line); if (stat) { rows.push({kind: "stat", line, stat}); @@ -4019,7 +4020,7 @@ function textPanelRows(lines: string[], maxWidth: number, scale: number): TextPa rows.push({kind: "columns", line, cells: line.split("\t")}); } else { const parts = textDisplaySettings.bitmapFont ? wrapFantasyLines(line, maxWidth, scale) : wrapCanvasLines(line, maxWidth); - for (const text of parts) rows.push({kind: "text", line, text}); + for (const text of parts) rows.push({kind: "text", line, text, color: colors[index] || ""}); } } return rows; @@ -4239,6 +4240,24 @@ function drawCreationStatLine( ctx.textAlign = "left"; } +// The colors a line of game text takes from a {red}-style marker at its start: the text, then its reveal tail. +const textLineColors: Record = { + red: ["#e8735c", "rgba(232, 115, 92, 0.25)"], + green: ["#8fcf7a", "rgba(143, 207, 122, 0.25)"], + yellow: ["#ead27a", "rgba(234, 210, 122, 0.25)"], + blue: ["#86aee8", "rgba(134, 174, 232, 0.25)"], + magenta: ["#d792d9", "rgba(215, 146, 217, 0.25)"], + cyan: ["#80d4d6", "rgba(128, 212, 214, 0.25)"] +}; + +function textPanelRowColor(row: TextPanelRow & {kind: "text"}): string { + return textLineColors[row.color]?.[0] ?? textPanelLineColor(row.line); +} + +function textPanelRowDimColor(row: TextPanelRow & {kind: "text"}): string { + return textLineColors[row.color]?.[1] ?? textPanelLineDimColor(row.line); +} + /** Chooses the normal or disabled prose color for text-window rows. */ function textPanelLineColor(line: string): string { return isDeadTargetLine(line) ? "#8f968d" : "#efe4c6"; diff --git a/runtimes/runtime-bitmap-web/src/test/kotlin/rylween/bitmapweb/BitmapFrameTest.kt b/runtimes/runtime-bitmap-web/src/test/kotlin/rylween/bitmapweb/BitmapFrameTest.kt new file mode 100644 index 00000000..69e14dbd --- /dev/null +++ b/runtimes/runtime-bitmap-web/src/test/kotlin/rylween/bitmapweb/BitmapFrameTest.kt @@ -0,0 +1,32 @@ +package rylween.bitmapweb + +import rylween.dsl.TextColor +import kotlin.test.Test +import kotlin.test.assertTrue + +class BitmapFrameTest { + /** The browser draws text itself, so a colored line arrives as plain text with its color named beside it. */ + @Test + fun aColoredLineReachesTheBrowserAsPlainTextWithItsColor() { + val json = frame(listOf("${TextColor.Red.escape}Walter DIES!", "Fine.")).toJson() + + assertTrue(""""textLines":["Walter DIES!", "Fine."]""" in json, json) + assertTrue(""""textLineColors":["red", ""]""" in json, json) + } + + @Test + fun plainTextNamesNoColors() { + assertTrue(""""textLineColors":[]""" in frame(listOf("Fine.")).toJson()) + } + + private fun frame(textLines: List): BitmapFrame = + BitmapFrame( + mode = "script", + backdrop = "", + title = "", + subtitle = "", + statusLines = emptyList(), + textLines = textLines, + commands = emptyList(), + ) +} diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeScreen.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeScreen.kt index 93d6bfb8..289e0566 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeScreen.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeScreen.kt @@ -25,6 +25,7 @@ import rylween.dsl.impl.GridPoint import rylween.dsl.impl.HitPoints import rylween.dsl.impl.PcClass import rylween.dsl.impl.TerrainSettlement +import rylween.dsl.lineColor import rylween.terminal.AnsiCodes import rylween.terminal.AnsiTerminal import kotlin.math.max @@ -213,7 +214,7 @@ internal class RuntimeScreen( logTextOverflow(rows) rows.take(textWindow.height ?: rows.size).forEachIndexed { index, row -> gotoTextRow(index) - terminal.writeRaw(row) + terminal.writeRaw(if (row.lineColor() == null) row else row + AnsiCodes.FG_WHITE) } terminal.flush() } diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt index cd5f252b..38989d32 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt @@ -69,6 +69,8 @@ import rylween.dsl.impl.Race import rylween.dsl.impl.Resource import rylween.dsl.impl.RuntimeMode import rylween.dsl.impl.StatPool +import rylween.dsl.lineColor +import rylween.dsl.withoutLineColor import rylween.terminal.AnsiTerminal import rylween.terminal.AnsiTerminals import java.io.Closeable @@ -2344,6 +2346,15 @@ private fun CompiledContentBundle.journalEntryText(entry: CompiledJournalEntry): internal fun wrapTextLine( line: String, width: Int, +): List { + // A colored line keeps its color on every row it wraps to. + val color = line.lineColor() ?: return wrapPlainTextLine(line, width) + return wrapPlainTextLine(line.withoutLineColor(), width).map { row -> color.escape + row } +} + +private fun wrapPlainTextLine( + line: String, + width: Int, ): List { if (width <= 0 || line.length <= width) return listOf(line) val tokens = line.split(' ').flatMap { word -> if (word.length > width) word.chunked(width) else listOf(word) } diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeScreenTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeScreenTest.kt index 35160145..c199642b 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeScreenTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeScreenTest.kt @@ -1,6 +1,7 @@ package rylween.runtime import rylween.compiled.ExternalScreenRegion +import rylween.dsl.TextColor import rylween.terminal.AnsiCodes import kotlin.test.Test import kotlin.test.assertEquals @@ -57,4 +58,14 @@ class RuntimeScreenTest { assertEquals(listOf("There is nothing to enter", "here."), textWindowRows(listOf("There is nothing to enter here."), width = 26)) assertEquals(listOf("Short line"), textWindowRows(listOf("Short line"), width = 26)) } + + @Test + fun aColoredLineKeepsItsColorOnEveryRowItWrapsTo() { + val red = TextColor.Red.escape + + assertEquals( + listOf("${red}Walter the Brave and", "${red}Mighty DIES!"), + textWindowRows(listOf("${red}Walter the Brave and Mighty DIES!"), width = 20), + ) + } } From ee7343d2f825ae2be956b542557ad11c8a6a2ac9 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:16 +0100 Subject: [PATCH 03/16] Let the runtime count the living; add wound, kill and revive 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. --- .../main/kotlin/rylween/dsl/ExpressionDsl.kt | 40 ++++++++++++- docs/dsl-authoring.md | 11 ++++ .../main/kotlin/rylween/game/RylweenGame.kt | 57 ++++++------------- .../rylween/runtime/ScriptExecutorTest.kt | 20 +++++++ 4 files changed, 85 insertions(+), 43 deletions(-) diff --git a/core/src/main/kotlin/rylween/dsl/ExpressionDsl.kt b/core/src/main/kotlin/rylween/dsl/ExpressionDsl.kt index 63215ec7..0c607de0 100644 --- a/core/src/main/kotlin/rylween/dsl/ExpressionDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/ExpressionDsl.kt @@ -185,7 +185,9 @@ class PartyRef( val food: IntSlot = IntSlot(script, LValueAst.PartyScalar("food"), IntAst.PartyScalar("food")) val timeLeft: IntSlot = IntSlot(script, LValueAst.PartyScalar("time_left"), IntAst.PartyScalar("time_left")) val restedHours: IntSlot = IntSlot(script, LValueAst.PartyScalar("rested_hours"), IntAst.PartyScalar("rested_hours")) - val memberCount: IntSlot = IntSlot(script, LValueAst.PartyScalar("member_count"), IntAst.PartyScalar("member_count")) + + /** The number of living members. The runtime counts them again whenever a member dies or comes back, so scripts only read it. */ + val memberCount: IntExpr = Expr(IntAst.PartyScalar("member_count")) val inventory: PartyInventoryRef = PartyInventoryRef(script) val leader: MemberRef get() = member(lit(1)) @@ -296,12 +298,32 @@ class MemberRef( script.record(ScriptStatementNode.Set(LValueAst.MemberField(index.ast, "hit_points"), maxHp.ast)) } + /** Takes [amount] hit points; at zero or below the member dies. */ + fun wound(amount: IntExpr) { + hp -= amount + script.whenever(hp lte 0) { kill() } + } + + fun wound(amount: Int): Unit = wound(lit(amount)) + + /** Kills the member outright. The runtime keeps the party's count of living members. */ + fun kill() { + hp set 0 + dead set true + } + + /** Brings a dead member back to life with [hitPoints] hit points. */ + fun revive(hitPoints: Int = 1) { + dead set false + hp set hitPoints + } + private fun intField(field: String): IntSlot = IntSlot(script, LValueAst.MemberField(index.ast, field), IntAst.MemberField(index.ast, field)) } class MonsterRef( - script: ScriptScope, + private val script: ScriptScope, val index: IntExpr, ) { val hp: IntSlot = IntSlot(script, LValueAst.MonsterField(index.ast, "hit_points"), IntAst.MonsterField(index.ast, "hit_points")) @@ -311,6 +333,20 @@ class MonsterRef( LValueAst.MonsterField(index.ast, "dead"), BoolAst.MonsterFlag(index.ast, "dead"), ) + + /** Takes [amount] hit points; at zero or below the monster dies. */ + fun wound(amount: IntExpr) { + hp -= amount + script.whenever(hp lte 0) { kill() } + } + + fun wound(amount: Int): Unit = wound(lit(amount)) + + /** Kills the monster outright. */ + fun kill() { + hp set 0 + dead set true + } } class BattleRef( diff --git a/docs/dsl-authoring.md b/docs/dsl-authoring.md index 579732aa..c768f542 100644 --- a/docs/dsl-authoring.md +++ b/docs/dsl-authoring.md @@ -338,6 +338,17 @@ gainTorches(2) gainFood(10) ``` +Members and monsters take damage with `wound(amount)`, which also kills them at +zero hit points; `kill()` and `revive()` do the rest. The runtime keeps the +party's count of living members, so `party.memberCount` is only read: + +```kotlin +target.wound(damage) +whenever(target.dead) { + appendText { line("{red}", partyName(target), " DIES! {pause 1s}") } +} +``` + Use direct state slots for local mechanics such as costs, damage, timers, and script counters: diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 710b0264..dd5a1c42 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -4114,9 +4114,7 @@ val authoredRylween: RylweenModel = writeText("You don't have the gold! {pause 1s}") }, paid = { - m.hp set 1 - m.dead set false - party.memberCount += 1 + m.revive() playSound(Sounds.Spell.rebirth) writeText(flowText("The priestess raises ", pronoun(m, PronounCase.Object), ". {pause 1s}")) }, @@ -4888,11 +4886,8 @@ val authoredRylween: RylweenModel = localInt(caster.level * random(2..8)) { damage -> writeText(flowText(partyName(caster), " chills the opponent for ", damage, " damage pts. {pause 2s}")) - target.hp -= damage - - whenever(target.hp lte 0) { - target.hp set 0 - target.dead set true + target.wound(damage) + whenever(target.dead) { writeText("...KILLED! {pause 600ms}") } } @@ -4934,8 +4929,7 @@ val authoredRylween: RylweenModel = The enemy is wiped straight off the surface of the earth! {pause 2s} """, ) - target.dead set true - target.hp set 0 + target.kill() } } } @@ -4971,10 +4965,8 @@ val authoredRylween: RylweenModel = line("Frost Finger on ", partyName(target), "! {pause 1s}") line("and does ", damage, " pts of damage! {pause 1s}") } - target.hp -= damage - whenever(target.hp lte 0) { - target.hp set 0 - target.dead set true + target.wound(damage) + whenever(target.dead) { appendText { line("{red}", partyName(target), " DIES! {pause 1s}") } @@ -4988,10 +4980,8 @@ val authoredRylween: RylweenModel = forEachMember { target -> localInt((battle.encounterHitPointMax / 5) + random(0..4)) { damage -> writeText(flowText(partyName(target), " is burnt for ", damage, " damage pts! {pause 1s}")) - target.hp -= damage - whenever(target.hp lte 0) { - target.hp set 0 - target.dead set true + target.wound(damage) + whenever(target.dead) { writeText { line("{red}", partyName(target), " DIES! {pause 1s}") } @@ -5097,9 +5087,7 @@ val authoredRylween: RylweenModel = ) { target -> whenever(target.dead) { caster.mp -= cost - target.dead set false - party.memberCount += 1 - target.hp set 1 + target.revive() writeText( flowText( partyName(target), @@ -5335,14 +5323,9 @@ val authoredRylween: RylweenModel = ) { target -> consumeActiveItem() localInt(potionPoints(target)) { points -> - target.hp -= points + target.wound(points) writeText(flowText(partyName(target), " is poisoned for ", points, " hit points. {pause 1s}")) } - whenever(target.hp lte 0) { - target.hp set 0 - target.dead set true - party.memberCount -= 1 - } } } } @@ -5387,12 +5370,9 @@ val authoredRylween: RylweenModel = ), ) - target.hp -= damage - - whenever(target.hp lte 0) { - target.hp set 0 + target.wound(damage) + whenever(target.dead) { writeText("...KILLED! {pause 600ms}") - target.dead set true } } } @@ -5457,8 +5437,7 @@ val authoredRylween: RylweenModel = battle.firstAliveMonster { target -> writeText(flowText(partyName(caster), " summons death to take a ", monsterName(target), " away... {pause 2s}")) writeText("...KILLED! {pause 600ms}") - target.dead set true - target.hp set 0 + target.kill() clearText() } } @@ -5539,8 +5518,7 @@ val authoredRylween: RylweenModel = writeText { line(partyName(target), " opens ", pronoun(target, PronounCase.Possessive), " eyes! {pause 1s}") } - target.dead set false - target.hp set 1 + target.revive() consumeActiveItem() } otherwise { writeText { @@ -6782,12 +6760,9 @@ private fun ScriptScope.burnEveryLivingMonster( whenever(!foe.dead) { writeText(flowText(partyName(caster), " burns ", monsterName(foe), " for ", damage, " pts! {pause 1s}")) - foe.hp -= damage - - whenever(foe.hp lte 0) { - foe.hp set 0 + foe.wound(damage) + whenever(foe.dead) { writeText("...KILLED! {pause 600ms}") - foe.dead set true } } } diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt index 888da091..4a2b82bf 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt @@ -66,6 +66,26 @@ class ScriptExecutorTest { assertTrue(menu.size <= CLASSIC_TEXT_WINDOW_ROWS, "church menu must fit the classic text window: $menu") } + // The runtime counts the living members itself, so a raise must not count the raised member twice. + @Test + fun raisingTheDeadAtTheChurchCountsTheLivingOnce() { + val town = thordRuntime() + val members = town.party.members.mapIndexed { index, member -> if (index == 1) member.copy(dead = true) else member } + val runtime = + town.withParty( + town.party.copy( + members = members, + resources = town.party.resources.copy(gold = 100_000), + counters = town.party.counters.copy(memberCount = members.count { member -> !member.dead }), + ), + ) + + val after = runScript(scriptRoot(ScriptRootKind.Scene, "towne.church"), runtime, "R2PL", TextCapturingScreen(), "church-raise.log") + + assertTrue(after.party.members.none { member -> member.dead }, "the dead member is raised: ${after.party.members}") + assertEquals(after.party.members.size, after.party.counters.memberCount) + } + @Test fun shopMenusSeparateProseFromKeyChoicesWithoutRepeatingThem() { // Decline the forced beer interlude, dismiss its pause, open Buy, then decline the catalog choice. From 52dc7451ef4be83f5c9a2d9c7e3f803df62a98f5 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:16 +0100 Subject: [PATCH 04/16] Price spells with an authored spell cost formula 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. --- .../compiled/ExternalBundleArtifact.kt | 6 +++- core/src/main/kotlin/rylween/dsl/Dsl.kt | 20 +++++++------ .../main/kotlin/rylween/dsl/DslValidation.kt | 5 +++- .../main/kotlin/rylween/dsl/ItemRealmDsl.kt | 4 +++ .../rylween/dsl/impl/ContentModelsDsl.kt | 1 + docs/dsl-authoring.md | 2 +- .../main/kotlin/rylween/game/RylweenGame.kt | 20 ++++++++----- .../rylween/RylweenCompiledGameLedgerTest.kt | 5 ++-- .../kotlin/rylween/runtime/BattleRunner.kt | 13 ++++++--- .../kotlin/rylween/runtime/CastleRuntime.kt | 13 +++++++-- .../kotlin/rylween/runtime/DungeonRuntime.kt | 1 + .../kotlin/rylween/runtime/RuntimeFormulas.kt | 24 ++++++++++++++-- .../kotlin/rylween/runtime/RuntimeSecrets.kt | 12 +++++++- .../kotlin/rylween/runtime/ScriptExecutor.kt | 13 +++++++-- .../kotlin/rylween/runtime/UtilityActions.kt | 6 +++- .../rylween/runtime/WildernessActions.kt | 12 +++++++- .../rylween/runtime/BattleRunnerTest.kt | 9 +++--- .../rylween/runtime/RuntimeAudioTest.kt | 2 +- .../rylween/runtime/UtilityActionsTest.kt | 28 +++++++++++++++++-- 19 files changed, 154 insertions(+), 42 deletions(-) diff --git a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index 5ccca327..04783bde 100644 --- a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt +++ b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt @@ -89,7 +89,7 @@ import kotlin.reflect.typeOf private const val EXTERNAL_BUNDLE_FORMAT = "rylween.compiled.bundle" private const val EXTERNAL_BUNDLE_VERSION = 3 -private const val EXTERNAL_RUNTIME_SYSTEMS_VERSION = 13 +private const val EXTERNAL_RUNTIME_SYSTEMS_VERSION = 14 private const val GRID_CASTLE_KIND = "gridCastle" /** Serializes this game into the canonical strict JSON J1 artifact bytes. */ @@ -579,6 +579,8 @@ data class ExternalRuntimeRealm( val camp: ExternalCampRules, val hunt: ExternalHuntRules?, val timeOfDay: List, + /** Slug of the formula that prices a spell for its caster, or null when a spell costs its base cost. */ + val spellCost: String?, ) /** One status-line time label exported for direct runtimes. */ @@ -1714,6 +1716,7 @@ private class ExternalBundleArtifactWriter { "upkeep" to upkeepJson(realm.upkeep), "camp" to campJson(realm.camp), "hunt" to realm.hunt?.let(::huntJson).orJsonNull(), + "spellCost" to realm.spellCost?.let { formula -> JsonString(formula.slug) }.orJsonNull(), "timeOfDay" to JsonArray( realm.timeOfDay.map { band -> @@ -3813,6 +3816,7 @@ private class ExternalRuntimeSystemsReader( upkeep = requiredObject("upkeep").readUpkeep(), camp = requiredObject("camp").readCamp(), hunt = optional("hunt")?.takeUnless { it is JsonNull }?.asObject("hunt")?.readHunt(), + spellCost = optional("spellCost")?.takeUnless { it is JsonNull }?.asString("spellCost"), timeOfDay = requiredArray("timeOfDay") .values diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index cc349c34..e9fd648d 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -249,15 +249,13 @@ class ScriptScope( } /** - * Exposes the active caster plus the standard `baseCost + caster.level` - * expression used by current priest spells. + * Exposes the active caster plus what the spell costs them, as the game's + * `realm { spellCost }` formula works it out. The runtime supplies both, + * the way battle charges a mage spell. */ - fun withCurrentCasterCost( - baseCost: Int, - body: ScriptScope.(MemberRef, IntExpr) -> Unit, - ) { + fun withCurrentCasterCost(body: ScriptScope.(MemberRef, IntExpr) -> Unit) { withCurrentCaster { caster -> - body(caster, lit(baseCost) + caster.level) + body(caster, v("spell_cost")) } } @@ -3471,10 +3469,14 @@ class FormulaBuilder( val health: IntExpr = v("health") // Member stats, bound by the system that evaluates the formula: the - // hunting ranger, the thief disarming a castle trap, or, for a haggle roll - // bonus, the party's highest living charisma. + // hunting ranger, the thief disarming a castle trap, the caster of a spell, + // or, for a haggle roll bonus, the party's highest living charisma. val charisma: IntExpr = v("charisma") val dexterity: IntExpr = v("dexterity") + val level: IntExpr = v("level") + + // The spell being cast, for the spell cost formula; the caster's stats are bound above. + val spellBaseCost: IntExpr = v("spell_base_cost") fun whenValue( condition: BoolExpr, diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 6b33ef16..2f90fafa 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -323,7 +323,7 @@ fun validateFormulas(formulas: List) { check(formulas.map { it.id }.toSet().size == formulas.size) { "duplicate formula" } } -/** Validates that the hunt and castle trap chances name authored formulas. */ +/** Validates that the hunt and castle trap chances and the spell cost name authored formulas. */ private fun validateSystemFormulaReferences(content: GameModel) { val formulaIds = content.formulas.map { it.id }.toSet() content.realm.hunt?.let { hunt -> @@ -331,6 +331,9 @@ private fun validateSystemFormulaReferences(content: GameModel) { "hunt success chance references missing formula ${hunt.successChance.slug}" } } + content.realm.spellCost?.let { spellCost -> + check(spellCost in formulaIds) { "realm spell cost references missing formula ${spellCost.slug}" } + } content.castles.forEach { castle -> val disarmChance = checkNotNull(castle.pitfall.disarmChance) { "castle ${castle.id.slug} pitfall needs a disarm chance formula" } diff --git a/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt b/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt index 655c5acb..83da96f8 100644 --- a/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt @@ -135,6 +135,9 @@ class RealmContentBuilder { private var hunt: HuntRulesModel? = null private var timeOfDayBands = defaultTimeOfDayBands() + /** What a spell costs its caster, mage spells in battle and priest spells alike; without it a spell costs its base cost. */ + var spellCost: FormulaId? = null + fun baseResourceCapacity( resource: Resource, amount: Int, @@ -165,6 +168,7 @@ class RealmContentBuilder { camp = camp, hunt = hunt, timeOfDay = timeOfDayBands, + spellCost = spellCost, ) } diff --git a/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt index 83312ca8..414c388f 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt @@ -64,6 +64,7 @@ data class RealmContentModel( val camp: CampRulesModel = CampRulesModel(), val hunt: HuntRulesModel? = null, val timeOfDay: List = defaultTimeOfDayBands(), + val spellCost: FormulaId? = null, ) /** Authored label for an inclusive hour span in the status line. */ diff --git a/docs/dsl-authoring.md b/docs/dsl-authoring.md index c768f542..3e64dd5d 100644 --- a/docs/dsl-authoring.md +++ b/docs/dsl-authoring.md @@ -722,7 +722,7 @@ Use this placement rule during design review: A change to the shape of the `runtimeSystems` rows also bumps `EXTERNAL_RUNTIME_SYSTEMS_VERSION` in -`core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt` (12 today), so +`core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt` (14 today), so a runtime refuses a bundle written for another shape. If a rule mentions Rylween story content, item names, NPCs, mission prose, diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index dd5a1c42..2d2c79aa 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -397,6 +397,7 @@ val authoredRylween: RylweenModel = // capacity, turn upkeep, hunting, camping, fatigue, and starvation. realm { baseResourceCapacity(Resource.Food, 150) + spellCost = Formulas.spellCost // Upkeep runs during wilderness turns. These fields control food // ticking, fatigue labels/drain, mana recovery, and starvation. upkeep { @@ -1332,6 +1333,11 @@ val authoredRylween: RylweenModel = formula(Formulas.haggleRollBonus) { value = whenValue(charisma gt 90, lit(20), (charisma - 50) / 2) } + // A spell costs its base cost plus the caster's level, for mage + // spells in battle and priest spells alike. + formula(Formulas.spellCost) { + value = spellBaseCost + level + } } // Reward bundles define how XP, gold, loot, and special milestones @@ -5016,7 +5022,7 @@ val authoredRylween: RylweenModel = // runtime owns the "Who?", class gate, spell list, and abort key; these // blocks declare the current game's spell effects. spell(Spells.Priest.heal, slot = 1, baseCost = 8, name = "Healing") { - withCurrentCasterCost(8) { caster, cost -> + withCurrentCasterCost { caster, cost -> clearText() whenever(caster.mp gte cost) { caster.mp -= cost @@ -5054,7 +5060,7 @@ val authoredRylween: RylweenModel = } spell(Spells.Priest.restoration, slot = 2, baseCost = 20, name = "Restoration") { - withCurrentCasterCost(20) { caster, cost -> + withCurrentCasterCost { caster, cost -> clearText() whenever(caster.mp gte cost) { caster.mp -= cost @@ -5076,7 +5082,7 @@ val authoredRylween: RylweenModel = } spell(Spells.Priest.rebirth, slot = 3, baseCost = 90, name = "Rebirth") { - withCurrentCasterCost(90) { caster, cost -> + withCurrentCasterCost { caster, cost -> clearText() whenever(caster.mp gte cost) { ask.member( @@ -5111,7 +5117,7 @@ val authoredRylween: RylweenModel = } spell(Spells.Priest.banish, slot = 4, baseCost = 85, name = "Banish Evil") { - withCurrentCasterCost(85) { caster, cost -> + withCurrentCasterCost { caster, cost -> clearText() whenever(caster.mp gte cost) { whenever(context.inDungeon) { @@ -5157,7 +5163,7 @@ val authoredRylween: RylweenModel = } spell(Spells.Priest.revelation, slot = 5, baseCost = 40, name = "Revelation") { - withCurrentCasterCost(40) { caster, cost -> + withCurrentCasterCost { caster, cost -> clearText() whenever(caster.mp gte cost) { whenever(context.inDungeon) { @@ -5191,7 +5197,7 @@ val authoredRylween: RylweenModel = } spell(Spells.Priest.teleport, slot = 6, baseCost = 35, name = "Teleport") { - withCurrentCasterCost(35) { caster, cost -> + withCurrentCasterCost { caster, cost -> whenever(caster.mp gte cost) { caster.mp -= cost writeText( @@ -5241,7 +5247,7 @@ val authoredRylween: RylweenModel = } spell(Spells.Priest.earthquake, slot = 7, baseCost = 55, name = "Earthquake") { - withCurrentCasterCost(55) { caster, cost -> + withCurrentCasterCost { caster, cost -> clearText() whenever(context.inDungeon or context.inCastle) { showTextAndWait("The roof would cave in on you!") diff --git a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt index eb722b2c..454b50d1 100644 --- a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt +++ b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt @@ -117,7 +117,8 @@ class RylweenCompiledGameLedgerTest { val externalBundleText = externalBundle.decodeToString() val runtimeSystems = externalBundle.readExternalRuntimeSystems() - check(runtimeSystems.schemaVersion == 13) + check(runtimeSystems.schemaVersion == 14) + check(runtimeSystems.realm.spellCost == Formulas.spellCost.slug) check("\"dexterity\"" in externalBundleText) check(nextDsl.flags.size == 14) check(nextDsl.authoredFlags.size == 14) @@ -198,7 +199,7 @@ class RylweenCompiledGameLedgerTest { it.requiredStat == CharacterCreationStat.Dexterity && it.minimum == 50 }, ) - check(nextDsl.formulas.size == 8) + check(nextDsl.formulas.size == 9) check(nextDsl.rewards.size == 1) check( nextDsl.rewards diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt index 49d353ab..6b0742a1 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt @@ -102,6 +102,8 @@ internal data class BattleResult( internal class BattleRunner( private val content: CompiledContentBundle, private val combat: ExternalRuntimeCombat, + // The game's spell cost formula, from the realm rules. + private val spellCost: String?, private val pacing: ExternalBattlePacing, private val input: RuntimeInputPort, private val screen: RuntimeScreenPort, @@ -569,7 +571,7 @@ internal class BattleRunner( messages: MutableList, ): BattleEncounter { val spells = mageSpells() - screen.writeText(spellChoiceLines(member, spells)) + screen.writeText(spellChoiceLines(member, spells, runtime.party)) val command = input.readCommand()?.uppercaseChar() ?: return copy(actionRetry = true) if (command == BATTLE_SPELL_CANCEL_KEY) return copy(actionRetry = true) val slot = command.digitToIntOrNull() ?: return copy(actionRetry = true) @@ -583,7 +585,7 @@ internal class BattleRunner( messages += rules.text.spellFizzle.renderBattle() return this } - val cost = spell.baseCost + member.level + val cost = content.spellCost(spellCost, spell, member, runtime.party) if (member.mana.current < cost) { audio.cue(AudioCue.SpellFizzle) messages += rules.text.notEnoughMagic.renderBattle() @@ -594,7 +596,7 @@ internal class BattleRunner( return copy(runtime = runtime.withMember(memberIndex, nextMember)) .runBattleScript( scriptRoot = spell.scriptRoot, - locals = mapOf("caster_idx" to memberIndex), + locals = mapOf("caster_idx" to memberIndex, "spell_cost" to cost), ) } @@ -1109,6 +1111,7 @@ internal class BattleRunner( private fun spellChoiceLines( member: CompiledPartyMember, spells: List, + party: PartyState, ): List = screen.choiceMenuLines( prompt = emptyList(), @@ -1116,7 +1119,9 @@ internal class BattleRunner( spells.map { spell -> choiceLine( spell.slot, - "${content.strings.value(spell.nameString)} (${spell.baseCost + member.level}/${member.mana.current})", + "${content.strings.value( + spell.nameString, + )} (${content.spellCost(spellCost, spell, member, party)}/${member.mana.current})", ) }, trailer = diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt index 6ecb6a62..2756469d 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt @@ -187,8 +187,17 @@ internal class CastleRuntime( ): RuntimeState { screen.writeText(castle.text.roomMonster.renderCastle(screen.textColumns)) val battle = - BattleRunner(content, systems.combat, systems.pacing.battle, input, screen, log, PausePrompts(systems.prompts), systems.audio) - .runTier(runtime, castle.monsterTier) + BattleRunner( + content, + systems.combat, + systems.realm.spellCost, + systems.pacing.battle, + input, + screen, + log, + PausePrompts(systems.prompts), + systems.audio, + ).runTier(runtime, castle.monsterTier) if (battle.messages.isNotEmpty()) screen.writeText(battle.messages) return battle.runtime.copy( currentMode = diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt index ec9c3b09..e69639a3 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt @@ -175,6 +175,7 @@ internal class DungeonRuntime( BattleRunner( content, systems.combat, + systems.realm.spellCost, systems.pacing.battle, input, screen, diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeFormulas.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeFormulas.kt index 98968048..2130fac9 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeFormulas.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeFormulas.kt @@ -4,8 +4,9 @@ * A formula is a named integer expression from the compiled bundle. The system * that evaluates it binds the formula's variables: battle rewards bind the * encounter numbers, leveling binds the new health, hunting binds the hunter's - * stats, a castle trap binds the disarming thief's stats, and a shop haggle - * binds the party's best charisma. + * stats, a castle trap binds the disarming thief's stats, a spell binds its + * caster's stats and base cost, and a shop haggle binds the party's best + * charisma. */ package rylween.runtime @@ -17,6 +18,7 @@ import rylween.compiled.CompiledHandleKind import rylween.compiled.CompiledHandleRef import rylween.compiled.CompiledIntExpr import rylween.compiled.CompiledPartyMember +import rylween.compiled.CompiledSpell import rylween.compiled.applyCompiledBinary import rylween.compiled.compareCompiled @@ -54,13 +56,29 @@ internal fun CompiledContentBundle.evalFormula( bindings: Map, ): FormulaResult = FormulaEvaluator(this, party, bindings).eval(formula.value) -/** The stat variables a formula sees for the one member it is evaluated for, such as a hunter or a disarming thief. */ +/** The stat variables a formula sees for the one member it is evaluated for, such as a hunter, a disarming thief or a caster. */ internal fun CompiledPartyMember.statBindings(): Map = mapOf( "charisma" to charisma, "dexterity" to dexterity, + "level" to level, ) +/** + * What [spell] costs [caster] in spell points: the game's spell cost formula + * [formulaSlug], evaluated with the caster's stats and the spell's base cost, + * or the base cost alone when the game declares no formula. + */ +internal fun CompiledContentBundle.spellCost( + formulaSlug: String?, + spell: CompiledSpell, + caster: CompiledPartyMember, + party: PartyState, +): Int = + formulaSlug + ?.let { slug -> evalFormula(slug, party, caster.statBindings() + ("spell_base_cost" to spell.baseCost)).value } + ?: spell.baseCost + private class FormulaEvaluator( private val content: CompiledContentBundle, private var party: PartyState, diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSecrets.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSecrets.kt index c33ad933..8aa52495 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSecrets.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSecrets.kt @@ -165,5 +165,15 @@ internal class SecretActions( ?: content.slug(item) private fun battleRunner(): BattleRunner = - BattleRunner(content, systems.combat, systems.pacing.battle, input, screen, log, PausePrompts(systems.prompts), systems.audio) + BattleRunner( + content, + systems.combat, + systems.realm.spellCost, + systems.pacing.battle, + input, + screen, + log, + PausePrompts(systems.prompts), + systems.audio, + ) } diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/ScriptExecutor.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/ScriptExecutor.kt index f92a5464..9b6a77cc 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/ScriptExecutor.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/ScriptExecutor.kt @@ -899,8 +899,17 @@ internal class ScriptExecutor( mandatory: Boolean, ) { val battle = - BattleRunner(content, systems.combat, systems.pacing.battle, input, screen, log, pausePrompts, systems.audio) - .runMonster(runtime, monster, mandatory = mandatory) + BattleRunner( + content, + systems.combat, + systems.realm.spellCost, + systems.pacing.battle, + input, + screen, + log, + pausePrompts, + systems.audio, + ).runMonster(runtime, monster, mandatory = mandatory) runtime = battle.runtime if (battle.messages.isNotEmpty()) screen.writeText(battle.messages) if (runtime.currentMode != RuntimeMode.GameOver) music?.let(screen::playMusic) diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt index 94f523cc..11ebb663 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt @@ -197,7 +197,11 @@ internal class UtilityActions( input = input, screen = screen, initialRuntime = runtime, - initialLocals = mapOf("caster_idx" to casterIndex + 1), + initialLocals = + mapOf( + "caster_idx" to casterIndex + 1, + "spell_cost" to content.spellCost(systems.realm.spellCost, spell, runtime.party.members[casterIndex], runtime.party), + ), log = log, ).execute(program) } diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt index 9805d2fc..7fd1d49d 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt @@ -745,7 +745,17 @@ internal class WildernessActions( ) private fun battleRunner(): BattleRunner = - BattleRunner(content, combat, systems.pacing.battle, input, screen, log, PausePrompts(systems.prompts), systems.audio) + BattleRunner( + content, + combat, + systems.realm.spellCost, + systems.pacing.battle, + input, + screen, + log, + PausePrompts(systems.prompts), + systems.audio, + ) private fun PartyState.matches(expr: CompiledBoolExpr): Boolean = when (expr) { diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/BattleRunnerTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/BattleRunnerTest.kt index 869c2e1a..4ee49ec9 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/BattleRunnerTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/BattleRunnerTest.kt @@ -38,7 +38,7 @@ class BattleRunnerTest { val input = ScriptedInput("FAA") RuntimeLog.open(testTmp.resolve("battle-saved-names.log")).use { log -> - BattleRunner(content, systems.combat, systems.pacing.battle, input, screen, log) + BattleRunner(content, systems.combat, systems.realm.spellCost, systems.pacing.battle, input, screen, log) .runMonster(runtime, content.monsters.first().id, mandatory = true) } @@ -58,7 +58,7 @@ class BattleRunnerTest { val screen = CapturingBattleScreen() val result = RuntimeLog.open(testTmp.resolve("battle-kill-tally.log")).use { log -> - BattleRunner(content, systems.combat, systems.pacing.battle, input, screen, log) + BattleRunner(content, systems.combat, systems.realm.spellCost, systems.pacing.battle, input, screen, log) .runMonster(runtime, chief, mandatory = true) } @@ -78,7 +78,7 @@ class BattleRunnerTest { val result = RuntimeLog.open(testTmp.resolve("battle-level-up-mana.log")).use { log -> - BattleRunner(content, systems.combat, systems.pacing.battle, input, CapturingBattleScreen(), log) + BattleRunner(content, systems.combat, systems.realm.spellCost, systems.pacing.battle, input, CapturingBattleScreen(), log) .runMonster(runtime, chief, mandatory = true) } @@ -181,6 +181,7 @@ class BattleRunnerTest { BattleRunner( holding, systems.combat, + systems.realm.spellCost, systems.pacing.battle, ScriptedInput("F" + "D".repeat(runtime.party.members.size)), screen, @@ -218,7 +219,7 @@ class BattleRunnerTest { val logged = mutableListOf() val result = RuntimeLog.open(testTmp.resolve("battle-run.log"), listOf { line -> logged += line }).use { log -> - BattleRunner(content, systems.combat, systems.pacing.battle, ScriptedInput(commands), screen, log) + BattleRunner(content, systems.combat, systems.realm.spellCost, systems.pacing.battle, ScriptedInput(commands), screen, log) .runMonster(runtime, content.ref(CompiledHandleKind.Monster, "hobgoblin_chief"), mandatory) } return BattleFight(result, (screen.textLines + result.messages).joinToString("\n"), logged) diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeAudioTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeAudioTest.kt index b0a3ec31..781edd5b 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeAudioTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeAudioTest.kt @@ -119,7 +119,7 @@ class RuntimeAudioTest { val input = ScriptedInput(("F" + "AA".repeat(runtime.party.members.size)).repeat(ROUNDS)) RuntimeLog.open(testTmp.resolve("audio-battle-miss.log")).use { log -> - BattleRunner(content, systems.combat, systems.pacing.battle, input, screen, log, audioData = audio) + BattleRunner(content, systems.combat, systems.realm.spellCost, systems.pacing.battle, input, screen, log, audioData = audio) .runMonster(runtime, content.ref(CompiledHandleKind.Monster, "hobgoblin_chief"), mandatory = true) } diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/UtilityActionsTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/UtilityActionsTest.kt index a31e4c42..f6d08560 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/UtilityActionsTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/UtilityActionsTest.kt @@ -272,6 +272,27 @@ class UtilityActionsTest { assertEquals(GridPoint(1, 2), world.lastPassable(GridPoint(1, 2), GridPoint(0, 1), steps = 18)) } + // The game prices spells with its spell cost formula: a heal costs its base cost plus the priest's level. + @Test + fun castingAPriestSpellChargesTheGamesSpellCost() { + val base = runtimeWithInventory() + val priest = base.party.members.indexOfFirst { member -> member.pcClass == PcClass.Priest } + val runtime = base.updateMember(priest) { member -> member.copy(mana = 200 of 200) } + val heal = priestSpells().single { spell -> content.slug(spell.id) == "priest.heal" } + val spellKey = + systems.prompts.priest.firstSpellKey + .single() + priestSpells().indexOf(heal) + + val after = runUtility("heal-cost.log", "${priest + 1}${spellKey}1") { actions -> actions.castPriestSpell(runtime) } + + val level = runtime.party.members[priest].level + assertEquals( + 200 - (heal.baseCost + level), + after.party.members[priest] + .mana.current, + ) + } + /** Where the party lands when its priest teleports it [miles] miles towards [direction] from [from]. */ private fun teleport( from: GridPoint, @@ -281,10 +302,9 @@ class UtilityActionsTest { val base = runtimeWithInventory() val priest = base.party.members.indexOfFirst { member -> member.pcClass == PcClass.Priest } val runtime = base.updateMember(priest) { member -> member.copy(mana = 200 of 200) } - val spells = content.spells.filter { spell -> content.slug(spell.id).startsWith("priest.") }.sortedBy(CompiledSpell::slot) val spellKey = systems.prompts.priest.firstSpellKey - .single() + spells.indexOfFirst { spell -> content.slug(spell.id) == "priest.teleport" } + .single() + priestSpells().indexOfFirst { spell -> content.slug(spell.id) == "priest.teleport" } val input = ScriptedInput("${priest + 1}$spellKey $direction$miles") val after = runUtility("teleport.log", input) { actions -> actions.castPriestSpell(runtime.withParty(runtime.party.copy(position = from))) } @@ -293,6 +313,10 @@ class UtilityActionsTest { return after.party.position } + // The priest spells in the order the spell menu lists them. + private fun priestSpells(): List = + content.spells.filter { spell -> content.slug(spell.id).startsWith("priest.") }.sortedBy(CompiledSpell::slot) + private fun leavePrompts(): List = checkNotNull(systems.town).leavePrompts.also { prompts -> assertEquals(listOf(EquipmentCommand.ReadyWeapon, EquipmentCommand.ReadyArmor), prompts) From 05e4365827bca2d66c517f129764708be42c69e7 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:16 +0100 Subject: [PATCH 05/16] Build collections without needless mutable state 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. --- .../rylween/gradle/RylweenBuildTasks.kt | 102 +++++------ .../compiled/ExternalBundleArtifact.kt | 9 +- .../kotlin/rylween/dsl/AuthoringFacade.kt | 3 +- core/src/main/kotlin/rylween/dsl/Dsl.kt | 9 +- .../main/kotlin/rylween/dsl/DslValidation.kt | 2 +- .../rylween/dsl/ScriptSourceAnalysis.kt | 20 +- .../main/kotlin/rylween/dsl/impl/FlagDsl.kt | 6 +- .../rylween/RylweenOpcodeContractTest.kt | 22 ++- .../rylween/bitmapweb/BitmapDocument.kt | 49 ++--- .../rylween/bitmapweb/BitmapRuntimePorts.kt | 60 +++--- .../kotlin/rylween/runtime/BattleRunner.kt | 80 ++++---- .../kotlin/rylween/runtime/CastleRuntime.kt | 2 +- .../kotlin/rylween/runtime/DungeonRuntime.kt | 8 +- .../kotlin/rylween/runtime/RuntimeSecrets.kt | 51 +++--- .../rylween/runtime/RylweenRuntimeMain.kt | 173 +++++++++--------- .../main/kotlin/rylween/runtime/SaveFile.kt | 22 ++- .../kotlin/rylween/runtime/ScriptExecutor.kt | 16 +- .../kotlin/rylween/runtime/ShopService.kt | 24 +-- .../kotlin/rylween/runtime/UtilityActions.kt | 10 +- .../rylween/runtime/WildernessActions.kt | 99 +++++----- .../rylween/runtime/AutopilotCreation.kt | 11 +- .../rylween/runtime/AutopilotFullGame.kt | 42 +++-- .../rylween/runtime/PrerolledPartyTest.kt | 105 ++++++----- .../test/kotlin/rylween/runtime/ReplayPlan.kt | 16 +- .../runtime/RuntimeSessionFactoryTest.kt | 2 +- .../main/kotlin/rylween/terminal/AnsiInput.kt | 46 ++--- .../tools/CompiledBundleArtifactMain.kt | 34 ++-- .../main/kotlin/rylween/webcommon/WebHttp.kt | 32 ++-- .../kotlin/rylween/webcommon/auth/WebAuth.kt | 2 +- 29 files changed, 521 insertions(+), 536 deletions(-) diff --git a/build-logic/src/main/kotlin/rylween/gradle/RylweenBuildTasks.kt b/build-logic/src/main/kotlin/rylween/gradle/RylweenBuildTasks.kt index f6d2ea52..2e1cbe31 100644 --- a/build-logic/src/main/kotlin/rylween/gradle/RylweenBuildTasks.kt +++ b/build-logic/src/main/kotlin/rylween/gradle/RylweenBuildTasks.kt @@ -128,44 +128,48 @@ abstract class RunInstalledLauncherWithJavaTask "configure exactly one launcher smoke mode: screen or script" } val launcherArgs = - mutableListOf( - executableFile.get().asFile.path, - "--bundle", - bundleFile.get().asFile.path, - "--log", - logFile.get().asFile.path, - ) - if (hasScreen) { - launcherArgs += listOf("--screen", screen.get()) - } - if (userId.isPresent) { - launcherArgs += listOf("--user", userId.get()) - } - if (stateSlug.isPresent) { - launcherArgs += listOf("--state", stateSlug.get()) - } - if (hasScript) { - launcherArgs += listOf("--script", script.get()) - } - if (title.orNull == true) { - launcherArgs += "--title" - } - if (seed.isPresent) { - launcherArgs += listOf("--seed", seed.get().toString()) - } - if (debugLog.orNull == true) { - launcherArgs += "--debug-log" - } - if (debugSecrets.orNull == true) { - launcherArgs += "--debug-secrets" - } - if (loadFile.isPresent) { - launcherArgs += listOf("--load", loadFile.get().asFile.path) - } - if (saveFile.isPresent) { - if (resetSaveFile.orNull == true) saveFile.get().asFile.delete() - launcherArgs += listOf("--save", saveFile.get().asFile.path) - } + buildList { + addAll( + listOf( + executableFile.get().asFile.path, + "--bundle", + bundleFile.get().asFile.path, + "--log", + logFile.get().asFile.path, + ), + ) + if (hasScreen) { + addAll(listOf("--screen", screen.get())) + } + if (userId.isPresent) { + addAll(listOf("--user", userId.get())) + } + if (stateSlug.isPresent) { + addAll(listOf("--state", stateSlug.get())) + } + if (hasScript) { + addAll(listOf("--script", script.get())) + } + if (title.orNull == true) { + add("--title") + } + if (seed.isPresent) { + addAll(listOf("--seed", seed.get().toString())) + } + if (debugLog.orNull == true) { + add("--debug-log") + } + if (debugSecrets.orNull == true) { + add("--debug-secrets") + } + if (loadFile.isPresent) { + addAll(listOf("--load", loadFile.get().asFile.path)) + } + if (saveFile.isPresent) { + if (resetSaveFile.orNull == true) saveFile.get().asFile.delete() + addAll(listOf("--save", saveFile.get().asFile.path)) + } + } val javaHome = javaLauncher.get().metadata.installationPath.asFile.absolutePath val output = ByteArrayOutputStream() val result = @@ -1458,15 +1462,9 @@ abstract class GenerateGameCatalogHandlesTask : DefaultTask() { ) } - private fun List.distinctInOrder(): List { - val seen = linkedSetOf() - return filter { seen.add(it) } - } + private fun List.distinctInOrder(): List = distinct() - private fun List.distinctNamesInOrder(): List { - val seen = linkedSetOf() - return mapNotNull { handle -> handle.name.takeIf { seen.add(it) } } - } + private fun List.distinctNamesInOrder(): List = map(SourceHandle::name).distinct() private fun MatchResult.groupOffset(index: Int): Int = groups[index]?.range?.first ?: range.first @@ -1497,15 +1495,9 @@ abstract class GenerateGameCatalogHandlesTask : DefaultTask() { private fun String.sourceLocation(offset: Int): SourceLocation { val boundedOffset = offset.coerceIn(0, length) - var line = 1 - var lineStart = 0 - for (index in 0 until boundedOffset) { - if (this[index] == '\n') { - line += 1 - lineStart = index + 1 - } - } - return SourceLocation(line, boundedOffset - lineStart + 1) + val before = take(boundedOffset) + val lineStart = before.lastIndexOf('\n') + 1 + return SourceLocation(line = before.count { char -> char == '\n' } + 1, column = boundedOffset - lineStart + 1) } private fun validateNoDuplicateDeclarations( diff --git a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index 04783bde..5150b396 100644 --- a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt +++ b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt @@ -4897,11 +4897,4 @@ private inline fun > JsonObject.requiredEnum(name: String): private inline fun > JsonObject.optionalNullableEnum(name: String): T? = optionalNullableString(name)?.let(::enumValueOf) -internal fun ByteArray.fnv1a32(): Int { - var hash = 0x811c9dc5.toInt() - forEach { byte -> - hash = hash xor (byte.toInt() and 0xff) - hash *= 0x01000193 - } - return hash -} +internal fun ByteArray.fnv1a32(): Int = fold(0x811c9dc5.toInt()) { hash, byte -> (hash xor (byte.toInt() and 0xff)) * 0x01000193 } diff --git a/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt b/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt index 3dfcc57f..f8518398 100644 --- a/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt +++ b/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt @@ -44,6 +44,7 @@ package rylween.dsl +import rylween.dsl.impl.declareFlag as implDeclareFlag import rylween.dsl.impl.item as implShopItem import rylween.dsl.impl.withStateModule as implWithStateModule @@ -143,7 +144,7 @@ infix fun Int.of(max: Int): StatPool = StatPool(this, max) fun shopText(body: ShopTextBuilder.() -> Unit): TextBlock = rylween.dsl.impl.shopText(body) -fun F.declareFlag(): F = also { flag -> rylween.dsl.impl.declaredFlags += flag } +fun F.declareFlag(): F = implDeclareFlag() fun ShopItemSink.item( binding: InputBindingModel, diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index e9fd648d..a316476d 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -322,7 +322,7 @@ class ScriptScope( ) { val builder = SwitchBuilder(ctx) builder.body() - record(ScriptStatementNode.Switch(expr.ast, builder.cases)) + record(ScriptStatementNode.Switch(expr.ast, builder.cases.toList())) } fun menu( @@ -823,17 +823,18 @@ class ElseBranch( class SwitchBuilder( private val ctx: ScriptContext, ) { - val cases: MutableList = mutableListOf() + private val switchCases = mutableListOf() + val cases: List get() = switchCases fun case( value: Int, body: ScriptScope.() -> Unit, ) { - cases += SwitchCase(value, recordStatementNodes(ctx, body)) + switchCases += SwitchCase(value, recordStatementNodes(ctx, body)) } fun default(body: ScriptScope.() -> Unit) { - cases += SwitchCase(null, recordStatementNodes(ctx, body)) + switchCases += SwitchCase(null, recordStatementNodes(ctx, body)) } } diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 2f90fafa..8e3e69ee 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -1192,7 +1192,7 @@ private fun validateRandomNpcTownServices( check(option.services.isNotEmpty()) { "character ${character.slug} random placement in ${option.town.slug} has no town services" } - val townServices = town.services.mapTo(mutableSetOf(), TownServiceModel::building) + val townServices = town.services.map(TownServiceModel::building).toSet() option.services.forEach { service -> check(service in townServices) { "character ${character.slug} random placement references ${option.town.slug}.${service.slug}, but that town does not offer the service" diff --git a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt index 660949e8..25122b7d 100644 --- a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt +++ b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt @@ -222,15 +222,8 @@ fun ScriptSourceRoot.visitScriptStatements(visitor: (ScriptSourceStatement) -> U } /** Returns true when any source statement in this source root matches [predicate]. */ -fun ScriptSourceRoot.anyScriptStatement(predicate: (ScriptStatement) -> Boolean): Boolean { - var found = false - visitScriptStatements { sourceStatement -> - if (!found && predicate(sourceStatement.statement)) { - found = true - } - } - return found -} +fun ScriptSourceRoot.anyScriptStatement(predicate: (ScriptStatement) -> Boolean): Boolean = + buildList { visitScriptStatements { sourceStatement -> add(sourceStatement.statement) } }.any(predicate) /** Walks an authored script using the shared traversal that feeds validation and source maps. */ fun visitScriptStatements( @@ -663,8 +656,8 @@ private class UnreadTextScan( private val scriptEnd = mutableSetOf() private class LoopExit { - val unread = mutableSetOf() - var reached = false + /** What the breaks out of the loop left unread, or null while no break has reached it. */ + var unread: Set? = null } fun scan(statements: List): List { @@ -771,7 +764,7 @@ private class UnreadTextScan( // A second pass carries the end of one iteration into the start of the next. scan(body, unread)?.let { end -> scan(body, unread + end) } loopExits.removeLast() - return exit.unread.takeIf { exit.reached } + return exit.unread } /** A member or monster iteration runs its body any number of times, including none. */ @@ -795,8 +788,7 @@ private class UnreadTextScan( if (exit == null) { scriptEnd += unread } else { - exit.unread += unread - exit.reached = true + exit.unread = exit.unread.orEmpty() + unread } null } diff --git a/core/src/main/kotlin/rylween/dsl/impl/FlagDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/FlagDsl.kt index 3a4402d5..57cc5c13 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/FlagDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/FlagDsl.kt @@ -33,8 +33,10 @@ open class FlagState internal constructor( override val ast: BoolAst = BoolAst.FlagIs(flag.slug, native) } +private val flagRegistry = mutableListOf() + /** Process-local registry populated by generated flag declarations. */ -val declaredFlags: MutableList = mutableListOf() +val declaredFlags: List get() = flagRegistry /** Registers a generated or hand-authored flag reference for validation and save parsing. */ -fun F.declareFlag(): F = also { declaredFlags += it } +fun F.declareFlag(): F = also { flagRegistry += it } diff --git a/game/src/test/kotlin/rylween/RylweenOpcodeContractTest.kt b/game/src/test/kotlin/rylween/RylweenOpcodeContractTest.kt index a1571abe..e031ab3d 100644 --- a/game/src/test/kotlin/rylween/RylweenOpcodeContractTest.kt +++ b/game/src/test/kotlin/rylween/RylweenOpcodeContractTest.kt @@ -34,10 +34,12 @@ class RylweenOpcodeContractTest { @Test fun emittedBundleInstructionsMatchTheirSchema() { val bundle = RylweenCompiledGame.nextRylween.toCompiledGameBundle() - val violations = mutableListOf() - bundle.content.scripts.roots.forEach { root -> - walk(root.instructions, root.rootHandle.toString(), violations) - } + val violations = + buildList { + bundle.content.scripts.roots.forEach { root -> + walk(root.instructions, root.rootHandle.toString(), this) + } + } assertTrue( violations.isEmpty(), "compiled bundle has ${violations.size} contract violation(s):\n" + violations.joinToString("\n"), @@ -56,8 +58,7 @@ class RylweenOpcodeContractTest { val instructionIndex = root.instructions.indexOfFirst(::hasFirstOperandOtherThanHandleList) val original = root.instructions[instructionIndex] val originalFirstSlot = CompiledOpcodeContract.slotOf(original.operands.first()) - val mutatedOperands = original.operands.toMutableList() - mutatedOperands[0] = CompiledOperand.HandleList(emptyList()) + val mutatedOperands = listOf(CompiledOperand.HandleList(emptyList())) + original.operands.drop(1) val mutatedBundle = bundle.withScriptInstruction( rootIndex = rootIndex, @@ -203,10 +204,11 @@ class RylweenOpcodeContractTest { instruction: CompiledInstruction, ): CompiledGameBundle { val root = content.scripts.roots[rootIndex] - val instructions = root.instructions.toMutableList() - instructions[instructionIndex] = instruction - val roots = content.scripts.roots.toMutableList() - roots[rootIndex] = root.copy(instructions = instructions) + val instructions = root.instructions.mapIndexed { index, current -> if (index == instructionIndex) instruction else current } + val roots = + content.scripts.roots.mapIndexed { index, current -> + if (index == rootIndex) root.copy(instructions = instructions) else current + } return copy(content = content.copy(scripts = content.scripts.copy(roots = roots))) } } diff --git a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapDocument.kt b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapDocument.kt index 53284c9c..b7c5dd70 100644 --- a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapDocument.kt +++ b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapDocument.kt @@ -109,34 +109,35 @@ internal fun bitmapMarkdownDocumentLayout( * code block only splits across pages when enough of it lands on both sides. */ internal fun List.toBitmapDocumentPages(rows: Int = BITMAP_DOCUMENT_ROWS): List> { - val pages = mutableListOf>() - var page = mutableListOf() + val lines = this + return buildList { + var page = emptyList() - fun closePage() { - pages += page.dropLastWhile(BitmapDocumentLine::isBlank) - page = mutableListOf() - } - - var index = 0 - while (index < size) { - if (this[index].isBlank) { - if (page.isNotEmpty()) page += this[index] - index += 1 - if (page.size >= rows) closePage() - continue + fun closePage() { + add(page.dropLastWhile(BitmapDocumentLine::isBlank)) + page = emptyList() } - val take = linesToPlace(index, free = rows - page.size, pageEmpty = page.isEmpty()) - if (take == 0) { - closePage() - continue + + var index = 0 + while (index < lines.size) { + if (lines[index].isBlank) { + if (page.isNotEmpty()) page += lines[index] + index += 1 + if (page.size >= rows) closePage() + continue + } + val take = lines.linesToPlace(index, free = rows - page.size, pageEmpty = page.isEmpty()) + if (take == 0) { + closePage() + continue + } + page += lines.subList(index, index + take) + index += take + val runSplit = index < lines.size && !lines[index].isBlank && lines[index].kind == lines[index - 1].kind + if (page.size >= rows || runSplit) closePage() } - page += subList(index, index + take) - index += take - val runSplit = index < size && !this[index].isBlank && this[index].kind == this[index - 1].kind - if (page.size >= rows || runSplit) closePage() + if (page.isNotEmpty() || isEmpty()) closePage() } - if (page.isNotEmpty() || pages.isEmpty()) closePage() - return pages } /** diff --git a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapRuntimePorts.kt b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapRuntimePorts.kt index d5dadf26..eb609ede 100644 --- a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapRuntimePorts.kt +++ b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/BitmapRuntimePorts.kt @@ -99,25 +99,28 @@ internal class BitmapRuntimeInput : RuntimeInputPort { override fun readText(maxLength: Int?): String? { val limit = (maxLength ?: 80).coerceAtLeast(0) - val text = StringBuilder() logEvent?.invoke("input.text.start maxLength=$limit transport=bitmap") - publishTextInput(text.toString(), limit) - while (true) { - when (val token = input.take()) { - CLOSED_INPUT -> return closeTextInput(null, "closed") - "ENTER", "RETURN" -> return closeTextInput(text.toString(), "submit") - "ESCAPE" -> return closeTextInput(null, "escape") - "BACKSPACE" -> { - if (text.isNotEmpty()) text.deleteAt(text.lastIndex) - publishTextInput(text.toString(), limit) - } - else -> { - val char = token.singleOrNull()?.takeIf { value -> !value.isISOControl() } - if (char != null && text.length < limit) text.append(char) - publishTextInput(text.toString(), limit) + val text = + buildString { + publishTextInput(toString(), limit) + while (true) { + when (val token = input.take()) { + CLOSED_INPUT -> return closeTextInput(null, "closed") + "ENTER", "RETURN" -> break + "ESCAPE" -> return closeTextInput(null, "escape") + "BACKSPACE" -> { + if (isNotEmpty()) deleteAt(lastIndex) + publishTextInput(toString(), limit) + } + else -> { + val char = token.singleOrNull()?.takeIf { value -> !value.isISOControl() } + if (char != null && length < limit) append(char) + publishTextInput(toString(), limit) + } + } } } - } + return closeTextInput(text, "submit") } fun acceptClientMessage(message: String) { @@ -783,14 +786,13 @@ private fun waterMask( world: WorldMap, point: GridPoint, content: CompiledContentBundle, -): Int { - var mask = 0 - if (world.terrainAt(GridPoint(point.x, point.y - 1)).isBitmapWater(content)) mask = mask or WATER_NORTH - if (world.terrainAt(GridPoint(point.x + 1, point.y)).isBitmapWater(content)) mask = mask or WATER_EAST - if (world.terrainAt(GridPoint(point.x, point.y + 1)).isBitmapWater(content)) mask = mask or WATER_SOUTH - if (world.terrainAt(GridPoint(point.x - 1, point.y)).isBitmapWater(content)) mask = mask or WATER_WEST - return mask -} +): Int = + listOf( + WATER_NORTH to GridPoint(point.x, point.y - 1), + WATER_EAST to GridPoint(point.x + 1, point.y), + WATER_SOUTH to GridPoint(point.x, point.y + 1), + WATER_WEST to GridPoint(point.x - 1, point.y), + ).fold(0) { mask, (side, neighbor) -> if (world.terrainAt(neighbor).isBitmapWater(content)) mask or side else mask } private fun CompiledTerrain?.isBitmapWater(content: CompiledContentBundle): Boolean = this @@ -823,12 +825,10 @@ private fun stableVariant( point: GridPoint, code: String, settlement: String?, -): Int { - var hash = point.x * 73_856_093 xor point.y * 19_349_663 - code.forEach { char -> hash = hash * 31 + char.code } - settlement.orEmpty().forEach { char -> hash = hash * 31 + char.code } - return hash.floorMod(4) -} +): Int = + (code + settlement.orEmpty()) + .fold(point.x * 73_856_093 xor point.y * 19_349_663) { hash, char -> hash * 31 + char.code } + .floorMod(4) private fun Int.floorMod(modulus: Int): Int = ((this % modulus) + modulus) % modulus diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt index 6b0742a1..5bed67dd 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt @@ -406,8 +406,7 @@ internal class BattleRunner( var retry = true var attempts = 0 while (retry && attempts < rules.roundLimit && next.monsterHasLivingMembers()) { - val messages = mutableListOf() - next = next.playerAction(index, member, messages) + val messages = buildList { next = next.playerAction(index, member, this) } retry = next.actionRetry next = next.copy(actionRetry = false) screen.updateStatus(next.runtime) @@ -604,13 +603,15 @@ internal class BattleRunner( var next = copy(partyHeld = false, partyConfused = false, actionRetry = false) monsterHp.forEachIndexed { index, hp -> if (hp > 0 && next.partyHasLivingMembers() && !next.monstersHeld) { - val messages = mutableListOf() val cast = next.shouldMonsterCast() next = cast.encounter - next = - when { - cast.value -> next.castMonsterSpell(index) - else -> next.monsterAttack(hp, messages) + val messages = + buildList { + next = + when { + cast.value -> next.castMonsterSpell(index) + else -> next.monsterAttack(hp, this) + } } screen.updateStatus(next.runtime) showBattleMessages(messages) @@ -959,32 +960,31 @@ internal class BattleRunner( private fun PartyState.applyLevelUps(leveling: ExternalLevelingRules?): BattleLevelUps { leveling ?: return BattleLevelUps(this) val growthByClass = leveling.classGrowth.associateBy { growth -> growth.pcClass } - val gains = mutableListOf() - val nextMembers = - members.mapIndexed { index, member -> - val gained = - ((member.level + 1)..leveling.maxLevel).count { targetLevel -> - member.experience >= leveling.xpThresholds.getOrElse(targetLevel) { Int.MAX_VALUE } - } - if (gained == 0) return@mapIndexed member - gains += BattleLevelGain(memberName(content, index), gained) - val growth = growthByClass[member.pcClass] - val nextHealth = member.health + (growth?.health ?: 0) * gained - val nextWisdom = member.wisdom + (growth?.wisdom ?: 0) * gained - val hpFloor = content.evalFormula(leveling.hitPointFloor, this, mapOf("health" to nextHealth)).value - member.copy( - level = (member.level + gained).coerceAtMost(leveling.maxLevel), - weaponSkill = member.weaponSkill + (growth?.weaponSkill ?: 0) * gained, - health = nextHealth, - wisdom = nextWisdom, - // Spell points refill up to wisdom, as in the original, so a wiser caster holds more of them. - mana = member.mana.current of nextWisdom, - charisma = member.charisma + (growth?.charisma ?: 0) * gained, - dexterity = member.dexterity + (growth?.dexterity ?: 0) * gained, - hitPoints = member.hitPoints.current.coerceAtLeast(hpFloor) of nextHealth, - ) - } - return BattleLevelUps(copy(members = nextMembers), gains.toList()) + val (nextMembers, gains) = + members + .mapIndexed { index, member -> + val gained = + ((member.level + 1)..leveling.maxLevel).count { targetLevel -> + member.experience >= leveling.xpThresholds.getOrElse(targetLevel) { Int.MAX_VALUE } + } + if (gained == 0) return@mapIndexed member to null + val growth = growthByClass[member.pcClass] + val nextHealth = member.health + (growth?.health ?: 0) * gained + val nextWisdom = member.wisdom + (growth?.wisdom ?: 0) * gained + val hpFloor = content.evalFormula(leveling.hitPointFloor, this, mapOf("health" to nextHealth)).value + member.copy( + level = (member.level + gained).coerceAtMost(leveling.maxLevel), + weaponSkill = member.weaponSkill + (growth?.weaponSkill ?: 0) * gained, + health = nextHealth, + wisdom = nextWisdom, + // Spell points refill up to wisdom, as in the original, so a wiser caster holds more of them. + mana = member.mana.current of nextWisdom, + charisma = member.charisma + (growth?.charisma ?: 0) * gained, + dexterity = member.dexterity + (growth?.dexterity ?: 0) * gained, + hitPoints = member.hitPoints.current.coerceAtLeast(hpFloor) of nextHealth, + ) to BattleLevelGain(memberName(content, index), gained) + }.unzip() + return BattleLevelUps(copy(members = nextMembers), gains.filterNotNull()) } private fun CompiledPartyMember.weaponDamage(): Int = content.itemRecord(equipment.weapon)?.weaponDamage ?: 1 @@ -1093,17 +1093,9 @@ internal class BattleRunner( .filter { spell -> content.slug(spell.id) != "monster.melee" } private fun spellsByPrefix(prefix: String): List = - buildList { - content.spells.forEach { spell -> - if (content.slug(spell.id).startsWith(prefix)) addBySlot(spell) - } - } - - private fun MutableList.addBySlot(spell: CompiledSpell) { - var index = 0 - while (index < size && this[index].slot <= spell.slot) index++ - add(index, spell) - } + content.spells + .filter { spell -> content.slug(spell.id).startsWith(prefix) } + .sortedBy(CompiledSpell::slot) private fun itemName(item: CompiledHandleRef): String = content.itemRecord(item)?.let { record -> content.strings.value(record.displayNameString) } ?: content.slug(item) diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt index 2756469d..ba038b73 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt @@ -352,7 +352,7 @@ internal class CastleRuntime( ): RuntimeState { val lines = castle.text.giveMenu.renderCastle(screen.textColumns) screen.writeText(lines) - val digits = castle.stairs.items.mapTo(mutableSetOf()) { stair -> stair.digit } + 5 + val digits = (castle.stairs.items.map { stair -> stair.digit } + 5).toSet() val digit = input.readValidDigitChoice(screen, lines, digits, audio = audio) ?: return runtime if (digit == 5) return runtime val item = castle.stairs.items.firstOrNull { stair -> stair.digit == digit } ?: return runtime diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt index e69639a3..ba2c2a5d 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt @@ -376,12 +376,8 @@ private fun List.drawDungeonEvent( val totalWeight = sumOf(CompiledDungeonRandomEvent::weight) if (totalWeight <= 0) return null val draw = party.drawRandom(1, totalWeight) - var running = 0 - val event = - first { random -> - running += random.weight - draw.value <= running - }.event + val cumulativeWeights = map(CompiledDungeonRandomEvent::weight).runningReduce(Int::plus) + val event = this[cumulativeWeights.indexOfFirst { weight -> draw.value <= weight }].event log.rngDraw( context = "dungeon.random_event", lo = 1, diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSecrets.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSecrets.kt index 8aa52495..a1e7d6e4 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSecrets.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSecrets.kt @@ -50,12 +50,13 @@ data class RuntimeSecretAccounts( /** The save-user spellings of an account name, with either `_` or `-` for spaces and punctuation. */ private fun String.accountAliases(): Set { val lowered = trim().lowercase() - return listOf('_', '-').mapTo(mutableSetOf()) { separator -> - lowered - .map { char -> char.takeIf { it.isLetterOrDigit() || it == '-' || it == '_' } ?: separator } - .joinToString("") - .trim('-', '_') - } + return listOf('_', '-') + .map { separator -> + lowered + .map { char -> char.takeIf { it.isLetterOrDigit() || it == '-' || it == '_' } ?: separator } + .joinToString("") + .trim('-', '_') + }.toSet() } /** Runs the secret actions of the roles the active account plays. */ @@ -133,25 +134,27 @@ internal class SecretActions( items: List, ): WildernessActionResult { var party = runtime.party - val notices = mutableListOf() - items.forEach { item -> - val freeSlot = party.inventory.firstOrNull { slot -> slot.item == null }?.slot - val slot = - freeSlot ?: chooseDropSlotForInventoryOverflow( - systems = systems, - input = input, - screen = screen, - party = party, - leadLines = runtimeChromeText("${itemName(item)} does not fit."), - itemName = ::itemName, - ) - log.event("secret.grant_item item=${content.slug(item)} slot=${slot ?: "passed"}") - if (slot != null) { - val carried = party.withInventoryItem(slot, item).leaveExcessFood(content, systems, screen.textColumns) - party = carried.party - notices += carried.notice + val notices = + buildList { + items.forEach { item -> + val freeSlot = party.inventory.firstOrNull { slot -> slot.item == null }?.slot + val slot = + freeSlot ?: chooseDropSlotForInventoryOverflow( + systems = systems, + input = input, + screen = screen, + party = party, + leadLines = runtimeChromeText("${itemName(item)} does not fit."), + itemName = ::itemName, + ) + log.event("secret.grant_item item=${content.slug(item)} slot=${slot ?: "passed"}") + if (slot != null) { + val carried = party.withInventoryItem(slot, item).leaveExcessFood(content, systems, screen.textColumns) + party = carried.party + addAll(carried.notice) + } + } } - } audio.cue(AudioCue.ItemTaken) val next = runtime.withParty(party) screen.updateStatus(next) diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt index 38989d32..5ce76bfb 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt @@ -1087,89 +1087,88 @@ class GameRuntime private constructor( val partyName = input.readText(24)?.normalizedCreationName()?.takeIf(String::isNotBlank) ?: return null log.event("creation.party_name name=$partyName") var runtime = baseRuntime - val members = mutableListOf() - val memberNames = mutableListOf() - while (members.size < rules.start.partyMemberMax) { - val memberNumber = members.size + 1 - if (prerolled) { - val member = rules.prerolledMembers[members.size] - val pcClass = rules.classes.single { it.pcClass == member.pcClass } - val draw = runtime.drawCreationStats(rules.statRoll, memberNumber, log, pcClass) - runtime = draw.runtime - members += runtime.creationMember(memberNumber, member.gender, member.race, member.pcClass, draw.stats) - memberNames += member.name - log.event( - "creation.member_accepted member=$memberNumber gender=${member.gender} race=${member.race} class=${member.pcClass}", - ) - continue - } - screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, null, null, null, null)) - val statsResult = readAcceptedCreationStats(runtime, memberNumber, input, screen, log) ?: return null - runtime = statsResult.runtime - screen.writeText(prompts.memberName.renderCreation(memberNumber = memberNumber, wrapWidth = screen.textColumns)) - val memberName = input.readText(24)?.normalizedCreationName()?.takeIf(String::isNotBlank) ?: return null - log.event("creation.member_name member=$memberNumber name=$memberName") - screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, memberName, null, null, null)) - val gender = - readCreationChoice( - screen, - input, - log, - prompts.gender.renderCreation(memberName = memberName, wrapWidth = screen.textColumns), - creationGenderChoices(prompts), - "gender", - ) - ?: return null - screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, memberName, gender, null, null)) - val race = - readCreationChoice( - screen, - input, - log, - prompts.race.renderCreation(memberName = memberName, wrapWidth = screen.textColumns), - rules.races.mapIndexed { index, option -> - CreationChoice( - index.digitChoiceKey(), - option.label, - option.race, + val (members, memberNames) = + buildList { + while (size < rules.start.partyMemberMax) { + val memberNumber = size + 1 + if (prerolled) { + val member = rules.prerolledMembers[memberNumber - 1] + val pcClass = rules.classes.single { it.pcClass == member.pcClass } + val draw = runtime.drawCreationStats(rules.statRoll, memberNumber, log, pcClass) + runtime = draw.runtime + add(runtime.creationMember(memberNumber, member.gender, member.race, member.pcClass, draw.stats) to member.name) + log.event( + "creation.member_accepted member=$memberNumber gender=${member.gender} race=${member.race} class=${member.pcClass}", ) - }, - "race", - ) - ?: return null - screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, memberName, gender, race, null)) - val pcClass = - readCreationChoice( - screen, - input, - log, - prompts.classMenu.renderCreation(wrapWidth = screen.textColumns), - rules.classes.mapIndexed { index, option -> - CreationChoice( - index.digitChoiceKey(), - option.label, - option, + continue + } + screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, null, null, null, null)) + val statsResult = readAcceptedCreationStats(runtime, memberNumber, input, screen, log) ?: return null + runtime = statsResult.runtime + screen.writeText(prompts.memberName.renderCreation(memberNumber = memberNumber, wrapWidth = screen.textColumns)) + val memberName = input.readText(24)?.normalizedCreationName()?.takeIf(String::isNotBlank) ?: return null + log.event("creation.member_name member=$memberNumber name=$memberName") + screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, memberName, null, null, null)) + val gender = + readCreationChoice( + screen, + input, + log, + prompts.gender.renderCreation(memberName = memberName, wrapWidth = screen.textColumns), + creationGenderChoices(prompts), + "gender", ) - }, - "class", - ) - ?: return null - screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, memberName, gender, race, pcClass.pcClass)) - val failure = pcClass.failureFor(statsResult.stats) - if (failure != null) { - log.event( - "creation.class_rejected member=$memberNumber class=${pcClass.pcClass} required=${pcClass.requiredStat} minimum=${pcClass.minimum}", - ) - audio.cue(AudioCue.InvalidChoice) - screen.writeText(failure.renderCreation(wrapWidth = screen.textColumns)) - input.pause(systems.pacing.characterCreation.classRejectionPauseMs) - } else { - log.event("creation.member_accepted member=$memberNumber gender=$gender race=$race class=${pcClass.pcClass}") - audio.cue(AudioCue.CharacterCreated) - members += runtime.creationMember(memberNumber, gender, race, pcClass.pcClass, statsResult.stats) - memberNames += memberName - } - } + ?: return null + screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, memberName, gender, null, null)) + val race = + readCreationChoice( + screen, + input, + log, + prompts.race.renderCreation(memberName = memberName, wrapWidth = screen.textColumns), + rules.races.mapIndexed { index, option -> + CreationChoice( + index.digitChoiceKey(), + option.label, + option.race, + ) + }, + "race", + ) + ?: return null + screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, memberName, gender, race, null)) + val pcClass = + readCreationChoice( + screen, + input, + log, + prompts.classMenu.renderCreation(wrapWidth = screen.textColumns), + rules.classes.mapIndexed { index, option -> + CreationChoice( + index.digitChoiceKey(), + option.label, + option, + ) + }, + "class", + ) + ?: return null + screen.showCharacterPortrait(rules.creationPortraitPreview(memberNumber, memberName, gender, race, pcClass.pcClass)) + val failure = pcClass.failureFor(statsResult.stats) + if (failure != null) { + log.event( + "creation.class_rejected member=$memberNumber class=${pcClass.pcClass} required=${pcClass.requiredStat} minimum=${pcClass.minimum}", + ) + audio.cue(AudioCue.InvalidChoice) + screen.writeText(failure.renderCreation(wrapWidth = screen.textColumns)) + input.pause(systems.pacing.characterCreation.classRejectionPauseMs) + } else { + log.event("creation.member_accepted member=$memberNumber gender=$gender race=$race class=${pcClass.pcClass}") + audio.cue(AudioCue.CharacterCreated) + add(runtime.creationMember(memberNumber, gender, race, pcClass.pcClass, statsResult.stats) to memberName) + } + } + }.unzip() runtime = runtime.applyCreatedParty(partyName, members, memberNames) log.event( "creation.party_created name=${logValue(partyName)} members=${members.size} " + @@ -1805,7 +1804,6 @@ class GameRuntime private constructor( ): RuntimeState { var current = this var placementParty = current.party.copy(rngState = current.party.rngState ?: 1L) - val placements = current.npcs.toMutableList() content.characters.forEach { character -> if (character.position(current) != null) return@forEach if (character.placement == CompiledCharacterPlacement.Unplaced) { @@ -1826,8 +1824,7 @@ class GameRuntime private constructor( } placementParty = draw.party val position = draw.position - placements += CompiledNpcPlacement(character.id, position) - current = current.copy(npcs = placements.toList()) + current = current.copy(npcs = current.npcs + CompiledNpcPlacement(character.id, position)) log.event( "npc.placement.generated npc=${slug(character.id)} " + "name=${logValue(string(character.nameString))} job=${slug(character.job)} " + @@ -1904,12 +1901,8 @@ class GameRuntime private constructor( val shareTotal = policy.options.sumOf(CompiledRandomNpcPlacementOption::chanceShares) if (shareTotal <= 0) return null val optionDraw = drawRandom(1, shareTotal) - var remaining = optionDraw.value - val option = - policy.options.firstOrNull { candidate -> - remaining -= candidate.chanceShares - remaining <= 0 - } ?: return null + val cumulativeShares = policy.options.map(CompiledRandomNpcPlacementOption::chanceShares).runningReduce(Int::plus) + val option = policy.options.getOrNull(cumulativeShares.indexOfFirst { shares -> shares >= optionDraw.value }) ?: return null return optionDraw.party.drawNpcPlacementOption(option, world, occupiedPositions) } diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/SaveFile.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/SaveFile.kt index d9d205a5..1945e08c 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/SaveFile.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/SaveFile.kt @@ -199,11 +199,11 @@ internal object SaveFile { .heroEntries() .withDerivedHeroes(scoreParties, hallOfHeroesCompletedBy, content) val values = - runtime - .worldSaveValues(bundleHash, content) - .toMutableMap() - values.putHeroEntries(heroes) - values.putUserRecords(userRecords) + buildMap { + putAll(runtime.worldSaveValues(bundleHash, content)) + putHeroEntries(heroes) + putUserRecords(userRecords) + } SaveFileStorage.replace(target, SaveCodec.encodeValues(values)) } @@ -271,8 +271,11 @@ internal object SaveFile { val records = values.userRecords() if (records.isEmpty()) return@update target.delete() val nextRecords = records.filterNot { record -> record.id == userId.normalizedSaveUser() } - val nextValues = values.withoutUserRecords().toMutableMap() - nextValues.putUserRecords(nextRecords) + val nextValues = + buildMap { + putAll(values.withoutUserRecords()) + putUserRecords(nextRecords) + } SaveFileStorage.replace(target, SaveCodec.encodeValues(nextValues)) true } @@ -650,10 +653,11 @@ internal object SaveFile { orEmpty() .takeIf(String::isNotEmpty) ?.split(',') - ?.mapTo(mutableSetOf()) { token -> + ?.map { token -> val parts = token.split(':') GridPoint(parts[0].toInt(), parts[1].toInt()) - }.orEmpty() + }?.toSet() + .orEmpty() private fun Map.readCastleFloorsOpened(base: Map): Map { val raw = get("party.castleFloorsOpened") ?: return base diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/ScriptExecutor.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/ScriptExecutor.kt index 9b6a77cc..1e918d19 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/ScriptExecutor.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/ScriptExecutor.kt @@ -128,9 +128,7 @@ internal class ScriptExecutor( program: CompiledScriptProgram, frames: List, ): ScriptSignal { - var pending = frames - while (pending.isNotEmpty()) { - val frame = pending.first() + frames.forEachIndexed { index, frame -> val signal = executeBlock( instructions = program.blockAt(frame.blockPath), @@ -138,13 +136,12 @@ internal class ScriptExecutor( ScriptBlockContext( program = program, blockPath = frame.blockPath, - parentFrames = pending.drop(1), + parentFrames = frames.drop(index + 1), insideLoop = frame.insideLoop, ), startIndex = frame.nextIndex, ) if (signal != ScriptSignal.Continue) return signal - pending = pending.drop(1) } return ScriptSignal.Continue } @@ -924,12 +921,9 @@ internal class ScriptExecutor( } private fun applyReward(reward: CompiledScriptReward): PartyState { - var party = reward.gold?.let { runtime.party.withGold(runtime.party.resources.gold + int(it)) } ?: runtime.party - if (party.resources.gold > runtime.party.resources.gold) audio.cue(AudioCue.GoldGained) - reward.items.forEach { item -> - party = applyItemReward(party, item, reward) - } - return party + val withGold = reward.gold?.let { runtime.party.withGold(runtime.party.resources.gold + int(it)) } ?: runtime.party + if (withGold.resources.gold > runtime.party.resources.gold) audio.cue(AudioCue.GoldGained) + return reward.items.fold(withGold) { party, item -> applyItemReward(party, item, reward) } } private fun applyItemReward( diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/ShopService.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/ShopService.kt index 797ef614..7654a3a5 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/ShopService.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/ShopService.kt @@ -415,7 +415,11 @@ internal class ShopService( input.readValidInventorySlotChoice( screen = screen, lines = promptLines, - validSlots = party.inventory.filter { slot -> slot.item != null }.mapTo(mutableSetOf(), CompiledInventorySlot::slot), + validSlots = + party.inventory + .filter { slot -> slot.item != null } + .map(CompiledInventorySlot::slot) + .toSet(), cancelKeys = setOf('\n'), ) ?: return runtime val item = party.inventoryItem(slot) @@ -527,8 +531,7 @@ internal class ShopService( price: Int, party: PartyState, ): SellQuote { - var current = price - val haggle = sell.haggle ?: return SellQuote(current, party) + val haggle = sell.haggle ?: return SellQuote(price, party) val draw = party.drawRandom(0, 99) // The party's best talker haggles: the roll bonus sees the highest living charisma. val bonusResult = @@ -550,25 +553,24 @@ internal class ShopService( hi = 99, value = draw.value, hit = false, - details = mapOf("bonus" to bonus, "threshold" to threshold, "item" to content.slug(item), "price" to current), + details = mapOf("bonus" to bonus, "threshold" to threshold, "item" to content.slug(item), "price" to price), ) return SellQuote(price = null, party = afterRoll) } } - haggle.bonuses.forEach { priceBonus -> - if (roll > priceBonus.rollGreaterThan) { - current += current / max(1, priceBonus.addCurrentDivisor) - } - } + val haggled = + haggle.bonuses + .filter { priceBonus -> roll > priceBonus.rollGreaterThan } + .fold(price) { current, priceBonus -> current + current / max(1, priceBonus.addCurrentDivisor) } log.rngDraw( context = "shop.sell.haggle", lo = 0, hi = 99, value = draw.value, hit = true, - details = mapOf("bonus" to bonus, "item" to content.slug(item), "price" to current), + details = mapOf("bonus" to bonus, "item" to content.slug(item), "price" to haggled), ) - return SellQuote(current, afterRoll) + return SellQuote(haggled, afterRoll) } private fun rumorLines(runtime: RuntimeState): RumorResult { diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt index 11ebb663..df605853 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt @@ -300,7 +300,7 @@ internal class UtilityActions( input.readValidInventorySlotChoice( screen = screen, lines = lines, - validSlots = choices.mapTo(mutableSetOf(), CompiledInventorySlot::slot), + validSlots = choices.map(CompiledInventorySlot::slot).toSet(), cancelKeys = inventoryCancelKeys, audio = audio, ) @@ -405,7 +405,7 @@ internal class UtilityActions( .readValidDigitChoice( screen = screen, lines = lines, - validDigits = indexes.mapTo(mutableSetOf()) { index -> index + 1 }, + validDigits = indexes.map { index -> index + 1 }.toSet(), cancelKeys = inventoryCancelKeys, audio = audio, )?.minus(1) @@ -547,7 +547,11 @@ internal fun chooseDropSlotForInventoryOverflow( return input.readValidInventorySlotChoice( screen = screen, lines = slotLines, - validSlots = party.inventory.filter { slot -> slot.item != null }.mapTo(mutableSetOf(), CompiledInventorySlot::slot), + validSlots = + party.inventory + .filter { slot -> slot.item != null } + .map(CompiledInventorySlot::slot) + .toSet(), cancelKeys = inventoryCancelKeys, ) } diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt index 7fd1d49d..ffbd4760 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt @@ -72,28 +72,26 @@ internal class WildernessActions( runtime: RuntimeState, leadingMessages: List = emptyList(), ): WildernessActionResult { - var party = runtime.party - val upkeepMessages = mutableListOf() - party = party.regenerateMana(realm.upkeep.manaRegenChance) + val regenerated = runtime.party.regenerateMana(realm.upkeep.manaRegenChance) - val foodTick = realm.upkeep.foodTickEvery > 0 && party.resources.timeLeft % realm.upkeep.foodTickEvery == 0 - val foodAfterTick = if (foodTick) (party.resources.food - party.foodTickCost()).coerceAtLeast(0) else party.resources.food - party = - party.applyStarvation( + val foodTick = realm.upkeep.foodTickEvery > 0 && regenerated.resources.timeLeft % realm.upkeep.foodTickEvery == 0 + val foodAfterTick = + if (foodTick) (regenerated.resources.food - regenerated.foodTickCost()).coerceAtLeast(0) else regenerated.resources.food + val starvation = + regenerated.applyStarvation( foodAfterTick, realm.upkeep.starveFoodThreshold, realm.upkeep.starveDamage, realm.upkeep.starvationDeath, - upkeepMessages, ) if (foodTick && foodAfterTick <= realm.upkeep.starveFoodThreshold && realm.upkeep.starveDamage > 0) audio.cue(AudioCue.Hunger) - val restedHours = party.resources.restedHours - realm.upkeep.restedHoursCostPerTurn - party = party.applyFatigue(restedHours, realm.upkeep.fatigue, upkeepMessages) - party = - party.copy( + val restedHours = starvation.party.resources.restedHours - realm.upkeep.restedHoursCostPerTurn + val fatigue = starvation.party.applyFatigue(restedHours, realm.upkeep.fatigue) + val party = + fatigue.party.copy( resources = - party.resources.copy( + fatigue.party.resources.copy( food = foodAfterTick, restedHours = restedHours, ), @@ -108,7 +106,7 @@ internal class WildernessActions( currentMode = mode, party = party, ), - messages = leadingMessages + upkeepMessages, + messages = leadingMessages + starvation.messages + fatigue.messages, ) } @@ -181,9 +179,9 @@ internal class WildernessActions( runtime: RuntimeState, move: MoveEvent, ): WildernessActionResult { - var current = runtime - val messages = mutableListOf() - current = current.applyTerrainTransition(move, messages) + val transition = runtime.applyTerrainTransition(move) + var current = transition.runtime + val messages = transition.messages val mission = current.pollMission(move.toTerrain) if (mission.mission != null) { @@ -608,14 +606,12 @@ internal class WildernessActions( return CampMutation(battle.runtime, triggered = true) } - private fun RuntimeState.applyTerrainTransition( - move: MoveEvent, - messages: MutableList, - ): RuntimeState { + private fun RuntimeState.applyTerrainTransition(move: MoveEvent): WildernessActionResult { val from = move.fromTerrain?.let { terrain -> content.slug(terrain.id) } val to = move.toTerrain?.let { terrain -> content.slug(terrain.id) } - if (from == null || to == null || from == to) return this - val transition = wilderness.terrainTransitions.entries.firstOrNull { entry -> entry.terrain == to } ?: return this + if (from == null || to == null || from == to) return WildernessActionResult(this) + val transition = + wilderness.terrainTransitions.entries.firstOrNull { entry -> entry.terrain == to } ?: return WildernessActionResult(this) val draw = party.drawRandom(0, 99) log.rngDraw( context = "wilderness.terrain_transition", @@ -630,10 +626,8 @@ internal class WildernessActions( "threshold_lt" to wilderness.terrainTransitions.chancePercent, ), ) - if (draw.value < wilderness.terrainTransitions.chancePercent) { - messages += transition.text.renderText() - } - return withParty(draw.party) + val messages = if (draw.value < wilderness.terrainTransitions.chancePercent) transition.text.renderText() else emptyList() + return WildernessActionResult(withParty(draw.party), messages) } private fun PartyState.regenerateMana(chancePercent: Int): PartyState { @@ -673,39 +667,39 @@ internal class WildernessActions( threshold: Int, damage: Int, deathText: ExternalRuntimeTextBlock, - messages: MutableList, - ): PartyState { - if (foodAfterTick > threshold || damage == 0) return this - return copy( - members = - members.mapIndexed { index, member -> - if (member.dead) return@mapIndexed member + ): PartyUpkeep { + if (foodAfterTick > threshold || damage == 0) return PartyUpkeep(this) + val (starved, deaths) = + members + .mapIndexed { index, member -> + if (member.dead) return@mapIndexed member to emptyList() val nextHp = member.hitPoints.current - damage - if (nextHp >= 1) return@mapIndexed member.copy(hitPoints = member.hitPoints.copy(current = nextHp)) - messages += deathText.renderUpkeep(memberName(content, index)) + if (nextHp >= 1) return@mapIndexed member.copy(hitPoints = member.hitPoints.copy(current = nextHp)) to emptyList() member.copy( hitPoints = member.hitPoints.copy(current = 0), dead = true, - ) - }, - ) + ) to deathText.renderUpkeep(memberName(content, index)) + }.unzip() + return PartyUpkeep(copy(members = starved), deaths.flatten()) } private fun PartyState.applyFatigue( restedHours: Int, rules: List, - messages: MutableList, - ): PartyState { - val rule = rules.firstOrNull { rule -> rule.matches(restedHours) } ?: return this - messages += rule.text.renderText() + ): PartyUpkeep { + val rule = rules.firstOrNull { rule -> rule.matches(restedHours) } ?: return PartyUpkeep(this) + val messages = rule.text.renderText() if (rule.startsAt(restedHours)) audio.cue(AudioCue.Fatigue) - if (!rule.drain) return this - return copy( - members = - members.map { member -> - member.takeUnless { it.hitPoints.current > 1 } - ?: member.copy(hitPoints = member.hitPoints.copy(current = member.hitPoints.current - 1)) - }, + if (!rule.drain) return PartyUpkeep(this, messages) + return PartyUpkeep( + copy( + members = + members.map { member -> + member.takeUnless { it.hitPoints.current > 1 } + ?: member.copy(hitPoints = member.hitPoints.copy(current = member.hitPoints.current - 1)) + }, + ), + messages, ) } @@ -876,6 +870,11 @@ private data class CampMutation( val triggered: Boolean = false, ) +private data class PartyUpkeep( + val party: PartyState, + val messages: List = emptyList(), +) + /** Movement context used for direct runtime wilderness event polling. */ internal data class MoveEvent( val from: GridPoint, diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotCreation.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotCreation.kt index 01a5a0e8..4684269d 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotCreation.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotCreation.kt @@ -37,11 +37,14 @@ internal class AutopilotCreation( private var started = false private var member = 0 + private val rollCounts = sortedMapOf() + private val acceptedStats = sortedMapOf>() + /** Every stat roll seen, per member number, accepted or not. */ - val rolls: MutableMap = sortedMapOf() + val rolls: Map get() = rollCounts /** The stats each member was created with, per member number. */ - val accepted: MutableMap> = sortedMapOf() + val accepted: Map> get() = acceptedStats /** The key for a title or creation screen, or `null` when [view] shows neither. */ fun key(view: AutopilotView): Char? { @@ -82,7 +85,7 @@ internal class AutopilotCreation( ?.get(1) ?.toInt() } - rolls.merge(member, 1, Int::plus) + rollCounts.merge(member, 1, Int::plus) val stats = lines .mapNotNull { line -> statPattern.find(line.trim()) } @@ -91,7 +94,7 @@ internal class AutopilotCreation( match.groupValues[2].toInt() } val good = recruit().minimums.all { (stat, minimum) -> (stats[stat] ?: 0) >= minimum } - if (good) accepted[member] = stats + if (good) acceptedStats[member] = stats return if (good) 'N' else 'Y' } diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotFullGame.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotFullGame.kt index edeea45d..8447d757 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotFullGame.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotFullGame.kt @@ -175,12 +175,14 @@ internal class AutopilotFullGamePlan( lastFloor: Boolean, ): Boolean { val reasons = if (lastFloor) blockers(state, castleStep) else listOf("weakened").takeIf { weakened(state) }.orEmpty() - reasons.forEach { reason -> castleRetreatReasons.merge(reason, 1, Int::plus) } + reasons.forEach { reason -> retreatReasons.merge(reason, 1, Int::plus) } return reasons.isEmpty() } + private val retreatReasons = sortedMapOf() + /** Why the party has left the castle to recover, such as "mana", counted per reason. */ - val castleRetreatReasons: MutableMap = sortedMapOf() + val castleRetreatReasons: Map get() = retreatReasons /** Between castle fights the priest heals and revives, and potions top the party up. */ override fun castle(state: RuntimeState): AutopilotAction? = upkeep(state) ?: quaff(state) ?: quaffMana(state) @@ -563,26 +565,26 @@ internal class AutopilotFullGamePlan( budget: Int, ): List { var gold = budget - val bought = mutableListOf() val inventoryFree = party.freeSlots(p) - 1 - AutopilotGear.entries.forEach { gear -> - val offers = if (gear == AutopilotGear.Weapon) shops.weapons else shops.armor - party - .living(p) - .sortedBy { member -> strength(member.member, gear) } - .forEach { member -> - if (bought.size >= inventoryFree) return@forEach - val best = - offers - .filter { offer -> offer.price <= gold && strength(offer.item, gear) > strength(member.member, gear) } - .filter { offer -> offer.item.equippableBy.isEmpty() || member.member.pcClass in offer.item.equippableBy } - .maxByOrNull { offer -> strength(offer.item, gear) } - ?: return@forEach - bought += AutopilotErrand.BuyGear(gear, best.label) - gold -= best.price - } + return buildList { + AutopilotGear.entries.forEach { gear -> + val offers = if (gear == AutopilotGear.Weapon) shops.weapons else shops.armor + party + .living(p) + .sortedBy { member -> strength(member.member, gear) } + .forEach { member -> + if (size >= inventoryFree) return@forEach + val best = + offers + .filter { offer -> offer.price <= gold && strength(offer.item, gear) > strength(member.member, gear) } + .filter { offer -> offer.item.equippableBy.isEmpty() || member.member.pcClass in offer.item.equippableBy } + .maxByOrNull { offer -> strength(offer.item, gear) } + ?: return@forEach + add(AutopilotErrand.BuyGear(gear, best.label)) + gold -= best.price + } + } } - return bought } /** Heads for a town when the party needs healing, food, torches, an item for the next step, or better gear. */ diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/PrerolledPartyTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/PrerolledPartyTest.kt index 336b2558..7641c154 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/PrerolledPartyTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/PrerolledPartyTest.kt @@ -28,52 +28,57 @@ class PrerolledPartyTest { @Test fun generatedPartiesMeetClassRequirementsAndKeepTheirRollsOnReload() = withSaveFile { file -> - val rolls = mutableSetOf>() - repeat(16) { seed -> - val user = "player-$seed" - val output = runSession(file, user, "x N 2 \"Dawnward $seed\"", seed.toLong()) - assertContains(output, "(1) Roll your own") - assertContains(output, "(2) Pre-rolled") - assertFalse("Reroll (y/N)" in output) - - val runtime = read(file, user) - val party = runtime.party - assertEquals("Dawnward $seed", party.name) - assertEquals(listOf("Ronan", "Brynja", "Elowen", "Walter"), party.memberNames) - assertEquals(listOf(Gender.Male, Gender.Female, Gender.Female, Gender.Male), party.members.map { it.gender }) - assertEquals(listOf(Race.Human, Race.Dwarf, Race.Elf, Race.Human), party.members.map { it.race }) - assertEquals(listOf(PcClass.Fighter, PcClass.Ranger, PcClass.Mage, PcClass.Priest), party.members.map { it.pcClass }) - assertTrue(party.members[0].weaponSkill >= 50) - assertTrue(party.members[2].wisdom >= 50) - assertTrue(party.members[3].wisdom >= 50) - party.members.forEach { member -> - val stats = listOf(member.weaponSkill, member.wisdom, member.health, member.charisma, member.dexterity) - assertTrue(stats.all { it in 15..70 }, "all generated stats must use the normal starting range") - rolls += stats - assertEquals(1, member.level) - assertEquals(0, member.experience) - assertFalse(member.dead) - assertEquals(member.health, member.hitPoints.current) - assertEquals(member.health, member.hitPoints.max) - val expectedMana = if (member.pcClass in setOf(PcClass.Mage, PcClass.Priest)) member.wisdom else 0 - assertEquals(expectedMana, member.mana.current) - assertEquals(member.wisdom, member.mana.max) - assertEquals("blank", bundle.content.slug(member.equipment.weapon)) - assertEquals("blank", bundle.content.slug(member.equipment.armor)) + val rolls = + buildSet { + repeat(16) { seed -> + val user = "player-$seed" + val output = runSession(file, user, "x N 2 \"Dawnward $seed\"", seed.toLong()) + assertContains(output, "(1) Roll your own") + assertContains(output, "(2) Pre-rolled") + assertFalse("Reroll (y/N)" in output) + + val runtime = read(file, user) + val party = runtime.party + assertEquals("Dawnward $seed", party.name) + assertEquals(listOf("Ronan", "Brynja", "Elowen", "Walter"), party.memberNames) + assertEquals(listOf(Gender.Male, Gender.Female, Gender.Female, Gender.Male), party.members.map { it.gender }) + assertEquals(listOf(Race.Human, Race.Dwarf, Race.Elf, Race.Human), party.members.map { it.race }) + assertEquals( + listOf(PcClass.Fighter, PcClass.Ranger, PcClass.Mage, PcClass.Priest), + party.members.map { it.pcClass }, + ) + assertTrue(party.members[0].weaponSkill >= 50) + assertTrue(party.members[2].wisdom >= 50) + assertTrue(party.members[3].wisdom >= 50) + party.members.forEach { member -> + val stats = listOf(member.weaponSkill, member.wisdom, member.health, member.charisma, member.dexterity) + assertTrue(stats.all { it in 15..70 }, "all generated stats must use the normal starting range") + add(stats) + assertEquals(1, member.level) + assertEquals(0, member.experience) + assertFalse(member.dead) + assertEquals(member.health, member.hitPoints.current) + assertEquals(member.health, member.hitPoints.max) + val expectedMana = if (member.pcClass in setOf(PcClass.Mage, PcClass.Priest)) member.wisdom else 0 + assertEquals(expectedMana, member.mana.current) + assertEquals(member.wisdom, member.mana.max) + assertEquals("blank", bundle.content.slug(member.equipment.weapon)) + assertEquals("blank", bundle.content.slug(member.equipment.armor)) + } + assertEquals(GridPoint(12, 9), party.position) + assertEquals(2_000, party.resources.gold) + assertEquals(5, party.resources.torches) + assertEquals(100, party.resources.food) + assertTrue(party.inventory.all { it.item == null }) + assertTrue(party.journal.isEmpty()) + assertTrue(party.milestones.isEmpty()) + assertEquals(0, party.counters.kills) + + val resumed = runSession(file, user, "x L") + assertContains(resumed, "Wilderness") + assertEquals(party, read(file, user).party, "continuing must keep the saved names, stats, and resources") + } } - assertEquals(GridPoint(12, 9), party.position) - assertEquals(2_000, party.resources.gold) - assertEquals(5, party.resources.torches) - assertEquals(100, party.resources.food) - assertTrue(party.inventory.all { it.item == null }) - assertTrue(party.journal.isEmpty()) - assertTrue(party.milestones.isEmpty()) - assertEquals(0, party.counters.kills) - - val resumed = runSession(file, user, "x L") - assertContains(resumed, "Wilderness") - assertEquals(party, read(file, user).party, "continuing must keep the saved names, stats, and resources") - } assertTrue(rolls.size > 16, "the generator should draw fresh stats rather than reuse a fixed test party") assertEquals("16", SaveCodec.decodeValues(file.readLines())["users.count"]) assertEquals("Dawnward 0", read(file, "player-0").party.name) @@ -84,8 +89,14 @@ class PrerolledPartyTest { withSaveFile { file -> val systems = bundleFile.readExternalRuntimeSystems() val rules = checkNotNull(systems.characterCreation) - val members = rules.prerolledMembers.reversed().toMutableList() - members[0] = members[0].copy(name = "Fenn", gender = Gender.Female, race = Race.Halfling, pcClass = PcClass.Thief) + val members = + rules.prerolledMembers.reversed().mapIndexed { index, member -> + if (index == 0) { + member.copy(name = "Fenn", gender = Gender.Female, race = Race.Halfling, pcClass = PcClass.Thief) + } else { + member + } + } val configuredSystems = systems.copy( characterCreation = diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/ReplayPlan.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/ReplayPlan.kt index 5549f507..61148eb5 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/ReplayPlan.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/ReplayPlan.kt @@ -849,16 +849,12 @@ private class ReplayWorldMap( private fun commandsTo( end: GridPoint, previous: Map?>, - ): String { - val commands = ArrayDeque() - var cursor = end - while (true) { - val step = previous[cursor] ?: break - commands.addFirst(step.second) - cursor = step.first - } - return commands.joinToString(separator = "") - } + ): String = + generateSequence(previous[end]) { (from, _) -> previous[from] } + .map { (_, command) -> command } + .toList() + .reversed() + .joinToString(separator = "") private fun GridPoint.neighbors(): List = listOf( diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeSessionFactoryTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeSessionFactoryTest.kt index 706fb633..b498f590 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeSessionFactoryTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/RuntimeSessionFactoryTest.kt @@ -501,7 +501,7 @@ private data class SaveNpcPlacement( private fun rylween.compiled.CompiledContentBundle.townServiceSlugs(): Map> = towns.associate { town -> - slug(town.id) to town.services.mapTo(mutableSetOf(), ::slug) + slug(town.id) to town.services.map(::slug).toSet() } private class RecordingAnsiTerminal : AnsiTerminal { diff --git a/support/terminal/src/main/kotlin/rylween/terminal/AnsiInput.kt b/support/terminal/src/main/kotlin/rylween/terminal/AnsiInput.kt index 206431a5..d5e7cc96 100644 --- a/support/terminal/src/main/kotlin/rylween/terminal/AnsiInput.kt +++ b/support/terminal/src/main/kotlin/rylween/terminal/AnsiInput.kt @@ -28,33 +28,33 @@ object AnsiInput { consumeQueuedLf: () -> Unit, writeRaw: (String) -> Unit, flush: () -> Unit, - ): String? { - val out = StringBuilder() - while (true) { - when (val ch = readCode(null)) { - -1, - '\u0003'.code, - '\u0004'.code, - -> return null - '\n'.code, - '\r'.code, - -> { - consumeQueuedLf() - return out.toString() - } - '\b'.code, - '\u007F'.code, - -> { - if (out.isNotEmpty()) { - out.deleteCharAt(out.lastIndex) - writeRaw("\b \b") - flush() + ): String? = + buildString { + while (true) { + when (val ch = readCode(null)) { + -1, + '\u0003'.code, + '\u0004'.code, + -> return null + '\n'.code, + '\r'.code, + -> { + consumeQueuedLf() + break } + '\b'.code, + '\u007F'.code, + -> { + if (isNotEmpty()) { + deleteCharAt(lastIndex) + writeRaw("\b \b") + flush() + } + } + else -> appendPrintable(maxLength, this, ch, writeRaw, flush) } - else -> appendPrintable(maxLength, out, ch, writeRaw, flush) } } - } private fun decodeEscapeKey(readCode: (timeoutMs: Int?) -> Int): String { val b1 = readCode(50) diff --git a/support/tools/src/main/kotlin/rylween/tools/CompiledBundleArtifactMain.kt b/support/tools/src/main/kotlin/rylween/tools/CompiledBundleArtifactMain.kt index 0147ccdf..02709eec 100644 --- a/support/tools/src/main/kotlin/rylween/tools/CompiledBundleArtifactMain.kt +++ b/support/tools/src/main/kotlin/rylween/tools/CompiledBundleArtifactMain.kt @@ -120,27 +120,29 @@ private data class ParsedToolArgs( ) private fun parseToolArgs(args: Array): ParsedToolArgs { - val positionals = mutableListOf() var logFile = System.getenv("RYLWEEN_TOOL_LOG")?.takeIf { value -> value.isNotBlank() }?.let(::File) var index = 0 - while (index < args.size) { - val arg = args[index] - when (arg) { - "--log" -> { - require(index + 1 < args.size) { "--log requires a file path" } - index += 1 - logFile = File(args[index]) - } - else -> { - if (arg.startsWith("--log=")) { - logFile = File(arg.substringAfter("--log=")) - } else { - positionals += arg + val positionals = + buildList { + while (index < args.size) { + val arg = args[index] + when (arg) { + "--log" -> { + require(index + 1 < args.size) { "--log requires a file path" } + index += 1 + logFile = File(args[index]) + } + else -> { + if (arg.startsWith("--log=")) { + logFile = File(arg.substringAfter("--log=")) + } else { + add(arg) + } + } } + index += 1 } } - index += 1 - } return ParsedToolArgs(positionals, logFile) } diff --git a/support/web-common/src/main/kotlin/rylween/webcommon/WebHttp.kt b/support/web-common/src/main/kotlin/rylween/webcommon/WebHttp.kt index 48c1ddca..52a2bb14 100644 --- a/support/web-common/src/main/kotlin/rylween/webcommon/WebHttp.kt +++ b/support/web-common/src/main/kotlin/rylween/webcommon/WebHttp.kt @@ -46,16 +46,18 @@ fun readHttpRequest( if (requestLine.isBlank()) return null val parts = requestLine.split(" ", limit = 3) if (parts.size < 2) return null - val headers = linkedMapOf() - while (true) { - val line = readHttpLine(input, maxLineBytes) ?: return null - if (line.isEmpty()) break - val separator = line.indexOf(':') - if (separator < 1) continue - val name = line.substring(0, separator).trim().lowercase(Locale.ROOT) - val value = line.substring(separator + 1).trim() - headers[name] = value - } + val headers = + buildMap { + while (true) { + val line = readHttpLine(input, maxLineBytes) ?: return null + if (line.isEmpty()) break + val separator = line.indexOf(':') + if (separator < 1) continue + val name = line.substring(0, separator).trim().lowercase(Locale.ROOT) + val value = line.substring(separator + 1).trim() + put(name, value) + } + } val contentLength = headers["content-length"]?.toIntOrNull()?.coerceAtLeast(0) ?: 0 check(contentLength <= maxBodyBytes) { "HTTP request body too large: $contentLength" } val body = ByteArray(contentLength) @@ -148,16 +150,14 @@ private fun parseKeyValue( decode: (String) -> String, ): Map { if (raw.isBlank()) return emptyMap() - val values = linkedMapOf() - raw.split('&').forEach { part -> + return raw.split('&').associate { part -> val separator = part.indexOf('=') if (separator < 0) { - values[decode(part)] = "" - return@forEach + decode(part) to "" + } else { + decode(part.substring(0, separator)) to decode(part.substring(separator + 1)) } - values[decode(part.substring(0, separator))] = decode(part.substring(separator + 1)) } - return values } private fun String.parseCookieHeader(): Map = diff --git a/support/web-common/src/main/kotlin/rylween/webcommon/auth/WebAuth.kt b/support/web-common/src/main/kotlin/rylween/webcommon/auth/WebAuth.kt index 23bcaafa..b4096b90 100644 --- a/support/web-common/src/main/kotlin/rylween/webcommon/auth/WebAuth.kt +++ b/support/web-common/src/main/kotlin/rylween/webcommon/auth/WebAuth.kt @@ -104,7 +104,7 @@ class WebUserStore( private val dataDir: File, reservedNames: Set = emptySet(), ) { - private val reservedSlugs = reservedNames.mapNotNullTo(mutableSetOf(), ::slugFrom) + private val reservedSlugs = reservedNames.mapNotNull(::slugFrom).toSet() private val lock = ReentrantLock(true) private val usersDir = dataDir.resolve("users/by-slug") private val emailIndexFile = dataDir.resolve("users/email-index.properties") From c898b948a6ca28e1b538f6166a92d03a5595df60 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:17 +0100 Subject: [PATCH 06/16] Author battle, upkeep and tax rules as formulas 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. --- .../kotlin/rylween/compiled/CompiledBundle.kt | 8 +- .../compiled/ExternalBundleArtifact.kt | 83 +++++------ core/src/main/kotlin/rylween/dsl/Dsl.kt | 31 +++- .../main/kotlin/rylween/dsl/DslValidation.kt | 55 +++---- .../main/kotlin/rylween/dsl/ExpressionDsl.kt | 19 +++ .../main/kotlin/rylween/dsl/ItemRealmDsl.kt | 5 +- .../main/kotlin/rylween/dsl/impl/CombatDsl.kt | 61 ++++---- .../rylween/dsl/impl/ContentModelsDsl.kt | 3 +- .../rylween/dsl/impl/WorldContentDsl.kt | 3 +- .../main/kotlin/rylween/game/RylweenGame.kt | 74 +++++++--- .../rylween/RylweenCompiledGameLedgerTest.kt | 10 +- .../kotlin/rylween/runtime/BattleRunner.kt | 56 +++++--- .../rylween/runtime/RuntimePresentation.kt | 9 -- .../rylween/runtime/RylweenRuntimeMain.kt | 19 +-- .../rylween/runtime/WildernessActions.kt | 10 +- .../kotlin/rylween/runtime/AutopilotBattle.kt | 135 ++++++++++++++++-- 16 files changed, 389 insertions(+), 192 deletions(-) diff --git a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt index 25c50a16..3f558157 100644 --- a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt +++ b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt @@ -134,6 +134,8 @@ import rylween.runtime.RuntimeSnapshotModel import rylween.runtime.ScriptContinuationSnapshot import rylween.runtime.ScriptRootRef import rylween.runtime.scriptRootCatalog +import kotlin.math.max +import kotlin.math.min /** * Complete compiled J1 bundle: content tables plus save/start state images. @@ -999,7 +1001,7 @@ sealed interface CompiledIntExpr { } /** Arithmetic operator for [CompiledIntExpr.Binary]. */ -enum class CompiledBinaryOp { Add, Sub, Mul, Div, Mod } +enum class CompiledBinaryOp { Add, Sub, Mul, Div, Mod, Max, Min } /** Applies a compiled integer binary operator using runtime-compatible divide-by-zero semantics. */ fun Int.applyCompiledBinary( @@ -1012,6 +1014,8 @@ fun Int.applyCompiledBinary( CompiledBinaryOp.Mul -> this * right CompiledBinaryOp.Div -> this / (right.takeUnless { value -> value == 0 } ?: 1) CompiledBinaryOp.Mod -> this % (right.takeUnless { value -> value == 0 } ?: 1) + CompiledBinaryOp.Max -> max(this, right) + CompiledBinaryOp.Min -> min(this, right) } /** Compiled boolean expression tree evaluated by scripts and runtime conditions. */ @@ -2105,6 +2109,8 @@ private class CompiledBundleCompiler( "*", "mul" -> CompiledBinaryOp.Mul "/", "div" -> CompiledBinaryOp.Div "%", "mod" -> CompiledBinaryOp.Mod + "max" -> CompiledBinaryOp.Max + "min" -> CompiledBinaryOp.Min else -> error("unknown int operator '$op'") } diff --git a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index 5150b396..3df11b24 100644 --- a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt +++ b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt @@ -435,13 +435,16 @@ data class ExternalTownPrompts( /** Town-system runtime rows consumed by direct runtimes. */ data class ExternalRuntimeTown( val entryTax: ExternalTownEntryTax?, + /** The street view shown with the town menu and the entry tax. */ + val image: String? = null, /** Equipment questions asked, in order, when the party leaves town. */ val leavePrompts: List = emptyList(), ) /** Town-entry tax gate exported from authored town-system content. */ data class ExternalTownEntryTax( - val minimumLeaderLevel: Int, + /** Slug of the formula for the gold the party pays to enter, or null when towns charge nothing. */ + val amount: String?, val pay: ExternalRuntimeInputBinding, val leave: ExternalRuntimeInputBinding, ) @@ -707,6 +710,8 @@ data class ExternalStandardBattle( val encounterFoeCountMax: Int, val encounterHitPointMinFormula: String, val encounterHitPointMaxFormula: String, + val encounterFoeCountMaxFormula: String, + val encounterWeaponSkillFormula: String, val victoryImage: String?, val defeatImage: String?, val nativeServices: List, @@ -742,16 +747,15 @@ data class ExternalPlayerRoundRules( val battleCry: ExternalBattleCryRules, ) -/** Player attack hit and damage tuning. */ +/** Slugs of the formulas for a player attack's hit chance and damage. */ data class ExternalPlayerAttackRules( - val hitBonus: Int, - val damageSpreadMax: Int, - val confusionDivisor: Int, - val hpDefenseDivisor: Int, + val hitChance: String, + val damage: String, ) -/** Defend action tuning. */ +/** Defend action tuning; [healing] is the slug of the formula for the hit points regained. */ data class ExternalDefendRules( + val healing: String, val weaponSkillPenalty: Int, val restThreshold: Int, val cap: Int, @@ -762,19 +766,16 @@ data class ExternalBattleCryRules( val weaponSkillPenalty: Int, ) -/** Monster-side spell and mêlée rules. */ +/** Monster-side spell and mêlée rules; [spellChance] is a formula slug. */ data class ExternalMonsterRoundRules( - val spellChanceBasePercent: Int, - val spellPowerDivisor: Int, + val spellChance: String, val melee: ExternalMonsterMeleeRules, ) -/** Monster mêlée hit and damage tuning. */ +/** Slugs of the formulas for a monster mêlée hit's chance and damage. */ data class ExternalMonsterMeleeRules( - val hitBonus: Int, - val damageDivisor: Int, - val damageSpreadMax: Int, - val damageMin: Int, + val hitChance: String, + val damage: String, val fallback: String, ) @@ -844,7 +845,8 @@ data class ExternalEngineServiceUse( /** Wilderness upkeep balance and fatigue text from the stable runtime-system section. */ data class ExternalWildernessUpkeep( - val foodCostLeaderDiv: Int, + /** Slug of the formula for the food eaten every food tick, or null when the party eats none. */ + val foodCost: String?, val foodTickEvery: Int, val starveFoodThreshold: Int, val starveDamage: Int, @@ -1586,6 +1588,8 @@ private class ExternalBundleArtifactWriter { "encounterFoeCountMax" to JsonNumber(battle.encounterFoeCountMax.toString()), "encounterHitPointMinFormula" to JsonString(battle.encounterHitPointMinFormula.slug), "encounterHitPointMaxFormula" to JsonString(battle.encounterHitPointMaxFormula.slug), + "encounterFoeCountMaxFormula" to JsonString(battle.encounterFoeCountMaxFormula.slug), + "encounterWeaponSkillFormula" to JsonString(battle.encounterWeaponSkillFormula.slug), "victoryImage" to battle.victoryImage?.let { JsonString(it.slug) }.orJsonNull(), "defeatImage" to battle.defeatImage?.let { JsonString(it.slug) }.orJsonNull(), "nativeServices" to nativeServicesJson(battle.nativeServices), @@ -1612,10 +1616,8 @@ private class ExternalBundleArtifactWriter { jsonObject( "attack" to jsonObject( - "hitBonus" to JsonNumber(round.attack.hitBonus.toString()), - "damageSpreadMax" to JsonNumber(round.attack.damageSpreadMax.toString()), - "confusionDivisor" to JsonNumber(round.attack.confusionDivisor.toString()), - "hpDefenseDivisor" to JsonNumber(round.attack.hpDefenseDivisor.toString()), + "hitChance" to JsonString(round.attack.hitChance.slug), + "damage" to JsonString(round.attack.damage.slug), ), "defend" to defendRulesJson(round.defend), "battleCry" to @@ -1626,6 +1628,7 @@ private class ExternalBundleArtifactWriter { private fun defendRulesJson(rules: DefendRulesModel): JsonValue = jsonObject( + "healing" to JsonString(rules.healing.slug), "weaponSkillPenalty" to JsonNumber(rules.weaponSkillPenalty.toString()), "restThreshold" to JsonNumber(rules.restThreshold.toString()), "cap" to JsonNumber(rules.cap.toString()), @@ -1633,17 +1636,14 @@ private class ExternalBundleArtifactWriter { private fun monsterRoundJson(round: MonsterRoundModel): JsonValue = jsonObject( - "spellChanceBasePercent" to JsonNumber(round.spellChanceBasePercent.toString()), - "spellPowerDivisor" to JsonNumber(round.spellPowerDivisor.toString()), + "spellChance" to JsonString(round.spellChance.slug), "melee" to monsterMeleeJson(round.melee), ) private fun monsterMeleeJson(melee: MonsterMeleeRulesModel): JsonValue = jsonObject( - "hitBonus" to JsonNumber(melee.hitBonus.toString()), - "damageDivisor" to JsonNumber(melee.damageDivisor.toString()), - "damageSpreadMax" to JsonNumber(melee.damageSpreadMax.toString()), - "damageMin" to JsonNumber(melee.damageMin.toString()), + "hitChance" to JsonString(melee.hitChance.slug), + "damage" to JsonString(melee.damage.slug), "fallback" to JsonString(melee.fallback.slug), ) @@ -1731,7 +1731,7 @@ private class ExternalBundleArtifactWriter { private fun upkeepJson(upkeep: WildernessUpkeepRules): JsonValue = jsonObject( - "foodCostLeaderDiv" to JsonNumber(upkeep.foodCostLeaderDiv.toString()), + "foodCost" to upkeep.foodCost?.let { formula -> JsonString(formula.slug) }.orJsonNull(), "foodTickEvery" to JsonNumber(upkeep.foodTickEvery.toString()), "starveFoodThreshold" to JsonNumber(upkeep.starveFoodThreshold.toString()), "starveDamage" to JsonNumber(upkeep.starveDamage.toString()), @@ -2292,9 +2292,13 @@ private class ExternalBundleArtifactWriter { ?.let { jsonObject( "leavePrompts" to JsonArray(it.leavePrompts.map { command -> JsonString(command.name) }), + "image" to it.image?.let { image -> JsonString(image.slug) }.orJsonNull(), "entryTax" to jsonObject( - "minimumLeaderLevel" to JsonNumber(it.entryTax.minimumLeaderLevel.toString()), + "amount" to + it.entryTax.amount + ?.let { formula -> JsonString(formula.slug) } + .orJsonNull(), "pay" to bindingJson(it.entryTax.pay), "leave" to bindingJson(it.entryTax.leave), ), @@ -3339,6 +3343,7 @@ private class ExternalRuntimeSystemsReader( ?.takeUnless { it is JsonNull } ?.asObject("town entry tax") ?.readTownEntryTax(), + image = optionalNullableString("image"), leavePrompts = optionalArray("leavePrompts")?.values.orEmpty().map { command -> enumValueOf(command.asString("town leave prompt")) @@ -3347,7 +3352,7 @@ private class ExternalRuntimeSystemsReader( private fun JsonObject.readTownEntryTax(): ExternalTownEntryTax = ExternalTownEntryTax( - minimumLeaderLevel = requiredInt("minimumLeaderLevel"), + amount = optionalNullableString("amount"), pay = requiredObject("pay").readBinding(), leave = requiredObject("leave").readBinding(), ) @@ -3678,6 +3683,8 @@ private class ExternalRuntimeSystemsReader( encounterFoeCountMax = requiredInt("encounterFoeCountMax"), encounterHitPointMinFormula = requiredString("encounterHitPointMinFormula"), encounterHitPointMaxFormula = requiredString("encounterHitPointMaxFormula"), + encounterFoeCountMaxFormula = requiredString("encounterFoeCountMaxFormula"), + encounterWeaponSkillFormula = requiredString("encounterWeaponSkillFormula"), victoryImage = optionalNullableString("victoryImage"), defeatImage = optionalNullableString("defeatImage"), nativeServices = requiredArray("nativeServices").values.map { row -> row.asObject("native service").readNativeService() }, @@ -3705,15 +3712,14 @@ private class ExternalRuntimeSystemsReader( attack = requiredObject("attack").let { attack -> ExternalPlayerAttackRules( - hitBonus = attack.requiredInt("hitBonus"), - damageSpreadMax = attack.requiredInt("damageSpreadMax"), - confusionDivisor = attack.requiredInt("confusionDivisor"), - hpDefenseDivisor = attack.requiredInt("hpDefenseDivisor"), + hitChance = attack.requiredString("hitChance"), + damage = attack.requiredString("damage"), ) }, defend = requiredObject("defend").let { defend -> ExternalDefendRules( + healing = defend.requiredString("healing"), weaponSkillPenalty = defend.requiredInt("weaponSkillPenalty"), restThreshold = defend.requiredInt("restThreshold"), cap = defend.requiredInt("cap"), @@ -3725,15 +3731,12 @@ private class ExternalRuntimeSystemsReader( private fun JsonObject.readMonsterRound(): ExternalMonsterRoundRules = ExternalMonsterRoundRules( - spellChanceBasePercent = requiredInt("spellChanceBasePercent"), - spellPowerDivisor = requiredInt("spellPowerDivisor"), + spellChance = requiredString("spellChance"), melee = requiredObject("melee").let { melee -> ExternalMonsterMeleeRules( - hitBonus = melee.requiredInt("hitBonus"), - damageDivisor = melee.requiredInt("damageDivisor"), - damageSpreadMax = melee.requiredInt("damageSpreadMax"), - damageMin = melee.requiredInt("damageMin"), + hitChance = melee.requiredString("hitChance"), + damage = melee.requiredString("damage"), fallback = melee.requiredString("fallback"), ) }, @@ -3832,7 +3835,7 @@ private class ExternalRuntimeSystemsReader( private fun JsonObject.readUpkeep(): ExternalWildernessUpkeep = ExternalWildernessUpkeep( - foodCostLeaderDiv = requiredInt("foodCostLeaderDiv"), + foodCost = optionalNullableString("foodCost"), foodTickEvery = requiredInt("foodTickEvery"), starveFoodThreshold = requiredInt("starveFoodThreshold"), starveDamage = requiredInt("starveDamage"), diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index a316476d..07ea866b 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -3084,6 +3084,9 @@ class TownSystemBuilder { private var leavePromptCommands: List = emptyList() private var entryTaxModel: TownEntryTaxModel = TownEntryTaxModel() + /** The street view shown with the town menu and the entry tax. */ + var image: ImageId? = null + fun menu(body: TownMenuBuilder.() -> Unit) { menuModel = TownMenuBuilder().apply(body).build() } @@ -3110,6 +3113,7 @@ class TownSystemBuilder { buildingServices = buildingServiceModels, leavePrompts = leavePromptCommands, entryTax = entryTaxModel, + image = image, nativeServices = listOf( EngineServiceUse(EngineService.KeyboardInput, "town menu command selection"), @@ -3127,20 +3131,21 @@ class TownSystemBuilder { /** * Receiver for the town-entry tax interaction. * - * It declares the leader-level threshold and pay/leave bindings used when a - * town charges entry tax. + * It declares the tax formula and the pay/leave bindings used when a town + * charges entry tax. */ @RylNextDsl class TownEntryTaxBuilder( initial: TownEntryTaxModel = TownEntryTaxModel(), ) { - var minimumLeaderLevel: Int = initial.minimumLeaderLevel + /** The gold a party pays to enter a town, as a formula; a town with nothing to charge lets it in. */ + var amount: FormulaId? = initial.amount var pay: InputBindingModel = initial.pay var leave: InputBindingModel = initial.leave fun build(): TownEntryTaxModel = TownEntryTaxModel( - minimumLeaderLevel = minimumLeaderLevel, + amount = amount, pay = pay, leave = leave, ) @@ -3479,6 +3484,24 @@ class FormulaBuilder( // The spell being cast, for the spell cost formula; the caster's stats are bound above. val spellBaseCost: IntExpr = v("spell_base_cost") + // Upkeep and town entry: the party's living members and the gold it + // carries, and the tax rate of the town it enters. + val livingMembers: IntExpr = v("living_members") + val gold: IntExpr = v("gold") + val taxPercent: IntExpr = v("tax_percent") + + // Battle arithmetic, bound by the battle runner: the member who attacks or + // defends, or the one a monster attacks; the attacking monster; and the + // monster an encounter is made of. + val weaponSkill: IntExpr = v("weapon_skill") + val weaponDamage: IntExpr = v("weapon_damage") + val hitPoints: IntExpr = v("hit_points") + val armorClass: IntExpr = v("armor_class") + val partyConfused: BoolExpr = Bool(BoolAst.Cmp(IntAst.Var("party_confused"), "ne", IntAst.Lit(0))) + val monsterHitPoints: IntExpr = v("monster_hit_points") + val monsterCountMax: IntExpr = v("monster_count_max") + val countMaxLevelDivisor: IntExpr = v("count_max_level_divisor") + fun whenValue( condition: BoolExpr, thenValue: IntExpr, diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 8e3e69ee..8f6238a6 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -323,7 +323,7 @@ fun validateFormulas(formulas: List) { check(formulas.map { it.id }.toSet().size == formulas.size) { "duplicate formula" } } -/** Validates that the hunt and castle trap chances and the spell cost name authored formulas. */ +/** Validates that the hunt and castle trap chances, the spell cost and the battle arithmetic name authored formulas. */ private fun validateSystemFormulaReferences(content: GameModel) { val formulaIds = content.formulas.map { it.id }.toSet() content.realm.hunt?.let { hunt -> @@ -334,6 +334,28 @@ private fun validateSystemFormulaReferences(content: GameModel) { content.realm.spellCost?.let { spellCost -> check(spellCost in formulaIds) { "realm spell cost references missing formula ${spellCost.slug}" } } + content.realm.upkeep.foodCost?.let { foodCost -> + check(foodCost in formulaIds) { "realm upkeep food cost references missing formula ${foodCost.slug}" } + } + content.townSystem?.entryTax?.amount?.let { tax -> + check(tax in formulaIds) { "town entry tax references missing formula ${tax.slug}" } + } + content.combat.standardBattle?.let { battle -> + listOf( + "attack hit chance" to battle.playerRound.attack.hitChance, + "attack damage" to battle.playerRound.attack.damage, + "defend healing" to battle.playerRound.defend.healing, + "monster spell chance" to battle.monsterRound.spellChance, + "monster melee hit chance" to battle.monsterRound.melee.hitChance, + "monster melee damage" to battle.monsterRound.melee.damage, + "encounter minimum hit points" to battle.encounterHitPointMinFormula, + "encounter maximum hit points" to battle.encounterHitPointMaxFormula, + "encounter foe count maximum" to battle.encounterFoeCountMaxFormula, + "encounter weapon skill" to battle.encounterWeaponSkillFormula, + ).forEach { (rule, formula) -> + check(formula in formulaIds) { "standard battle $rule references missing formula ${formula.slug}" } + } + } content.castles.forEach { castle -> val disarmChance = checkNotNull(castle.pitfall.disarmChance) { "castle ${castle.id.slug} pitfall needs a disarm chance formula" } @@ -436,18 +458,6 @@ fun validateCombatSystem( } validateBattleText(battle.text) - check(battle.playerRound.attack.hitBonus >= 0) { - "standard battle attack hit bonus must be non-negative" - } - check(battle.playerRound.attack.damageSpreadMax >= 0) { - "standard battle attack damage spread must be non-negative" - } - check(battle.playerRound.attack.confusionDivisor > 0) { - "standard battle attack confusion divisor must be positive" - } - check(battle.playerRound.attack.hpDefenseDivisor > 0) { - "standard battle attack HP defense divisor must be positive" - } check(battle.playerRound.defend.weaponSkillPenalty >= 0) { "standard battle defend weapon-skill penalty must be non-negative" } @@ -461,22 +471,6 @@ fun validateCombatSystem( "standard battle battle-cry weapon-skill penalty must be non-negative" } - checkPercent(battle.monsterRound.spellChanceBasePercent, "standard battle monster spell base chance") - check(battle.monsterRound.spellPowerDivisor > 0) { - "standard battle monster spell-power divisor must be positive" - } - check(battle.monsterRound.melee.hitBonus >= 0) { - "standard battle monster melee hit bonus must be non-negative" - } - check(battle.monsterRound.melee.damageDivisor > 0) { - "standard battle monster melee damage divisor must be positive" - } - check(battle.monsterRound.melee.damageSpreadMax >= 0) { - "standard battle monster melee damage spread must be non-negative" - } - check(battle.monsterRound.melee.damageMin >= 0) { - "standard battle monster melee damage minimum must be non-negative" - } check(battle.roundLimit > 0) { "standard battle round limit must be positive" } check(battle.encounterFoeCountMax > 0) { "standard battle foe count max must be positive" } @@ -999,9 +993,6 @@ fun validateTownSystem( "town leave prompt ${command.name} is not a ready command" } } - check(townSystem.entryTax.minimumLeaderLevel >= 0) { - "town entry tax minimum leader level must be non-negative" - } validateInputChoiceBinding(townSystem.entryTax.pay, "town entry tax pay key") validateInputChoiceBinding(townSystem.entryTax.leave, "town entry tax leave key") checkUniqueBindings(listOf(townSystem.entryTax.pay, townSystem.entryTax.leave), "town entry tax") diff --git a/core/src/main/kotlin/rylween/dsl/ExpressionDsl.kt b/core/src/main/kotlin/rylween/dsl/ExpressionDsl.kt index 0c607de0..62974088 100644 --- a/core/src/main/kotlin/rylween/dsl/ExpressionDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/ExpressionDsl.kt @@ -31,8 +31,27 @@ abstract class IntExpr { operator fun div(other: IntExpr): IntExpr = Expr(IntAst.Binary(ast, "div", other.ast)) operator fun div(other: Int): IntExpr = this / lit(other) + + /** This value, or [other] when this is smaller: `damage atLeast 1`. */ + infix fun atLeast(other: IntExpr): IntExpr = Expr(IntAst.Binary(ast, "max", other.ast)) + + infix fun atLeast(other: Int): IntExpr = this atLeast lit(other) + + /** This value, or [other] when this is larger: `chance atMost 95`. */ + infix fun atMost(other: IntExpr): IntExpr = Expr(IntAst.Binary(ast, "min", other.ast)) + + infix fun atMost(other: Int): IntExpr = this atMost lit(other) } +// A plain number on the left of a value, as in `40 - dexterity * 2 / 5`, needs no lit(). +operator fun Int.plus(other: IntExpr): IntExpr = lit(this) + other + +operator fun Int.minus(other: IntExpr): IntExpr = lit(this) - other + +operator fun Int.times(other: IntExpr): IntExpr = lit(this) * other + +operator fun Int.div(other: IntExpr): IntExpr = lit(this) / other + data class Expr( override val ast: IntAst, ) : IntExpr() diff --git a/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt b/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt index 83da96f8..d32aa562 100644 --- a/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt @@ -203,7 +203,8 @@ class TimeOfDayBandsBuilder { class WildernessUpkeepRulesBuilder( initial: WildernessUpkeepRules = WildernessUpkeepRules(), ) { - var foodCostLeaderDiv: Int = initial.foodCostLeaderDiv + /** The food the party eats every [foodTickEvery] turns, as a formula; without one it eats none. */ + var foodCost: FormulaId? = initial.foodCost var foodTickEvery: Int = initial.foodTickEvery var starveFoodThreshold: Int = initial.starveFoodThreshold var starveDamage: Int = initial.starveDamage @@ -250,7 +251,7 @@ class WildernessUpkeepRulesBuilder( internal fun build(): WildernessUpkeepRules = WildernessUpkeepRules( - foodCostLeaderDiv = foodCostLeaderDiv, + foodCost = foodCost, foodTickEvery = foodTickEvery, starveFoodThreshold = starveFoodThreshold, starveDamage = starveDamage, diff --git a/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt index 622c8e1c..aa9bf551 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt @@ -91,13 +91,12 @@ data class BattleTextModel( ) data class PlayerAttackRulesModel( - val hitBonus: Int, - val damageSpreadMax: Int, - val confusionDivisor: Int, - val hpDefenseDivisor: Int, + val hitChance: FormulaId, + val damage: FormulaId, ) data class DefendRulesModel( + val healing: FormulaId, val weaponSkillPenalty: Int, val restThreshold: Int, val cap: Int, @@ -114,16 +113,13 @@ data class PlayerRoundModel( ) data class MonsterMeleeRulesModel( - val hitBonus: Int, - val damageDivisor: Int, - val damageSpreadMax: Int, - val damageMin: Int, + val hitChance: FormulaId, + val damage: FormulaId, val fallback: SceneId, ) data class MonsterRoundModel( - val spellChanceBasePercent: Int, - val spellPowerDivisor: Int, + val spellChance: FormulaId, val melee: MonsterMeleeRulesModel, ) @@ -139,6 +135,8 @@ data class StandardBattleModel( val encounterFoeCountMax: Int, val encounterHitPointMinFormula: FormulaId, val encounterHitPointMaxFormula: FormulaId, + val encounterFoeCountMaxFormula: FormulaId, + val encounterWeaponSkillFormula: FormulaId, val victoryImage: ImageId?, val defeatImage: ImageId?, val nativeServices: List, @@ -198,6 +196,8 @@ class StandardBattleBuilder { var encounterFoeCountMax: Int? = null var encounterHitPointMinFormula: FormulaId? = null var encounterHitPointMaxFormula: FormulaId? = null + var encounterFoeCountMaxFormula: FormulaId? = null + var encounterWeaponSkillFormula: FormulaId? = null private var victoryImage: ImageId? = null private var defeatImage: ImageId? = null @@ -248,6 +248,10 @@ class StandardBattleBuilder { requiredStandardBattle(encounterHitPointMinFormula, "encounterHitPointMinFormula = ..."), encounterHitPointMaxFormula = requiredStandardBattle(encounterHitPointMaxFormula, "encounterHitPointMaxFormula = ..."), + encounterFoeCountMaxFormula = + requiredStandardBattle(encounterFoeCountMaxFormula, "encounterFoeCountMaxFormula = ..."), + encounterWeaponSkillFormula = + requiredStandardBattle(encounterWeaponSkillFormula, "encounterWeaponSkillFormula = ..."), victoryImage = victoryImage, defeatImage = defeatImage, nativeServices = defaultNativeServices, @@ -743,21 +747,22 @@ class PlayerRoundBuilder( private var defendRules = initial?.defend private var battleCryRules = initial?.battleCry + /** A member's chance to hit, in percent, and the damage a hit does: both formulas. */ fun attack( - hitBonus: Int, - damageSpreadMax: Int, - confusionDivisor: Int, - hpDefenseDivisor: Int, + hitChance: FormulaId, + damage: FormulaId, ) { - attackRules = PlayerAttackRulesModel(hitBonus, damageSpreadMax, confusionDivisor, hpDefenseDivisor) + attackRules = PlayerAttackRulesModel(hitChance, damage) } + /** The hit points a defending member regains, from the [healing] formula, and how defending wears the foes down. */ fun defend( + healing: FormulaId, weaponSkillPenalty: Int, restThreshold: Int, cap: Int, ) { - defendRules = DefendRulesModel(weaponSkillPenalty, restThreshold, cap) + defendRules = DefendRulesModel(healing, weaponSkillPenalty, restThreshold, cap) } fun battleCry(weaponSkillPenalty: Int) { @@ -782,32 +787,22 @@ class PlayerRoundBuilder( class MonsterRoundBuilder( initial: MonsterRoundModel? = null, ) { - private var spellChanceBasePercent = initial?.spellChanceBasePercent - private var spellPowerDivisor = initial?.spellPowerDivisor + /** A monster's chance, in percent, to cast a spell instead of attacking. */ + var spellChance: FormulaId? = initial?.spellChance private var meleeRules = initial?.melee - fun spellChance( - basePercent: Int, - spellPowerDivisor: Int, - ) { - spellChanceBasePercent = basePercent - this.spellPowerDivisor = spellPowerDivisor - } - + /** A monster's chance to hit, in percent, and the damage a hit does: both formulas. */ fun melee( - hitBonus: Int, - damageDivisor: Int, - damageSpreadMax: Int, - damageMin: Int, + hitChance: FormulaId, + damage: FormulaId, fallback: SceneId, ) { - meleeRules = MonsterMeleeRulesModel(hitBonus, damageDivisor, damageSpreadMax, damageMin, fallback) + meleeRules = MonsterMeleeRulesModel(hitChance, damage, fallback) } fun build(): MonsterRoundModel = MonsterRoundModel( - spellChanceBasePercent = requiredStandardBattle(spellChanceBasePercent, "monsterRound.spellChance(...)"), - spellPowerDivisor = requiredStandardBattle(spellPowerDivisor, "monsterRound.spellChance(...)"), + spellChance = requiredStandardBattle(spellChance, "monsterRound.spellChance = ..."), melee = requiredStandardBattle(meleeRules, "monsterRound.melee(...)"), ) } diff --git a/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt index 414c388f..27ba9b12 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/ContentModelsDsl.kt @@ -104,7 +104,7 @@ data class WildernessFatigueRule( * prose authored while the runtime only supplies the affected member name. */ data class WildernessUpkeepRules( - val foodCostLeaderDiv: Int = 0, + val foodCost: FormulaId? = null, val foodTickEvery: Int = 0, val starveFoodThreshold: Int = 0, val starveDamage: Int = 0, @@ -118,7 +118,6 @@ data class WildernessUpkeepRules( ) { init { require(foodTickEvery >= 0) { "food tick interval must be non-negative" } - require(foodCostLeaderDiv >= 0) { "food leader divisor must be non-negative" } require(starveFoodThreshold >= 0) { "starvation food threshold must be non-negative" } require(starveDamage >= 0) { "starve damage must be non-negative" } require(manaRegenChance in 0..100) { "mana regeneration chance must be 0..100" } diff --git a/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt index dd3db9b2..20f68236 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt @@ -164,10 +164,11 @@ data class TownSystemModel( val leavePrompts: List, val entryTax: TownEntryTaxModel, val nativeServices: List, + val image: ImageId? = null, ) data class TownEntryTaxModel( - val minimumLeaderLevel: Int = 5, + val amount: FormulaId? = null, val pay: InputBindingModel = inputKey("P", label = "Pay to Enter"), val leave: InputBindingModel = inputKey("L", label = "Leave"), ) diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 2d2c79aa..41a7cba1 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -401,7 +401,7 @@ val authoredRylween: RylweenModel = // Upkeep runs during wilderness turns. These fields control food // ticking, fatigue labels/drain, mana recovery, and starvation. upkeep { - foodCostLeaderDiv = 4 + foodCost = Formulas.foodUpkeep foodTickEvery = 5 starveFoodThreshold = 0 starveDamage = 2 @@ -1325,19 +1325,60 @@ val authoredRylween: RylweenModel = // bonus at +20, which leaves the smith refusing at least 56% // of haggles. formula(Formulas.huntSuccessChance) { - value = whenValue(dexterity gt 100, lit(95), dexterity - 5) + value = (dexterity - 5) atMost 95 } formula(Formulas.castleTrapDisarmChance) { - value = whenValue(dexterity gt 95, lit(95), dexterity) + value = dexterity atMost 95 } formula(Formulas.haggleRollBonus) { - value = whenValue(charisma gt 90, lit(20), (charisma - 50) / 2) + value = ((charisma - 50) / 2) atMost 20 } // A spell costs its base cost plus the caster's level, for mage // spells in battle and priest spells alike. + // Every food tick each living member eats a ration, and the + // leader one more for every four levels. + formula(Formulas.foodUpkeep) { + value = livingMembers + firstLevel / 4 + } + // Towns tax a party whose leader has reached level 5: a share + // of the gold it carries, at the town's rate. + formula(Formulas.townEntryTax) { + value = whenValue(firstLevel gte 5, gold * taxPercent / 100) + } formula(Formulas.spellCost) { value = spellBaseCost + level } + // Battle arithmetic. A chance is a percentage, rolled against + // 0-99. A confused party fights at a third of its weapon skill, + // and a member's own hit points add to the damage they deal. + formula(Formulas.playerHitChance) { + value = whenValue(partyConfused, weaponSkill / 3, weaponSkill) + 1 + } + formula(Formulas.playerDamage) { + value = weaponDamage + random(0..4) + hitPoints / 12 + } + formula(Formulas.defendHealing) { + value = level + } + // A wounded monster hits less hard, and armor takes damage off + // every blow, down to a single point. + formula(Formulas.monsterHitChance) { + value = monsterWeaponSkill + 1 + } + formula(Formulas.monsterDamage) { + value = (monsterHitPoints / 6 + random(0..9) - armorClass) atLeast 1 + } + formula(Formulas.monsterSpellChance) { + value = 15 + monsterSpellPower / 2 + } + // Encounters grow with the party: monsters gain the leader's + // level in weapon skill, and some come in bigger groups. + formula(Formulas.encounterWeaponSkill) { + value = monsterWeaponSkill + firstLevel + } + formula(Formulas.encounterFoeCountMax) { + value = monsterCountMax + whenValue(countMaxLevelDivisor gt 0, firstLevel / countMaxLevelDivisor) + } } // Reward bundles define how XP, gold, loot, and special milestones @@ -1372,6 +1413,8 @@ val authoredRylween: RylweenModel = encounterFoeCountMax = 8 encounterHitPointMinFormula = Formulas.encounterH1Scaled encounterHitPointMaxFormula = Formulas.encounterH2Scaled + encounterFoeCountMaxFormula = Formulas.encounterFoeCountMax + encounterWeaponSkillFormula = Formulas.encounterWeaponSkill victoryImage(Images.Backdrop.battleVictory) defeatImage(Images.Backdrop.death) @@ -1467,23 +1510,20 @@ val authoredRylween: RylweenModel = castMageSpell('C') { line("(C)ast Spell") } } - // Player-round tunables control hit/damage math and the - // effects of defending or using a battle cry. + // The player round's hit and damage math lives in the formulas + // above; defending and a battle cry also wear the foes down. playerRound { - attack(hitBonus = 1, damageSpreadMax = 4, confusionDivisor = 3, hpDefenseDivisor = 12) - defend(weaponSkillPenalty = 2, restThreshold = 5, cap = 250) + attack(hitChance = Formulas.playerHitChance, damage = Formulas.playerDamage) + defend(healing = Formulas.defendHealing, weaponSkillPenalty = 2, restThreshold = 5, cap = 250) battleCry(weaponSkillPenalty = 4) } - // Monster-round tunables control spell chance and fallback - // melee damage for enemies that do not cast this round. + // A monster casts a spell or, failing that, attacks in melee. monsterRound { - spellChance(basePercent = 15, spellPowerDivisor = 2) + spellChance = Formulas.monsterSpellChance melee( - hitBonus = 1, - damageDivisor = 6, - damageSpreadMax = 9, - damageMin = 1, + hitChance = Formulas.monsterHitChance, + damage = Formulas.monsterDamage, fallback = Scenes.Battle.monsterMelee, ) } @@ -2839,10 +2879,12 @@ val authoredRylween: RylweenModel = // leave prompts, service scene ids, and opening-hour policy. townSystem { leavePrompts(EquipmentCommand.ReadyWeapon, EquipmentCommand.ReadyArmor) + // The street view behind the town menu and the entry tax. + image = Images.Scene.towneMainstreet // Entry tax applies before town entry for qualifying parties. // The bindings are semantic actions used by the town prompt. entryTax { - minimumLeaderLevel = 5 + amount = Formulas.townEntryTax pay = inputKey("P", label = "Pay to Enter") leave = inputKey("L", label = "Leave") } diff --git a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt index 454b50d1..c2958c7b 100644 --- a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt +++ b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt @@ -199,7 +199,7 @@ class RylweenCompiledGameLedgerTest { it.requiredStat == CharacterCreationStat.Dexterity && it.minimum == 50 }, ) - check(nextDsl.formulas.size == 9) + check(nextDsl.formulas.size == 19) check(nextDsl.rewards.size == 1) check( nextDsl.rewards @@ -211,10 +211,10 @@ class RylweenCompiledGameLedgerTest { check(standardBattle.actions.map { it.prompt }.first() == literalText { line("(A)ttack") }) check(standardBattle.text.useWhat == literalText { lines("Use what?", "") }) check(standardBattle.text.spellAbort.fallbackText() == "RETURN leaves.") - check(standardBattle.playerRound.attack.confusionDivisor == 3) - check(standardBattle.playerRound.attack.hpDefenseDivisor == 12) + check(standardBattle.playerRound.attack.hitChance == Formulas.playerHitChance) + check(standardBattle.playerRound.attack.damage == Formulas.playerDamage) check(standardBattle.playerRound.defend.cap == 250) - check(standardBattle.monsterRound.melee.damageDivisor == 6) + check(standardBattle.monsterRound.melee.damage == Formulas.monsterDamage) check(standardBattle.roundLimit == 200) check(standardBattle.encounterFoeCountMax == 8) check(standardBattle.victoryImage == Images.Backdrop.battleVictory) @@ -358,7 +358,7 @@ class RylweenCompiledGameLedgerTest { check(townSystem.menu.single { it.key == 'C' }.building == Buildings.church) check(townSystem.menu.single { it.action == keyAction("leave_town") }.endsMenu) check(townSystem.leavePrompts == listOf(EquipmentCommand.ReadyWeapon, EquipmentCommand.ReadyArmor)) - check(townSystem.entryTax.minimumLeaderLevel == 5) + check(townSystem.entryTax.amount == Formulas.townEntryTax) check(townSystem.entryTax.pay.primary == "P") check(townSystem.entryTax.pay.label == "Pay to Enter") check(townSystem.entryTax.leave.primary == "L") diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt index 5bed67dd..436fb301 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt @@ -448,22 +448,15 @@ internal class BattleRunner( ): BattleEncounter { val targetIndex = selectMonsterTarget() ?: return copy(actionRetry = true) val hit = runtime.party.drawRandom(0, RANDOM_PERCENT_MAX) - val skill = - when { - partyConfused -> member.weaponSkill / rules.playerRound.attack.confusionDivisor - else -> member.weaponSkill - } - val hitChance = (skill + rules.playerRound.attack.hitBonus).coerceIn(0, 100) + val attacker = member.battleBindings() + ("party_confused" to if (partyConfused) 1 else 0) + val hitChance = content.evalFormula(rules.playerRound.attack.hitChance, hit.party, attacker).value.coerceIn(0, 100) if (hit.value >= hitChance) { audio.weaponMiss(content.slug(member.equipment.weapon)) messages += rules.text.playerMiss.renderBattle(BATTLE_ATTACKER_NAME to runtime.party.memberName(content, memberIndex)) return copy(runtime = runtime.withParty(hit.party)) } - val damageDraw = hit.party.drawRandom(0, rules.playerRound.attack.damageSpreadMax) - val damage = - member.weaponDamage() + - damageDraw.value + - member.hitPoints.current / rules.playerRound.attack.hpDefenseDivisor + val damageDraw = content.evalFormula(rules.playerRound.attack.damage, hit.party, attacker) + val damage = damageDraw.value.coerceAtLeast(0) val nextHp = monsterHp.mapIndexed { index, hp -> hp.takeUnless { index == targetIndex } ?: (hp - damage).coerceAtLeast(0) @@ -494,7 +487,8 @@ internal class BattleRunner( messages: MutableList, ): BattleEncounter { audio.cue(AudioCue.Defend) - val healed = (member.hitPoints.current + member.level).coerceAtMost(member.hitPoints.max) + val healing = content.evalFormula(rules.playerRound.defend.healing, runtime.party, member.battleBindings()).value + val healed = (member.hitPoints.current + healing).coerceAtMost(member.hitPoints.max) val nextMember = member.copy(hitPoints = healed of member.hitPoints.max) val nextMessages = rules.text.restGainHits @@ -631,7 +625,9 @@ internal class BattleRunner( val target = targetDraw.party.members[targetIndex] val targetName = targetDraw.party.memberName(content, targetIndex) val hit = targetDraw.party.drawRandom(0, RANDOM_PERCENT_MAX) - val hitChance = (monsterWeaponSkill + rules.monsterRound.melee.hitBonus).coerceIn(0, 100) + val melee = + target.battleBindings() + mapOf("monster_weapon_skill" to monsterWeaponSkill, "monster_hit_points" to monsterHitPoints) + val hitChance = content.evalFormula(rules.monsterRound.melee.hitChance, hit.party, melee).value.coerceIn(0, 100) if (hit.value >= hitChance) { audio.cue(AudioCue.MonsterMiss) messages += @@ -641,10 +637,8 @@ internal class BattleRunner( ) return copy(runtime = runtime.withParty(hit.party)) } - val damageDraw = hit.party.drawRandom(0, rules.monsterRound.melee.damageSpreadMax) - val damage = - (monsterHitPoints / rules.monsterRound.melee.damageDivisor + damageDraw.value - target.armorClass()) - .coerceAtLeast(rules.monsterRound.melee.damageMin) + val damageDraw = content.evalFormula(rules.monsterRound.melee.damage, hit.party, melee) + val damage = damageDraw.value.coerceAtLeast(0) val nextHp = (target.hitPoints.current - damage).coerceAtLeast(0) val nextTarget = target.copy(hitPoints = nextHp of target.hitPoints.max, dead = target.dead || nextHp == 0) audio.monsterHit(content.slug(monster.id), content.slug(target.equipment.armor)) @@ -665,7 +659,12 @@ internal class BattleRunner( val options = monsterSpells() if (antimagic || monster.spellPower <= 0 || options.isEmpty()) return BattleCastDecision(false, this) val chance = - rules.monsterRound.spellChanceBasePercent + monster.spellPower / rules.monsterRound.spellPowerDivisor + content + .evalFormula( + rules.monsterRound.spellChance, + runtime.party, + mapOf("monster_spell_power" to monster.spellPower), + ).value val draw = runtime.party.drawRandom(0, RANDOM_PERCENT_MAX) return BattleCastDecision(draw.value < chance, copy(runtime = runtime.withParty(draw.party))) } @@ -815,7 +814,14 @@ internal class BattleRunner( ): BattleEncounter { var party = runtime.party val firstLevel = party.members.firstOrNull()?.level ?: 0 - val countMax = monster.count.last + (monster.countMaxLevelDivisor?.let { divisor -> firstLevel / divisor } ?: 0) + val scaling = + mapOf( + "first_level" to firstLevel, + "monster_weapon_skill" to monster.weaponSkill, + "monster_count_max" to monster.count.last, + "count_max_level_divisor" to (monster.countMaxLevelDivisor ?: 0), + ) + val countMax = content.evalFormula(rules.encounterFoeCountMaxFormula, party, scaling).value val bannerDraw = rules.opening.banners .takeIf { banners -> banners.isNotEmpty() } @@ -878,7 +884,7 @@ internal class BattleRunner( monsterHp = hitPoints, monsterHpMax = hitPoints, hitPointMax = hpRange.last, - monsterWeaponSkill = monster.weaponSkill + firstLevel, + monsterWeaponSkill = content.evalFormula(rules.encounterWeaponSkillFormula, party, scaling).value, mandatory = mandatory, bannerIndex = bannerDraw?.value, ) @@ -987,6 +993,16 @@ internal class BattleRunner( return BattleLevelUps(copy(members = nextMembers), gains.filterNotNull()) } + // The formula variables for one member in battle: their stats, weapon and armor. + private fun CompiledPartyMember.battleBindings(): Map = + statBindings() + + mapOf( + "weapon_skill" to weaponSkill, + "weapon_damage" to weaponDamage(), + "hit_points" to hitPoints.current, + "armor_class" to armorClass(), + ) + private fun CompiledPartyMember.weaponDamage(): Int = content.itemRecord(equipment.weapon)?.weaponDamage ?: 1 private fun CompiledPartyMember.armorClass(): Int = content.itemRecord(equipment.armor)?.armorClass ?: 0 diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimePresentation.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimePresentation.kt index 2a3a6ff5..67722e2a 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimePresentation.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimePresentation.kt @@ -16,8 +16,6 @@ import rylween.compiled.RuntimeCommandGroupId import rylween.dsl.impl.PcClass import rylween.dsl.impl.WildernessFatigueMatch -private const val PERCENT_DENOMINATOR = 100 - fun runtimeWildernessContextLines( content: CompiledContentBundle, systems: ExternalRuntimeSystems, @@ -77,16 +75,9 @@ fun RuntimeState.runtimeTextValue( "partyMemberMax" -> partyMemberMax.toString() "currentTownName" -> currentTown?.let(content::runtimeTownName) "townTaxPercent" -> currentTown?.let(content::runtimeTown)?.taxPercent?.toString() - "townTaxAmount" -> runtimeTownTaxAmount(content)?.toString() else -> null } -fun RuntimeState.runtimeTownTaxAmount(content: CompiledContentBundle): Int? = - currentTown - ?.let(content::runtimeTown) - ?.taxPercent - ?.let { tax -> party.resources.gold * tax / PERCENT_DENOMINATOR } - fun RuntimeState.runtimeTextValue( content: CompiledContentBundle, part: CompiledRuntimeTextPart, diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt index 5ce76bfb..a51f6ebb 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt @@ -89,7 +89,6 @@ private const val MANUAL_SCREEN = "manual" private const val HUT_SCENE = "towne.hut" private const val TEXT_WINDOW_PAGE_LINES = 9 -private const val TOWN_MAIN_STREET_IMAGE = "blitgfx.towne_mainstreet" private val townCommandGroup = RuntimeCommandGroupId.Town.id private val townLeaveAction = RuntimeCommandActionId.LeaveTown.id @@ -1673,7 +1672,7 @@ class GameRuntime private constructor( val menu = menuLines(menuNotice) menuNotice = emptyList() audio.music(MusicArea.Town) - screen.showImage(TOWN_MAIN_STREET_IMAGE) + systems.town?.image?.let(screen::showImage) screen.writeText(menu) var choice = input.readCommand() ?: return current while (choice == '!') { @@ -1719,13 +1718,16 @@ class GameRuntime private constructor( town: rylween.compiled.CompiledTown, log: RuntimeLog, ): TownEntryTaxResult? { - val tax = systems.town?.entryTax ?: return TownEntryTaxResult(runtime) + val townSystem = systems.town ?: return TownEntryTaxResult(runtime) + val tax = townSystem.entryTax ?: return TownEntryTaxResult(runtime) + val formula = tax.amount ?: return TownEntryTaxResult(runtime) val leaderLevel = runtime.party.leaderLevel - if (leaderLevel < tax.minimumLeaderLevel) return TownEntryTaxResult(runtime) - val amount = runtime.runtimeTownTaxAmount(content)?.takeIf { gold -> gold > 0 } ?: return TownEntryTaxResult(runtime) - val lines = townEntryTaxLines(runtime, tax, screen) + val taxed = mapOf("gold" to runtime.party.resources.gold, "tax_percent" to town.taxPercent, "first_level" to leaderLevel) + val amount = + content.evalFormula(formula, runtime.party, taxed).value.takeIf { gold -> gold > 0 } ?: return TownEntryTaxResult(runtime) + val lines = townEntryTaxLines(runtime, tax, amount, screen) log.event("town.tax.prompt town=${slug(town.id)} level=$leaderLevel amount=$amount gold=${runtime.party.resources.gold}") - screen.showImage(TOWN_MAIN_STREET_IMAGE) + townSystem.image?.let(screen::showImage) screen.writeText(lines) val audio = RuntimeAudio(systems.audio, screen) val choice = @@ -1752,11 +1754,12 @@ class GameRuntime private constructor( private fun townEntryTaxLines( runtime: RuntimeState, tax: ExternalTownEntryTax, + amount: Int, screen: RuntimeScreenPort, ): List = screen.choiceMenuLines( systems.prompts.town.entryTax - .renderRuntimeText(content, runtime, screen.textColumns), + .renderRuntimeText(content, runtime, screen.textColumns) { kind -> amount.toString().takeIf { kind == "townTaxAmount" } }, listOf( tax.pay.mnemonicLine(tax.pay.label), tax.leave.mnemonicLine(tax.leave.label), diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt index ffbd4760..3bc515dc 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/WildernessActions.kt @@ -657,10 +657,12 @@ internal class WildernessActions( return party.copy(members = members) } - private fun PartyState.foodTickCost(): Int { - val leaderLevelCost = if (realm.upkeep.foodCostLeaderDiv > 0) leaderLevel() / realm.upkeep.foodCostLeaderDiv else 0 - return (counters.memberCount ?: members.size) + leaderLevelCost - } + private fun PartyState.foodTickCost(): Int = + realm.upkeep.foodCost + ?.let { formula -> + val upkeep = mapOf("living_members" to (counters.memberCount ?: members.size), "first_level" to leaderLevel()) + content.evalFormula(formula, this, upkeep).value + } ?: 0 private fun PartyState.applyStarvation( foodAfterTick: Int, diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotBattle.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotBattle.kt index 3921d57c..f414090e 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotBattle.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/AutopilotBattle.kt @@ -3,15 +3,19 @@ * the rest, and wear the enemy down from its weakest member. * * Decisions come from an expected-value model of the bundle's own combat - * rules: a party member hits with chance weapon skill + bonus for weapon - * damage plus a spread plus current hit points over a divisor, and each living - * monster hits with chance weapon skill + bonus for its current hit points over - * a divisor plus a spread, less the target's armor. + * formulas: each is evaluated at its average, a random draw counting as the + * middle of its range, for the party's hits on the foes and the foes' hits on + * the party. */ package rylween.runtime +import rylween.compiled.CompiledBinaryOp +import rylween.compiled.CompiledBoolExpr +import rylween.compiled.CompiledComparisonOp import rylween.compiled.CompiledContentBundle +import rylween.compiled.CompiledHandleKind +import rylween.compiled.CompiledIntExpr import rylween.compiled.CompiledMonster import rylween.compiled.CompiledPartyMember import rylween.compiled.ExternalRuntimeSystems @@ -211,8 +215,8 @@ internal class AutopilotBattle( val attack = rules.playerRound.attack val partyDamagePerRound = living.sumOf { member -> - hitChance(member.weaponSkill + attack.hitBonus) * - (weaponDamage(member) + attack.damageSpreadMax / 2.0 + member.hitPoints.current / attack.hpDefenseDivisor) + val attacker = formulaBindings(member) + hitChance(expected(attack.hitChance, attacker)) * expected(attack.damage, attacker) } if (partyDamagePerRound <= 0.0) return Double.MAX_VALUE val melee = rules.monsterRound.melee @@ -221,7 +225,7 @@ internal class AutopilotBattle( foes.monster ?.spellPower ?.takeIf { power -> power > 0 } - ?.let { power -> (rules.monsterRound.spellChanceBasePercent + power / rules.monsterRound.spellPowerDivisor) / 100.0 } + ?.let { power -> expected(rules.monsterRound.spellChance, mapOf("monster_spell_power" to power.toDouble())) / 100.0 } ?: 0.0 val armor = living.map(::armorClass).average() // Kill the weakest foe first: it stops attacking soonest. @@ -236,8 +240,13 @@ internal class AutopilotBattle( while (remaining.isNotEmpty() && rounds < MAX_ROUNDS) { taken += remaining.sumOf { hitPoints -> - val hit = maxOf(melee.damageMin.toDouble(), hitPoints / melee.damageDivisor + melee.damageSpreadMax / 2.0 - armor) - hitChance(weaponSkill + melee.hitBonus) * hit * (1 - spellChance) + spellChance * SPELL_DAMAGE + val foe = + mapOf( + "monster_weapon_skill" to weaponSkill.toDouble(), + "monster_hit_points" to hitPoints, + "armor_class" to armor, + ) + hitChance(expected(melee.hitChance, foe)) * expected(melee.damage, foe) * (1 - spellChance) + spellChance * SPELL_DAMAGE } var damage = partyDamagePerRound while (damage > 0 && remaining.isNotEmpty()) { @@ -257,11 +266,21 @@ internal class AutopilotBattle( foes: AutopilotFoes, ): List { val range = foes.monster?.hitPoints ?: defaultHitPoints - val leaderLevel = party.members.firstOrNull()?.level ?: 1 - val averageLevel = party.members.map(CompiledPartyMember::level).average() - val low = range.first + (averageLevel * 2).toInt() + if (leaderLevel > 2) leaderLevel * 2 else 0 - val high = range.last + leaderLevel * 3 - return List(foes.count) { (low + high) / 2 } + val scaling = + mapOf( + "encounter_hit_point_min_base" to range.first.toDouble(), + "encounter_hit_point_max_base" to range.last.toDouble(), + "party_avg" to + party.members + .map(CompiledPartyMember::level) + .average() + .toInt() + .toDouble(), + "first_level" to (party.members.firstOrNull()?.level ?: 1).toDouble(), + ) + val low = expected(rules.encounterHitPointMinFormula, scaling) + val high = expected(rules.encounterHitPointMaxFormula, scaling) + return List(foes.count) { ((low + high) / 2).toInt() } } private fun targetHitPoints(line: String): Int? = targetHitPointsPattern.find(line)?.let { match -> match.groupValues[2].toInt() } @@ -272,7 +291,93 @@ internal class AutopilotBattle( private fun armorClass(member: CompiledPartyMember): Int = content.items.firstOrNull { item -> item.id == member.equipment.armor }?.armorClass ?: 0 - private fun hitChance(chance: Int): Double = chance.coerceIn(0, 100) / 100.0 + private fun hitChance(chance: Double): Double = chance.coerceIn(0.0, 100.0) / 100.0 + + // The formula variables the battle runner binds for a member. + private fun formulaBindings(member: CompiledPartyMember): Map = + mapOf( + "weapon_skill" to member.weaponSkill, + "weapon_damage" to weaponDamage(member), + "hit_points" to member.hitPoints.current, + "armor_class" to armorClass(member), + "level" to member.level, + "charisma" to member.charisma, + "dexterity" to member.dexterity, + ).mapValues { (_, value) -> value.toDouble() } + + /** The average value of the formula [slug]: a random draw counts as the middle of its range. */ + private fun expected( + slug: String, + bindings: Map, + ): Double { + val formula = content.ref(CompiledHandleKind.Formula, slug) + return expected(content.formulas.single { candidate -> candidate.id == formula }.value, bindings) + } + + private fun expected( + expr: CompiledIntExpr, + bindings: Map, + ): Double = + when (expr) { + is CompiledIntExpr.Literal -> expr.value.toDouble() + is CompiledIntExpr.Local -> bindings[content.strings.value(expr.nameString)] ?: 0.0 + is CompiledIntExpr.Binary -> expected(expr.left, bindings).combinedWith(expr.op, expected(expr.right, bindings)) + is CompiledIntExpr.If -> + if (holds( + expr.cond, + bindings, + ) + ) { + expected(expr.thenValue, bindings) + } else { + expected(expr.elseValue, bindings) + } + is CompiledIntExpr.Random -> (expected(expr.lo, bindings) + expected(expr.hi, bindings)) / 2 + else -> 0.0 + } + + // Whole numbers divide as the runtime's integers do; an average divides exactly. + private fun Double.combinedWith( + op: CompiledBinaryOp, + right: Double, + ): Double = + when (op) { + CompiledBinaryOp.Add -> this + right + CompiledBinaryOp.Sub -> this - right + CompiledBinaryOp.Mul -> this * right + CompiledBinaryOp.Div -> + when { + right == 0.0 -> this + this % 1.0 == 0.0 && right % 1.0 == 0.0 -> (this / right).toLong().toDouble() + else -> this / right + } + CompiledBinaryOp.Mod -> if (right == 0.0) this else this % right + CompiledBinaryOp.Max -> maxOf(this, right) + CompiledBinaryOp.Min -> minOf(this, right) + } + + private fun holds( + cond: CompiledBoolExpr, + bindings: Map, + ): Boolean = + when (cond) { + is CompiledBoolExpr.Cmp -> { + val left = expected(cond.left, bindings) + val right = expected(cond.right, bindings) + when (cond.op) { + CompiledComparisonOp.Eq -> left == right + CompiledComparisonOp.Ne -> left != right + CompiledComparisonOp.Lt -> left < right + CompiledComparisonOp.Lte -> left <= right + CompiledComparisonOp.Gt -> left > right + CompiledComparisonOp.Gte -> left >= right + } + } + is CompiledBoolExpr.Not -> !holds(cond.expr, bindings) + is CompiledBoolExpr.And -> holds(cond.left, bindings) && holds(cond.right, bindings) + is CompiledBoolExpr.Or -> holds(cond.left, bindings) || holds(cond.right, bindings) + else -> false + } private companion object { const val HOPELESS_AFTER_FAILED_ESCAPES = 2 From 6871458de056bf2a11b257eb2319ef6719682dc7 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:17 +0100 Subject: [PATCH 07/16] Price shop goods with formulas 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. --- .../kotlin/rylween/compiled/CompiledBundle.kt | 16 ++++---------- core/src/main/kotlin/rylween/dsl/Dsl.kt | 3 +++ .../main/kotlin/rylween/dsl/DslValidation.kt | 15 ++++--------- .../main/kotlin/rylween/dsl/impl/ShopDsl.kt | 22 +++++++------------ .../main/kotlin/rylween/game/RylweenGame.kt | 18 +++++++++++++-- .../rylween/RylweenCompiledGameLedgerTest.kt | 2 +- .../kotlin/rylween/runtime/ShopService.kt | 9 ++++---- 7 files changed, 41 insertions(+), 44 deletions(-) diff --git a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt index 3f558157..bc15da0e 100644 --- a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt +++ b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt @@ -1243,18 +1243,13 @@ data class CompiledShopItemOffer( sealed interface CompiledShopPrice { data object ItemCost : CompiledShopPrice - data object HalfItemCost : CompiledShopPrice - data class Fixed( val amount: Int, ) : CompiledShopPrice - data class LeaderLevelPlus( - val addend: Int, - ) : CompiledShopPrice - - data class ItemCostPlusLeaderLevelTimes( - val multiplier: Int, + /** A price from an authored formula, evaluated with the item's cost and the party leader's level. */ + data class Formula( + val formula: CompiledHandleRef, ) : CompiledShopPrice } @@ -2352,11 +2347,8 @@ private class CompiledBundleCompiler( private fun shopPrice(price: ShopPriceModel): CompiledShopPrice = when (price) { ShopPriceModel.ItemCost -> CompiledShopPrice.ItemCost - ShopPriceModel.HalfItemCost -> CompiledShopPrice.HalfItemCost is ShopPriceModel.Fixed -> CompiledShopPrice.Fixed(price.amount) - is ShopPriceModel.LeaderLevelPlus -> CompiledShopPrice.LeaderLevelPlus(price.addend) - is ShopPriceModel.ItemCostPlusLeaderLevelTimes -> - CompiledShopPrice.ItemCostPlusLeaderLevelTimes(price.multiplier) + is ShopPriceModel.Formula -> CompiledShopPrice.Formula(formulaRef(price.formula)) } private fun shopPurchase(purchase: ShopPurchaseModel): CompiledShopPurchase = diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index 07ea866b..e6f3dd35 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -3487,6 +3487,9 @@ class FormulaBuilder( // Upkeep and town entry: the party's living members and the gold it // carries, and the tax rate of the town it enters. val livingMembers: IntExpr = v("living_members") + + // A shop price: the cost of the item on offer. + val itemCost: IntExpr = v("item_cost") val gold: IntExpr = v("gold") val taxPercent: IntExpr = v("tax_percent") diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 8f6238a6..04d3cfd0 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -1757,6 +1757,7 @@ fun validateScriptRewards( .map { it.id } .toSet() val dungeonScenarios = content.dungeons.scenarios.associateBy { it.dungeon } + val knownFormulas = content.formulas.map { it.id }.toSet() fun validateSlottedItemPool( pool: ItemPoolId, @@ -1916,18 +1917,10 @@ fun validateScriptRewards( label: String, ) { when (price) { - ShopPriceModel.ItemCost, - ShopPriceModel.HalfItemCost, - -> Unit + ShopPriceModel.ItemCost -> Unit is ShopPriceModel.Fixed -> check(price.amount >= 0) { "$label fixed price is negative" } - is ShopPriceModel.LeaderLevelPlus -> - check(price.addend >= 0) { - "$label leader-level addend is negative" - } - is ShopPriceModel.ItemCostPlusLeaderLevelTimes -> - check(price.multiplier >= 0) { - "$label leader-level multiplier is negative" - } + is ShopPriceModel.Formula -> + check(price.formula in knownFormulas) { "$label price references missing formula ${price.formula.slug}" } } } diff --git a/core/src/main/kotlin/rylween/dsl/impl/ShopDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/ShopDsl.kt index a946682d..855ef8ca 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/ShopDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/ShopDsl.kt @@ -88,30 +88,22 @@ object ShopZeroQuantityDeal { sealed interface ShopPriceModel { object ItemCost : ShopPriceModel - object HalfItemCost : ShopPriceModel - data class Fixed( val amount: Int, ) : ShopPriceModel - data class LeaderLevelPlus( - val addend: Int, - ) : ShopPriceModel - - data class ItemCostPlusLeaderLevelTimes( - val multiplier: Int, + /** A price worked out by a formula, which sees the item's cost and the party leader's level. */ + data class Formula( + val formula: FormulaId, ) : ShopPriceModel } class ShopPriceRefs { val itemCost: ShopPriceModel = ShopPriceModel.ItemCost - val halfItemCost: ShopPriceModel = ShopPriceModel.HalfItemCost fun fixed(amount: Int): ShopPriceModel = ShopPriceModel.Fixed(amount) - fun leaderLevelPlus(addend: Int): ShopPriceModel = ShopPriceModel.LeaderLevelPlus(addend) - - fun itemCostPlusLeaderLevelTimes(multiplier: Int): ShopPriceModel = ShopPriceModel.ItemCostPlusLeaderLevelTimes(multiplier) + fun formula(formula: FormulaId): ShopPriceModel = ShopPriceModel.Formula(formula) } val ShopPrices: ShopPriceRefs = ShopPriceRefs() @@ -799,7 +791,9 @@ class ShopSellBuilder { private var offerText: TextBlock? = null private var declinedText: TextBlock? = null private var soldText: TextBlock? = null - var price: ShopPriceModel = ShopPriceModel.HalfItemCost + + /** What the shop offers for an item before any haggling. */ + var price: ShopPriceModel? = null private var haggleModel: ShopSellHaggleModel? = null private var saleKeysModel: ShopSaleKeysModel = ShopSaleKeysModel() @@ -869,7 +863,7 @@ class ShopSellBuilder { offer = requireNotNull(offerText) { "shop sell section requires offer text" }, declined = declinedText, sold = soldText, - price = price, + price = requireNotNull(price) { "shop sell section requires a price" }, haggle = haggleModel, saleKeys = saleKeysModel, ) diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 41a7cba1..9bba74e1 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -1345,6 +1345,18 @@ val authoredRylween: RylweenModel = formula(Formulas.townEntryTax) { value = whenValue(firstLevel gte 5, gold * taxPercent / 100) } + // Shop prices: a ration costs a gold piece more than the + // leader's level, a healing potion three per level on top of + // its cost, and shops buy at half an item's cost. + formula(Formulas.rationPrice) { + value = firstLevel + 1 + } + formula(Formulas.healingPotionPrice) { + value = itemCost + firstLevel * 3 + } + formula(Formulas.sellPrice) { + value = itemCost / 2 + } formula(Formulas.spellCost) { value = spellBaseCost + level } @@ -4284,6 +4296,7 @@ val authoredRylween: RylweenModel = sell { prompt("Sell what?", "") acceptsKinds(ItemKind.Weapon, ItemKind.Armor) + price = ShopPrices.formula(Formulas.sellPrice) wrongKind("Not weapon or armor.") offer { line("Ok! Give ya ", price, "!") @@ -4549,7 +4562,7 @@ val authoredRylween: RylweenModel = line("You can carry no more than ", cap, " units!") }, label = "Food Ration", - price = ShopPrices.leaderLevelPlus(1), + price = ShopPrices.formula(Formulas.rationPrice), description = flowText("Better food is not available anywhere else in the entire realm."), ) item('C', Items.blanket, label = "Blanket", description = flowText("Our blankets are very warm and soft.")) @@ -4559,7 +4572,7 @@ val authoredRylween: RylweenModel = 'F', Items.redPotion, label = "Healing Potion", - price = ShopPrices.itemCostPlusLeaderLevelTimes(3), + price = ShopPrices.formula(Formulas.healingPotionPrice), description = flowText("The best healing potions available for money!"), ) item( @@ -4576,6 +4589,7 @@ val authoredRylween: RylweenModel = accepts(Items.ration, Items.blanket, Items.tent, Items.rope) acceptsKinds(ItemKind.Potion, ItemKind.Treasure, ItemKind.MagicItem) rejects(Items.donkey) + price = ShopPrices.formula(Formulas.sellPrice) wrongKind(flowText("- I don't deal in that kind of stuff!")) offer { line("- Ok. Give ya ", price, "!") diff --git a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt index c2958c7b..a9e387e1 100644 --- a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt +++ b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt @@ -199,7 +199,7 @@ class RylweenCompiledGameLedgerTest { it.requiredStat == CharacterCreationStat.Dexterity && it.minimum == 50 }, ) - check(nextDsl.formulas.size == 19) + check(nextDsl.formulas.size == 22) check(nextDsl.rewards.size == 1) check( nextDsl.rewards diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/ShopService.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/ShopService.kt index 7654a3a5..3f421dbb 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/ShopService.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/ShopService.kt @@ -613,14 +613,15 @@ internal class ShopService( private fun price( price: CompiledShopPrice, item: CompiledHandleRef, - party: PartyState?, + party: PartyState, ): Int = when (price) { CompiledShopPrice.ItemCost -> itemRecord(item).cost - CompiledShopPrice.HalfItemCost -> itemRecord(item).cost / 2 is CompiledShopPrice.Fixed -> price.amount - is CompiledShopPrice.LeaderLevelPlus -> (party?.leaderLevel ?: 0) + price.addend - is CompiledShopPrice.ItemCostPlusLeaderLevelTimes -> itemRecord(item).cost + (party?.leaderLevel ?: 0) * price.multiplier + is CompiledShopPrice.Formula -> { + val priced = mapOf("item_cost" to itemRecord(item).cost, "first_level" to party.leaderLevel) + content.evalFormula(price.formula, party, priced).value.coerceAtLeast(0) + } } private fun remainingCapacity( From 84592aecfe5e20968753957b440555f268884975 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:17 +0100 Subject: [PATCH 08/16] Author battle and castle messages whole 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. --- .../kotlin/rylween/compiled/CompiledBundle.kt | 4 ++ .../compiled/ExternalBundleArtifact.kt | 32 ++++-------- .../kotlin/rylween/dsl/AuthoringFacade.kt | 1 + .../main/kotlin/rylween/dsl/DslValidation.kt | 13 +++-- .../rylween/dsl/ScriptSourceAnalysis.kt | 2 + core/src/main/kotlin/rylween/dsl/TextDsl.kt | 7 +++ .../main/kotlin/rylween/dsl/impl/CastleDsl.kt | 8 +-- .../main/kotlin/rylween/dsl/impl/CombatDsl.kt | 51 +++++-------------- .../rylween/dsl/impl/WorldContentDsl.kt | 6 +++ .../main/kotlin/rylween/game/RylweenGame.kt | 30 +++++++---- .../rylween/RylweenCompiledGameLedgerTest.kt | 2 +- .../kotlin/rylween/runtime/BattleRunner.kt | 24 ++++----- .../kotlin/rylween/runtime/CastleRuntime.kt | 8 +-- 13 files changed, 92 insertions(+), 96 deletions(-) diff --git a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt index bc15da0e..1563b8df 100644 --- a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt +++ b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt @@ -883,6 +883,7 @@ enum class CompiledRuntimeTextPart { HuntFoodGained, UpkeepMemberName, CampGuardName, + CastleThiefName, PartyMemberCount, PartyMemberMax, WildernessDungeonName, @@ -908,6 +909,7 @@ enum class CompiledRuntimeTextPart { BattleLootName, BattleLevelMemberName, BattleLevelsGained, + BattleRoundNumber, } /** Screen/view command emitted from scripts and interpreted by runtime renderers. */ @@ -2200,6 +2202,7 @@ private class CompiledBundleCompiler( TextPart.HuntFoodGained -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.HuntFoodGained) TextPart.UpkeepMemberName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.UpkeepMemberName) TextPart.CampGuardName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.CampGuardName) + TextPart.CastleThiefName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.CastleThiefName) TextPart.PartyMemberCount -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.PartyMemberCount) TextPart.PartyMemberMax -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.PartyMemberMax) TextPart.WildernessDungeonName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.WildernessDungeonName) @@ -2225,6 +2228,7 @@ private class CompiledBundleCompiler( TextPart.BattleLootName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.BattleLootName) TextPart.BattleLevelMemberName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.BattleLevelMemberName) TextPart.BattleLevelsGained -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.BattleLevelsGained) + TextPart.BattleRoundNumber -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.BattleRoundNumber) } private fun viewCommand(command: ViewCommand): CompiledViewCommand = diff --git a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index 3df11b24..65c1391b 100644 --- a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt +++ b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt @@ -781,10 +781,8 @@ data class ExternalMonsterMeleeRules( /** Battle prompt and narration text blocks. */ data class ExternalBattleText( - val encounterBanner: ExternalRuntimeTextBlock, - val youFace: ExternalRuntimeTextBlock, - val foeDisplayName: ExternalRuntimeTextBlock, - val stillFace: ExternalRuntimeTextBlock, + val encounter: ExternalRuntimeTextBlock, + val nextRound: ExternalRuntimeTextBlock, val fight: ExternalRuntimeTextBlock, val run: ExternalRuntimeTextBlock, val bloodFlow: ExternalRuntimeTextBlock, @@ -812,9 +810,7 @@ data class ExternalBattleText( val partyHeld: ExternalRuntimeTextBlock, val partyDefeated: ExternalRuntimeTextBlock, val victoryBested: ExternalRuntimeTextBlock, - val victoryEachSurvivor: ExternalRuntimeTextBlock, val victoryReward: ExternalRuntimeTextBlock, - val victoryFoundObject: ExternalRuntimeTextBlock, val victoryLoot: ExternalRuntimeTextBlock, val levelGain: ExternalRuntimeTextBlock, ) @@ -1116,7 +1112,7 @@ data class ExternalCastleScripts( /** Castle text prompts and narration exported without the Kotlin runtime facade. */ data class ExternalCastleText( val roomMonster: ExternalRuntimeTextBlock, - val trapTriesDisarmSuffix: ExternalRuntimeTextBlock, + val trapTriesDisarm: ExternalRuntimeTextBlock, val trapDisarmSucceed: ExternalRuntimeTextBlock, val trapDisarmFail: ExternalRuntimeTextBlock, val pitfallIllustration: String?, @@ -1649,10 +1645,8 @@ private class ExternalBundleArtifactWriter { private fun battleTextJson(text: BattleTextModel): JsonValue = jsonObject( - "encounterBanner" to textBlockJson(text.encounterBanner), - "youFace" to textBlockJson(text.youFace), - "foeDisplayName" to textBlockJson(text.foeDisplayName), - "stillFace" to textBlockJson(text.stillFace), + "encounter" to textBlockJson(text.encounter), + "nextRound" to textBlockJson(text.nextRound), "fight" to textBlockJson(text.fight), "run" to textBlockJson(text.run), "bloodFlow" to textBlockJson(text.bloodFlow), @@ -1680,9 +1674,7 @@ private class ExternalBundleArtifactWriter { "partyHeld" to textBlockJson(text.partyHeld), "partyDefeated" to textBlockJson(text.partyDefeated), "victoryBested" to textBlockJson(text.victoryBested), - "victoryEachSurvivor" to textBlockJson(text.victoryEachSurvivor), "victoryReward" to textBlockJson(text.victoryReward), - "victoryFoundObject" to textBlockJson(text.victoryFoundObject), "victoryLoot" to textBlockJson(text.victoryLoot), "levelGain" to textBlockJson(text.levelGain), ) @@ -2499,7 +2491,7 @@ private class ExternalBundleArtifactWriter { private fun castleTextJson(text: CastleTextModel): JsonValue = jsonObject( "roomMonster" to textBlockJson(text.roomMonster), - "trapTriesDisarmSuffix" to textBlockJson(text.trapTriesDisarmSuffix), + "trapTriesDisarm" to textBlockJson(text.trapTriesDisarm), "trapDisarmSucceed" to textBlockJson(text.trapDisarmSucceed), "trapDisarmFail" to textBlockJson(text.trapDisarmFail), "pitfallIllustration" to text.pitfallIllustration?.let { JsonString(it.slug) }.orJsonNull(), @@ -2594,6 +2586,7 @@ private class ExternalBundleArtifactWriter { TextPart.HuntFoodGained -> textTokenJson("huntFoodGained") TextPart.UpkeepMemberName -> textTokenJson("upkeepMemberName") TextPart.CampGuardName -> textTokenJson("campGuardName") + TextPart.CastleThiefName -> textTokenJson("castleThiefName") TextPart.PartyMemberCount -> textTokenJson("partyMemberCount") TextPart.PartyMemberMax -> textTokenJson("partyMemberMax") TextPart.WildernessDungeonName -> textTokenJson("wildernessDungeonName") @@ -2619,6 +2612,7 @@ private class ExternalBundleArtifactWriter { TextPart.BattleLootName -> textTokenJson("battleLootName") TextPart.BattleLevelMemberName -> textTokenJson("battleLevelMemberName") TextPart.BattleLevelsGained -> textTokenJson("battleLevelsGained") + TextPart.BattleRoundNumber -> textTokenJson("battleRoundNumber") } private fun textTokenJson(kind: String): JsonValue = jsonObject("kind" to JsonString(kind)) @@ -3489,7 +3483,7 @@ private class ExternalRuntimeSystemsReader( private fun JsonObject.readCastleText(): ExternalCastleText = ExternalCastleText( roomMonster = required("roomMonster").readTextBlock(), - trapTriesDisarmSuffix = required("trapTriesDisarmSuffix").readTextBlock(), + trapTriesDisarm = required("trapTriesDisarm").readTextBlock(), trapDisarmSucceed = required("trapDisarmSucceed").readTextBlock(), trapDisarmFail = required("trapDisarmFail").readTextBlock(), pitfallIllustration = optionalNullableString("pitfallIllustration"), @@ -3744,10 +3738,8 @@ private class ExternalRuntimeSystemsReader( private fun JsonObject.readBattleText(): ExternalBattleText = ExternalBattleText( - encounterBanner = required("encounterBanner").readTextBlock(), - youFace = required("youFace").readTextBlock(), - foeDisplayName = required("foeDisplayName").readTextBlock(), - stillFace = required("stillFace").readTextBlock(), + encounter = required("encounter").readTextBlock(), + nextRound = required("nextRound").readTextBlock(), fight = required("fight").readTextBlock(), run = required("run").readTextBlock(), bloodFlow = required("bloodFlow").readTextBlock(), @@ -3775,9 +3767,7 @@ private class ExternalRuntimeSystemsReader( partyHeld = required("partyHeld").readTextBlock(), partyDefeated = required("partyDefeated").readTextBlock(), victoryBested = required("victoryBested").readTextBlock(), - victoryEachSurvivor = required("victoryEachSurvivor").readTextBlock(), victoryReward = required("victoryReward").readTextBlock(), - victoryFoundObject = required("victoryFoundObject").readTextBlock(), victoryLoot = required("victoryLoot").readTextBlock(), levelGain = required("levelGain").readTextBlock(), ) diff --git a/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt b/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt index f8518398..c15c5777 100644 --- a/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt +++ b/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt @@ -107,6 +107,7 @@ val BattleText: rylween.dsl.impl.BattleText get() = rylween.dsl.impl.BattleText val HuntText: rylween.dsl.impl.HuntText get() = rylween.dsl.impl.HuntText val UpkeepText: rylween.dsl.impl.UpkeepText get() = rylween.dsl.impl.UpkeepText val CampText: rylween.dsl.impl.CampText get() = rylween.dsl.impl.CampText +val CastleText: rylween.dsl.impl.CastleText get() = rylween.dsl.impl.CastleText val InventoryText: rylween.dsl.impl.InventoryText get() = rylween.dsl.impl.InventoryText val TownText: rylween.dsl.impl.TownText get() = rylween.dsl.impl.TownText val ShopResources: rylween.dsl.impl.ShopResources get() = rylween.dsl.impl.ShopResources diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 04d3cfd0..1a0067d7 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -191,6 +191,7 @@ private val battleTextBindings: Set = TextPart.BattleLootName, TextPart.BattleLevelMemberName, TextPart.BattleLevelsGained, + TextPart.BattleRoundNumber, ) private val characterCreationStatsTextBindings: Set = setOf( @@ -485,10 +486,8 @@ fun validateCombatSystem( private fun validateBattleText(text: BattleTextModel) { listOf( - "encounter banner" to text.encounterBanner, - "you-face" to text.youFace, - "foe display name" to text.foeDisplayName, - "still-face" to text.stillFace, + "encounter" to text.encounter, + "next round" to text.nextRound, "fight prompt" to text.fight, "run prompt" to text.run, "blood-flow" to text.bloodFlow, @@ -516,9 +515,7 @@ private fun validateBattleText(text: BattleTextModel) { "party held" to text.partyHeld, "party defeated" to text.partyDefeated, "victory bested" to text.victoryBested, - "victory each survivor" to text.victoryEachSurvivor, "victory reward" to text.victoryReward, - "victory found object" to text.victoryFoundObject, "victory loot" to text.victoryLoot, "level gain" to text.levelGain, ).forEach { (label, block) -> @@ -834,7 +831,6 @@ private fun validateCastleText( ) { listOf( "room monster" to text.roomMonster, - "trap disarm suffix" to text.trapTriesDisarmSuffix, "trap disarm succeeds" to text.trapDisarmSucceed, "trap disarm fails" to text.trapDisarmFail, "treasure menu" to text.treasureMenu, @@ -853,6 +849,7 @@ private fun validateCastleText( "give menu" to text.giveMenu, "stairs guardian grateful" to text.stairsGuardianGrateful, ).forEach { (textLabel, block) -> validateTextBlock(block, "$label $textLabel") } + validateTextBlock(text.trapTriesDisarm, "$label trap disarm", allowedRuntimeBindings = setOf(TextPart.CastleThiefName)) text.floorNames.forEachIndexed { index, floor -> check(floor.isNotBlank()) { "$label floor name ${index + 1} is blank" } } @@ -1303,6 +1300,7 @@ private fun validateTextBlock( TextPart.HuntFoodGained, TextPart.UpkeepMemberName, TextPart.CampGuardName, + TextPart.CastleThiefName, TextPart.PartyMemberCount, TextPart.PartyMemberMax, TextPart.WildernessDungeonName, @@ -1328,6 +1326,7 @@ private fun validateTextBlock( TextPart.BattleLootName, TextPart.BattleLevelMemberName, TextPart.BattleLevelsGained, + TextPart.BattleRoundNumber, -> check(part in allowedRuntimeBindings) { "$label uses runtime text binding ${part.fallbackText()}, but this text is not rendered with that binding" diff --git a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt index 25122b7d..b2f0d568 100644 --- a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt +++ b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt @@ -470,6 +470,7 @@ private class NativePathCollector { TextPart.HuntFoodGained, TextPart.UpkeepMemberName, TextPart.CampGuardName, + TextPart.CastleThiefName, TextPart.PartyMemberCount, TextPart.PartyMemberMax, TextPart.WildernessDungeonName, @@ -495,6 +496,7 @@ private class NativePathCollector { TextPart.BattleLootName, TextPart.BattleLevelMemberName, TextPart.BattleLevelsGained, + TextPart.BattleRoundNumber, -> Unit } } diff --git a/core/src/main/kotlin/rylween/dsl/TextDsl.kt b/core/src/main/kotlin/rylween/dsl/TextDsl.kt index cda6a889..fe0ce120 100644 --- a/core/src/main/kotlin/rylween/dsl/TextDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/TextDsl.kt @@ -110,6 +110,9 @@ sealed interface TextPart { /** Name of the party member who stands guard while the party camps. */ object CampGuardName : TextPart + /** Name of the thief who tries to disarm a castle trap. */ + object CastleThiefName : TextPart + object PartyMemberCount : TextPart object PartyMemberMax : TextPart @@ -159,6 +162,8 @@ sealed interface TextPart { object BattleLevelMemberName : TextPart object BattleLevelsGained : TextPart + + object BattleRoundNumber : TextPart } /** Returns a deterministic placeholder used when no runtime renderer is available. */ @@ -190,6 +195,7 @@ fun TextPart.fallbackText(): String = TextPart.HuntFoodGained -> "{hunt_food_gained}" TextPart.UpkeepMemberName -> "{upkeep_member_name}" TextPart.CampGuardName -> "{camp_guard_name}" + TextPart.CastleThiefName -> "{castle_thief_name}" TextPart.PartyMemberCount -> "{party_count}" TextPart.PartyMemberMax -> "{party_max}" TextPart.WildernessDungeonName -> "{dungeon}" @@ -215,6 +221,7 @@ fun TextPart.fallbackText(): String = TextPart.BattleLootName -> "{battle_loot}" TextPart.BattleLevelMemberName -> "{battle_level_member}" TextPart.BattleLevelsGained -> "{battle_levels}" + TextPart.BattleRoundNumber -> "{battle_round}" } /** Structured text line made of literal and dynamic parts. */ diff --git a/core/src/main/kotlin/rylween/dsl/impl/CastleDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/CastleDsl.kt index a7a56a80..17bfa8e9 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/CastleDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/CastleDsl.kt @@ -118,7 +118,7 @@ data class CastleScriptsModel( /** Text prompts and narration used by the castle runtime session. */ data class CastleTextModel( val roomMonster: TextBlock = literalText(), - val trapTriesDisarmSuffix: TextBlock = literalText(), + val trapTriesDisarm: TextBlock = literalText(), val trapDisarmSucceed: TextBlock = literalText(), val trapDisarmFail: TextBlock = literalText(), val pitfallIllustration: ImageId? = null, @@ -479,7 +479,9 @@ class CastleTextBuilder( initial: CastleTextModel = CastleTextModel(), ) { var roomMonster: TextBlock = initial.roomMonster - var trapTriesDisarmSuffix: TextBlock = initial.trapTriesDisarmSuffix + + /** The line a thief tries a trap with, naming them with [CastleText.thiefName]. */ + var trapTriesDisarm: TextBlock = initial.trapTriesDisarm var trapDisarmSucceed: TextBlock = initial.trapDisarmSucceed var trapDisarmFail: TextBlock = initial.trapDisarmFail var pitfallIllustration: ImageId? = initial.pitfallIllustration @@ -510,7 +512,7 @@ class CastleTextBuilder( fun build(): CastleTextModel = CastleTextModel( roomMonster = roomMonster, - trapTriesDisarmSuffix = trapTriesDisarmSuffix, + trapTriesDisarm = trapTriesDisarm, trapDisarmSucceed = trapDisarmSucceed, trapDisarmFail = trapDisarmFail, pitfallIllustration = pitfallIllustration, diff --git a/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt index aa9bf551..d61bc1b9 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt @@ -52,10 +52,8 @@ data class BattleOpeningKeysModel( ) data class BattleTextModel( - val encounterBanner: TextBlock, - val youFace: TextBlock, - val foeDisplayName: TextBlock, - val stillFace: TextBlock, + val encounter: TextBlock, + val nextRound: TextBlock, val fight: TextBlock, val run: TextBlock, val bloodFlow: TextBlock, @@ -83,9 +81,7 @@ data class BattleTextModel( val partyHeld: TextBlock, val partyDefeated: TextBlock, val victoryBested: TextBlock, - val victoryEachSurvivor: TextBlock, val victoryReward: TextBlock, - val victoryFoundObject: TextBlock, val victoryLoot: TextBlock, val levelGain: TextBlock, ) @@ -156,6 +152,7 @@ object BattleText { val lootName: TextPart = TextPart.BattleLootName val levelMemberName: TextPart = TextPart.BattleLevelMemberName val levelsGained: TextPart = TextPart.BattleLevelsGained + val roundNumber: TextPart = TextPart.BattleRoundNumber } /** @@ -302,10 +299,8 @@ class BattleOpeningKeysBuilder( class BattleTextBuilder( initial: BattleTextModel? = null, ) { - private var encounterBannerText = initial?.encounterBanner - private var youFaceText = initial?.youFace - private var foeDisplayNameText = initial?.foeDisplayName - private var stillFaceText = initial?.stillFace + private var encounterText = initial?.encounter + private var nextRoundText = initial?.nextRound private var fightText = initial?.fight private var runText = initial?.run private var bloodFlowText = initial?.bloodFlow @@ -333,26 +328,18 @@ class BattleTextBuilder( private var partyHeldText = initial?.partyHeld private var partyDefeatedText = initial?.partyDefeated private var victoryBestedText = initial?.victoryBested - private var victoryEachSurvivorText = initial?.victoryEachSurvivor private var victoryRewardText = initial?.victoryReward - private var victoryFoundObjectText = initial?.victoryFoundObject private var victoryLootText = initial?.victoryLoot private var levelGainText = initial?.levelGain - fun encounterBanner(body: StructuredTextBlockBuilder.() -> Unit) { - encounterBannerText = literalText(body) + /** The page that opens a battle, naming the foes with [BattleText.foeDisplayName]. */ + fun encounter(body: StructuredTextBlockBuilder.() -> Unit) { + encounterText = literalText(body) } - fun youFace(body: StructuredTextBlockBuilder.() -> Unit) { - youFaceText = literalText(body) - } - - fun foeDisplayName(body: StructuredTextBlockBuilder.() -> Unit) { - foeDisplayNameText = literalText(body) - } - - fun stillFace(body: StructuredTextBlockBuilder.() -> Unit) { - stillFaceText = literalText(body) + /** The page each later round opens with: [BattleText.roundNumber] and the foes still standing. */ + fun nextRound(body: StructuredTextBlockBuilder.() -> Unit) { + nextRoundText = literalText(body) } fun fight(body: StructuredTextBlockBuilder.() -> Unit) { @@ -503,18 +490,10 @@ class BattleTextBuilder( victoryBestedText = text } - fun victoryEachSurvivor(body: StructuredTextBlockBuilder.() -> Unit) { - victoryEachSurvivorText = literalText(body) - } - fun victoryReward(body: StructuredTextBlockBuilder.() -> Unit) { victoryRewardText = literalText(body) } - fun victoryFoundObject(body: StructuredTextBlockBuilder.() -> Unit) { - victoryFoundObjectText = literalText(body) - } - fun victoryLoot(body: StructuredTextBlockBuilder.() -> Unit) { victoryLootText = literalText(body) } @@ -525,10 +504,8 @@ class BattleTextBuilder( fun build(): BattleTextModel = BattleTextModel( - encounterBanner = requiredStandardBattleText(encounterBannerText, "encounterBanner"), - youFace = requiredStandardBattleText(youFaceText, "youFace"), - foeDisplayName = requiredStandardBattleText(foeDisplayNameText, "foeDisplayName"), - stillFace = requiredStandardBattleText(stillFaceText, "stillFace"), + encounter = requiredStandardBattleText(encounterText, "encounter"), + nextRound = requiredStandardBattleText(nextRoundText, "nextRound"), fight = requiredStandardBattleText(fightText, "fight"), run = requiredStandardBattleText(runText, "run"), bloodFlow = requiredStandardBattleText(bloodFlowText, "bloodFlow"), @@ -556,9 +533,7 @@ class BattleTextBuilder( partyHeld = requiredStandardBattleText(partyHeldText, "partyHeld"), partyDefeated = requiredStandardBattleText(partyDefeatedText, "partyDefeated"), victoryBested = requiredStandardBattleText(victoryBestedText, "victoryBested"), - victoryEachSurvivor = requiredStandardBattleText(victoryEachSurvivorText, "victoryEachSurvivor"), victoryReward = requiredStandardBattleText(victoryRewardText, "victoryReward"), - victoryFoundObject = requiredStandardBattleText(victoryFoundObjectText, "victoryFoundObject"), victoryLoot = requiredStandardBattleText(victoryLootText, "victoryLoot"), levelGain = requiredStandardBattleText(levelGainText, "levelGain"), ) diff --git a/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt index 20f68236..849fca22 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt @@ -413,6 +413,12 @@ object CampText { val guardName: TextPart = TextPart.CampGuardName } +/** Runtime placeholders available to authored castle messages. */ +object CastleText { + /** The thief who tries to disarm a trap. */ + val thiefName: TextPart = TextPart.CastleThiefName +} + /** Runtime placeholders available to authored wilderness upkeep messages. */ object UpkeepText { /** The current party member affected by an upkeep effect. */ diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 9bba74e1..7516f5ef 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -589,7 +589,11 @@ val authoredRylween: RylweenModel = text { floorNames("(Ground Level)", "(First Floor)", "(Base of Tower)", "(Top of Tower)") roomMonster = flowText("You are spotted by monsters!") - trapTriesDisarmSuffix = literalText("tries to disarm it...", "") + trapTriesDisarm = + literalText { + line(CastleText.thiefName, " tries to disarm it...") + line("") + } trapDisarmSucceed = literalText("AND SUCCEEDS!") trapDisarmFail = literalText("BUT FAILS!") treasureIllustration = Images.Castle.treasure @@ -795,7 +799,7 @@ val authoredRylween: RylweenModel = dropPrompt = literalText("Drop what?") dropEmptySlot = literalText("Nothing to drop.") dropAborted = literalText("Aborted.") - dropped(flowText("You drop the ", TextPart.SelectedItemName, ".")) + dropped(flowText("You drop the ", InventoryText.itemName, ".")) dropCapacityReduced = flowText("You are forced to leave some of your food behind...") killsHeader = literalText("MONSTERS SLAIN", "") killsEmpty = literalText("No monsters slain yet.") @@ -1455,13 +1459,19 @@ val authoredRylween: RylweenModel = // Battle text uses typed placeholders such as attackerName // and damage so the runtime does not assemble prose itself. text { - encounterBanner { lines("ENCOUNTER!", "") } - youFace { line("You face") } - foeDisplayName { + encounter { + lines("ENCOUNTER!", "") + line("You face") + line(BattleText.foeDisplayName) + line("") + } + nextRound { + line("Round ", BattleText.roundNumber) + line("") + line("You still face") line(BattleText.foeDisplayName) line("") } - stillFace { line("You still face") } fight { line("(F)ight") } fleeOption { line("(R)un") } bloodFlow { line("Blood shall flow!") } @@ -1500,13 +1510,15 @@ val authoredRylween: RylweenModel = partyHeld { line("PARTY IS HELD!") } partyDefeated { line("The party has fallen.") } victoryBested(flowText("Thou hast bested thy foes.")) - victoryEachSurvivor { line("Each survivor gets") } victoryReward { + line("Each survivor gets") line(BattleText.experience, " experience pts and ", BattleText.gold, " gold pieces.") line("") } - victoryFoundObject { line("You find a") } - victoryLoot { line(BattleText.lootName, ".") } + victoryLoot { + line("You find a") + line(BattleText.lootName, ".") + } levelGain { line(BattleText.levelMemberName, " gains >", BattleText.levelsGained, "< experience levels.") } diff --git a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt index a9e387e1..06932d21 100644 --- a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt +++ b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt @@ -2458,7 +2458,7 @@ class RylweenCompiledGameLedgerTest { } check( "nextRoundDecision" in battleRunnerSource && - "Round $" + "roundNumber" in battleRunnerSource && + "BATTLE_ROUND_NUMBER to roundNumber" in battleRunnerSource && "rules.openingKeys.run.matches(choice) -> return attemptDesperateRun(this)" in battleRunnerSource, ) { "battle runner must offer Fight/Run decisions with round numbers after completed rounds" diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt index 436fb301..121f7654 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt @@ -74,6 +74,7 @@ private const val BATTLE_GOLD = "battleGold" private const val BATTLE_LOOT_NAME = "battleLootName" private const val BATTLE_LEVEL_MEMBER_NAME = "battleLevelMemberName" private const val BATTLE_LEVELS_GAINED = "battleLevelsGained" +private const val BATTLE_ROUND_NUMBER = "battleRoundNumber" private const val BATTLE_MESSAGE_PAGE_LINES = 4 private const val BATTLE_VICTORY_PAGE_LINES = 7 @@ -362,9 +363,7 @@ internal class BattleRunner( private fun ExternalStandardBattle.openingText(encounter: BattleEncounter): List = screen.choiceMenuLines( - text.encounterBanner.renderBattle() + - text.youFace.renderBattle() + - text.foeDisplayName.renderBattle(BATTLE_FOE_DISPLAY_NAME to encounter.foeDisplayName()), + text.encounter.renderBattle(BATTLE_FOE_DISPLAY_NAME to encounter.foeDisplayName()), text.fight.renderBattle() + text.run.renderBattle(), ) @@ -393,9 +392,10 @@ internal class BattleRunner( roundNumber: Int, ): List = screen.choiceMenuLines( - listOf("Round $roundNumber", "") + - text.stillFace.renderBattle() + - text.foeDisplayName.renderBattle(BATTLE_FOE_DISPLAY_NAME to encounter.foeDisplayName()), + text.nextRound.renderBattle( + BATTLE_ROUND_NUMBER to roundNumber.toString(), + BATTLE_FOE_DISPLAY_NAME to encounter.foeDisplayName(), + ), text.fight.renderBattle() + text.run.renderBattle(), ) @@ -782,16 +782,14 @@ internal class BattleRunner( buildList { addAll(rules.text.victoryBested.renderBattle()) addAll( - rules.text.victoryEachSurvivor.renderBattle() + - rules.text.victoryReward.renderBattle( - BATTLE_EXPERIENCE to experience.toString(), - BATTLE_GOLD to gold.toString(), - ), + rules.text.victoryReward.renderBattle( + BATTLE_EXPERIENCE to experience.toString(), + BATTLE_GOLD to gold.toString(), + ), ) loot?.let { item -> addAll( - rules.text.victoryFoundObject.renderBattle() + - rules.text.victoryLoot.renderBattle(BATTLE_LOOT_NAME to item.displayName()), + rules.text.victoryLoot.renderBattle(BATTLE_LOOT_NAME to item.displayName()), ) } levelUps.gains.forEach { gain -> diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt index ba038b73..099c6ab8 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt @@ -220,10 +220,10 @@ internal class CastleRuntime( .takeIf { index -> index >= 0 } ?.let { index -> val thief = next.party.members[index] - // The suffix continues the thief's name, so the first of its lines joins the name's. - val suffix = castle.text.trapTriesDisarmSuffix.renderCastle(screen.textColumns) - val tries = next.party.memberName(content, index) + suffix.firstOrNull()?.let { line -> " $line" }.orEmpty() - screen.writeText(listOf(tries) + suffix.drop(1)) + val thiefName = next.party.memberName(content, index) + screen.writeText( + castle.text.trapTriesDisarm.render({ kind -> thiefName.takeIf { kind == "castleThiefName" } }, screen.textColumns), + ) val disarmChance = content.evalFormula(castle.pitfall.disarmChance, next.party, thief.statBindings()) val draw = disarmChance.party.drawRandom(0, 99) next = next.withParty(draw.party) From 6e05bb0ac3d9dbf1b71d1b22bf90e537af5b53f9 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:17 +0100 Subject: [PATCH 09/16] Name castle scenes by handle and list the guardian's items 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. --- .../compiled/ExternalBundleArtifact.kt | 6 ++--- .../main/kotlin/rylween/dsl/DslValidation.kt | 2 +- .../main/kotlin/rylween/dsl/impl/CastleDsl.kt | 8 +++--- .../main/kotlin/rylween/game/RylweenAudio.kt | 2 +- .../main/kotlin/rylween/game/RylweenGame.kt | 27 +++++++------------ .../rylween/RylweenCompiledGameLedgerTest.kt | 8 +++--- .../kotlin/rylween/runtime/CastleRuntime.kt | 15 ++++++++--- .../test/kotlin/rylween/runtime/Autopilot.kt | 4 ++- 8 files changed, 37 insertions(+), 35 deletions(-) diff --git a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index 65c1391b..2c87331f 100644 --- a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt +++ b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt @@ -1131,7 +1131,7 @@ data class ExternalCastleText( val stairsLeave: ExternalRuntimeTextBlock, val teleportVortex: ExternalRuntimeTextBlock, val teleportOutside: ExternalRuntimeTextBlock, - val giveMenu: ExternalRuntimeTextBlock, + val givePrompt: ExternalRuntimeTextBlock, val stairsGuardianGrateful: ExternalRuntimeTextBlock, val floorNames: List, ) @@ -2510,7 +2510,7 @@ private class ExternalBundleArtifactWriter { "stairsLeave" to textBlockJson(text.stairsLeave), "teleportVortex" to textBlockJson(text.teleportVortex), "teleportOutside" to textBlockJson(text.teleportOutside), - "giveMenu" to textBlockJson(text.giveMenu), + "givePrompt" to textBlockJson(text.givePrompt), "stairsGuardianGrateful" to textBlockJson(text.stairsGuardianGrateful), "floorNames" to JsonArray(text.floorNames.map(::JsonString)), ) @@ -3502,7 +3502,7 @@ private class ExternalRuntimeSystemsReader( stairsLeave = required("stairsLeave").readTextBlock(), teleportVortex = required("teleportVortex").readTextBlock(), teleportOutside = required("teleportOutside").readTextBlock(), - giveMenu = required("giveMenu").readTextBlock(), + givePrompt = required("givePrompt").readTextBlock(), stairsGuardianGrateful = required("stairsGuardianGrateful").readTextBlock(), floorNames = requiredArray("floorNames").values.map { value -> value.asString("castle floor name") }, ) diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 1a0067d7..7a3fa3dc 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -846,7 +846,7 @@ private fun validateCastleText( "stairs leave" to text.stairsLeave, "teleport vortex" to text.teleportVortex, "teleport outside" to text.teleportOutside, - "give menu" to text.giveMenu, + "give prompt" to text.givePrompt, "stairs guardian grateful" to text.stairsGuardianGrateful, ).forEach { (textLabel, block) -> validateTextBlock(block, "$label $textLabel") } validateTextBlock(text.trapTriesDisarm, "$label trap disarm", allowedRuntimeBindings = setOf(TextPart.CastleThiefName)) diff --git a/core/src/main/kotlin/rylween/dsl/impl/CastleDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/CastleDsl.kt index 17bfa8e9..62387f84 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/CastleDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/CastleDsl.kt @@ -137,7 +137,7 @@ data class CastleTextModel( val stairsLeave: TextBlock = literalText(), val teleportVortex: TextBlock = literalText(), val teleportOutside: TextBlock = literalText(), - val giveMenu: TextBlock = literalText(), + val givePrompt: TextBlock = literalText(), val stairsGuardianGrateful: TextBlock = literalText(), val floorNames: List = emptyList(), ) @@ -500,7 +500,9 @@ class CastleTextBuilder( var stairsLeave: TextBlock = initial.stairsLeave var teleportVortex: TextBlock = initial.teleportVortex var teleportOutside: TextBlock = initial.teleportOutside - var giveMenu: TextBlock = initial.giveMenu + + /** The question above the stairs items the party can give; the runtime lists the items and RETURN leaves. */ + var givePrompt: TextBlock = initial.givePrompt var stairsGuardianGrateful: TextBlock = initial.stairsGuardianGrateful private val floorNames = initial.floorNames.toMutableList() @@ -531,7 +533,7 @@ class CastleTextBuilder( stairsLeave = stairsLeave, teleportVortex = teleportVortex, teleportOutside = teleportOutside, - giveMenu = giveMenu, + givePrompt = givePrompt, stairsGuardianGrateful = stairsGuardianGrateful, floorNames = floorNames.toList(), ) diff --git a/game/src/main/kotlin/rylween/game/RylweenAudio.kt b/game/src/main/kotlin/rylween/game/RylweenAudio.kt index 6741206c..b8b0a4c8 100644 --- a/game/src/main/kotlin/rylween/game/RylweenAudio.kt +++ b/game/src/main/kotlin/rylween/game/RylweenAudio.kt @@ -479,6 +479,6 @@ val rylweenAudio: GameSection = scene(Scenes.Towne.smith, Music.smithForge) scene(Scenes.Towne.merchant, Music.merchantShop) scene(Scenes.Towne.hut, Music.hutFireside) - scene(sceneId("castle.ydarg.completed"), Music.ending) + scene(Scenes.Castle.ydargCompleted, Music.ending) } } diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 7516f5ef..e7ce8f07 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -578,10 +578,10 @@ val authoredRylween: RylweenModel = // Script ids are story hooks invoked by the castle runner at // entry, completion, and blocked/already-complete branches. scripts { - alreadyCompleted = sceneId("castle.ydarg.already_completed") - entryBlocked = sceneId("castle.ydarg.entry_blocked") - entered = sceneId("castle.ydarg.entered") - completed = sceneId("castle.ydarg.completed") + alreadyCompleted = Scenes.Castle.ydargAlreadyCompleted + entryBlocked = Scenes.Castle.ydargEntryBlocked + entered = Scenes.Castle.ydargEntered + completed = Scenes.Castle.ydargCompleted } // Text rows are castle-specific prompts, menus, labels, images, @@ -619,16 +619,7 @@ val authoredRylween: RylweenModel = stairsLeave = literalText("You take the nearest exit!") teleportVortex = flowText("The world fades into a vortex of agonizing vertigo...") teleportOutside = literalText("And you are outside...") - giveMenu = - literalText( - "Give him what?", - "", - "1. The Fire Shield", - "2. The Master Crown", - "3. The Foot of Jazzy", - "4. The Bracelets of Thun", - "5. Nothing", - ) + givePrompt = literalText("Give him what?", "") stairsGuardianGrateful = flowText( """ @@ -3887,7 +3878,7 @@ val authoredRylween: RylweenModel = // Castle scenes are script roots named from the castle model above. // They keep the story beats authored while the castle runner stays generic. - scene(sceneId("castle.ydarg.already_completed")) { + scene(Scenes.Castle.ydargAlreadyCompleted) { showBackdrop(Images.Backdrop.ydargCastle) writeText( flowText( @@ -3899,7 +3890,7 @@ val authoredRylween: RylweenModel = waitInput("after the ruined castle") } - scene(sceneId("castle.ydarg.entry_blocked")) { + scene(Scenes.Castle.ydargEntryBlocked) { showBackdrop(Images.Backdrop.ydargCastle) showBackdrop(Images.Castle.jaaraGate) writeText( @@ -3922,7 +3913,7 @@ val authoredRylween: RylweenModel = waitInput("after Jaara blocks the gate") } - scene(sceneId("castle.ydarg.entered")) { + scene(Scenes.Castle.ydargEntered) { showBackdrop(Images.Backdrop.ydargCastle) showBackdrop(Images.Castle.jaaraGate) writeText( @@ -3955,7 +3946,7 @@ val authoredRylween: RylweenModel = waitInput("after entering castle Ydarg") } - scene(sceneId("castle.ydarg.completed")) { + scene(Scenes.Castle.ydargCompleted) { showTextAndWait( """ The last trapdoor slams shut behind you. You are high above the forest, on the roof of this fortress. Suddenly, a voice speaks: diff --git a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt index 06932d21..ee3f7677 100644 --- a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt +++ b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt @@ -491,7 +491,7 @@ class RylweenCompiledGameLedgerTest { check(castleContent.entryRequirement == Milestones.silverKey) check(castleContent.completionMilestone == Milestones.ydargVictory) check(castleContent.pitfall.disarmChance == Formulas.castleTrapDisarmChance) - check(castleContent.scripts.completed?.slug == "castle.ydarg.completed") + check(castleContent.scripts.completed?.slug == "castle.ydarg_completed") check(castleContent.text.stairsIllustration?.slug == "blitgfx.castle_stairs_guardians") check( runtimeSystems.castleRows @@ -546,7 +546,7 @@ class RylweenCompiledGameLedgerTest { RuntimeCommandActionId.Save.id to "Save Game", ), ) - listOf("castle.ydarg.entry_blocked", "castle.ydarg.entered").forEach { sceneSlug -> + listOf("castle.ydarg_entry_blocked", "castle.ydarg_entered").forEach { sceneSlug -> val scene = nextDsl.scenes.single { it.id.slug == sceneSlug } val firstScreen = scene.statementNodes.first { op -> op is ScriptStatementNode.Screen } as ScriptStatementNode.Screen check("Jaara" in firstScreen.text.fallbackText()) { @@ -567,7 +567,7 @@ class RylweenCompiledGameLedgerTest { ) check( nextDsl.scenes - .single { it.id.slug == "castle.ydarg.completed" } + .single { it.id.slug == "castle.ydarg_completed" } .statementNodes .filterIsInstance() .map { it.foe } == @@ -2943,7 +2943,7 @@ class RylweenCompiledGameLedgerTest { "characters {", "monsters {", "missions {", - "scene(sceneId(\"castle.ydarg.already_completed\")) {", + "scene(Scenes.Castle.ydargAlreadyCompleted) {", "scene(Scenes.Towne.church) {", "scene(Scenes.Missions.erethorEntry) {", "dialogue {", diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt index 099c6ab8..60af782a 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt @@ -350,11 +350,18 @@ internal class CastleRuntime( runtime: RuntimeState, castle: ExternalRuntimeCastle, ): RuntimeState { - val lines = castle.text.giveMenu.renderCastle(screen.textColumns) + val lines = + screen.choiceMenuLines( + castle.text.givePrompt.renderCastle(screen.textColumns), + castle.stairs.items.map { stair -> choiceLine(stair.digit, stair.itemName) }, + listOf(systems.prompts.returnLeavesLine()), + ) screen.writeText(lines) - val digits = (castle.stairs.items.map { stair -> stair.digit } + 5).toSet() - val digit = input.readValidDigitChoice(screen, lines, digits, audio = audio) ?: return runtime - if (digit == 5) return runtime + val digits = + castle.stairs.items + .map { stair -> stair.digit } + .toSet() + val digit = input.readValidDigitChoice(screen, lines, digits, cancelKeys = setOf('\n'), audio = audio) ?: return runtime val item = castle.stairs.items.firstOrNull { stair -> stair.digit == digit } ?: return runtime val milestone = content.ref(CompiledHandleKind.Milestone, item.milestone) if (milestone !in runtime.party.milestones) { diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/Autopilot.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/Autopilot.kt index e97a138d..52358a8b 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/Autopilot.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/Autopilot.kt @@ -410,7 +410,9 @@ internal class Autopilot( val key = stairs.key(choice) return key.also { coverage.recordKey(stairsGroup, it) } } - lines.any { line -> line.trimStart().startsWith("1.") } -> return stairsItemDigit(state, castle) + castle.text.givePrompt + .render { null } + .first() in lines -> return stairsItemDigit(state, castle) lines.offers(treasure.binding(RuntimeCommandActionId.Take)) -> { val take = party.freeSlots(state.party) >= TREASURE_FREE_SLOTS && !tour.leavesTreasure() val key = treasure.key(if (take) RuntimeCommandActionId.Take else RuntimeCommandActionId.Leave) From 25f9a0a7be5c74e284b7bd12e54cefbd0ea93a60 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:17 +0100 Subject: [PATCH 10/16] Share one random event mix across dungeons 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. --- core/src/main/kotlin/rylween/dsl/Dsl.kt | 28 +++- .../main/kotlin/rylween/game/RylweenGame.kt | 125 +++--------------- 2 files changed, 45 insertions(+), 108 deletions(-) diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index e6f3dd35..065155be 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -2620,6 +2620,12 @@ class DungeonSystemBuilder { private val scenarios = mutableListOf() private var backdrop: ImageId? = null private var keys = DungeonKeysModel() + private var defaultRandomEvents = emptyList() + + /** The random-event mix of every scenario that names none of its own. */ + fun randomEvents(vararg events: Pair) { + defaultRandomEvents = events.map { (event, weight) -> DungeonRandomEventModel(event, weight) } + } fun backdrop(image: ImageId?) { backdrop = image @@ -2646,7 +2652,11 @@ class DungeonSystemBuilder { fun build(): DungeonSystemModel = DungeonSystemModel( events = events.toList(), - scenarios = scenarios.toList(), + scenarios = + scenarios.map { scenario -> + scenario.takeUnless { it.randomEvents.isEmpty() } + ?: scenario.copy(randomEvents = defaultRandomEvents) + }, backdrop = backdrop, keys = keys, ) @@ -2790,6 +2800,22 @@ class DungeonScenarioBuilder( fixedLevelEvents[number] = event } + /** The same fixed event on each of [numbers], such as `level(13..19, DungeonEvents.colorRiddle)`. */ + fun level( + numbers: IntRange, + event: DungeonEventId, + ) { + numbers.forEach { number -> level(number, event) } + } + + /** The same fixed event on each of [numbers], such as `level(3, 6, 9, event = DungeonEvents.hobgoblinPatrol)`. */ + fun level( + vararg numbers: Int, + event: DungeonEventId, + ) { + numbers.forEach { number -> level(number, event) } + } + fun randomEvents(body: DungeonRandomEventPoolBuilder.() -> Unit) { randomEvents += DungeonRandomEventPoolBuilder().apply(body).build() } diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index e7ce8f07..d0d42ccb 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -2343,35 +2343,28 @@ val authoredRylween: RylweenModel = } } - // Scenarios map a dungeon id to depth, random-event weights, and - // fixed levels that override the random mix. + // Every dungeon draws the levels without a fixed event from this + // weighted mix, unless its scenario names a mix of its own. + randomEvents( + DungeonEvents.findObject to 1, + DungeonEvents.gold to 1, + DungeonEvents.weakEncounter to 2, + DungeonEvents.deepEncounter to 1, + DungeonEvents.nothingSpecial to 1, + DungeonEvents.emptyLevel to 1, + DungeonEvents.goldChest to 1, + DungeonEvents.torches to 1, + ) + + // Scenarios map a dungeon id to depth and the fixed levels that + // override the random mix. scenario(Dungeons.randomCave) { name("Random Cave") - randomEvents( - DungeonEvents.findObject to 1, - DungeonEvents.gold to 1, - DungeonEvents.weakEncounter to 2, - DungeonEvents.deepEncounter to 1, - DungeonEvents.nothingSpecial to 1, - DungeonEvents.emptyLevel to 1, - DungeonEvents.goldChest to 1, - DungeonEvents.torches to 1, - ) } scenario(Dungeons.fireShieldCave) { name("Fire Shield Cave") levels(20) - randomEvents( - DungeonEvents.findObject to 1, - DungeonEvents.gold to 1, - DungeonEvents.weakEncounter to 2, - DungeonEvents.deepEncounter to 1, - DungeonEvents.nothingSpecial to 1, - DungeonEvents.emptyLevel to 1, - DungeonEvents.goldChest to 1, - DungeonEvents.torches to 1, - ) level(19, DungeonEvents.fireShieldGuardian) level(20, DungeonEvents.fireShield) } @@ -2379,16 +2372,6 @@ val authoredRylween: RylweenModel = scenario(Dungeons.thunTemple) { name("Thun Temple") levels(18) - randomEvents( - DungeonEvents.findObject to 1, - DungeonEvents.gold to 1, - DungeonEvents.weakEncounter to 2, - DungeonEvents.deepEncounter to 1, - DungeonEvents.nothingSpecial to 1, - DungeonEvents.emptyLevel to 1, - DungeonEvents.goldChest to 1, - DungeonEvents.torches to 1, - ) level(4, DungeonEvents.thunRiddle1) level(8, DungeonEvents.thunRiddle2) level(12, DungeonEvents.thunRiddle3) @@ -2398,78 +2381,27 @@ val authoredRylween: RylweenModel = scenario(Dungeons.reebarTomb) { name("Reebar Tomb") levels(20) - randomEvents( - DungeonEvents.findObject to 1, - DungeonEvents.gold to 1, - DungeonEvents.weakEncounter to 2, - DungeonEvents.deepEncounter to 1, - DungeonEvents.nothingSpecial to 1, - DungeonEvents.emptyLevel to 1, - DungeonEvents.goldChest to 1, - DungeonEvents.torches to 1, - ) level(12, DungeonEvents.spectrumMessage) - level(13, DungeonEvents.colorRiddle) - level(14, DungeonEvents.colorRiddle) - level(15, DungeonEvents.colorRiddle) - level(16, DungeonEvents.colorRiddle) - level(17, DungeonEvents.colorRiddle) - level(18, DungeonEvents.colorRiddle) - level(19, DungeonEvents.colorRiddle) + level(13..19, DungeonEvents.colorRiddle) level(20, DungeonEvents.nolrimTomb) } scenario(Dungeons.masterCrownDungeon) { name("Master Crown Dungeon") levels(10) - randomEvents( - DungeonEvents.findObject to 1, - DungeonEvents.gold to 1, - DungeonEvents.weakEncounter to 2, - DungeonEvents.deepEncounter to 1, - DungeonEvents.nothingSpecial to 1, - DungeonEvents.emptyLevel to 1, - DungeonEvents.goldChest to 1, - DungeonEvents.torches to 1, - ) level(10, DungeonEvents.masterCrown) } scenario(Dungeons.silverSanctum) { name("Silver Sanctum") levels(20) - randomEvents( - DungeonEvents.findObject to 1, - DungeonEvents.gold to 1, - DungeonEvents.weakEncounter to 2, - DungeonEvents.deepEncounter to 1, - DungeonEvents.nothingSpecial to 1, - DungeonEvents.emptyLevel to 1, - DungeonEvents.goldChest to 1, - DungeonEvents.torches to 1, - ) level(20, DungeonEvents.silverSanctum) } scenario(Dungeons.hobgoblinStronghold) { name("Hobgoblin Stronghold") levels(22) - randomEvents( - DungeonEvents.findObject to 1, - DungeonEvents.gold to 1, - DungeonEvents.weakEncounter to 2, - DungeonEvents.deepEncounter to 1, - DungeonEvents.nothingSpecial to 1, - DungeonEvents.emptyLevel to 1, - DungeonEvents.goldChest to 1, - DungeonEvents.torches to 1, - ) - level(3, DungeonEvents.hobgoblinPatrol) - level(6, DungeonEvents.hobgoblinPatrol) - level(9, DungeonEvents.hobgoblinPatrol) - level(14, DungeonEvents.hobgoblinPatrol) - level(17, DungeonEvents.hobgoblinPatrol) - level(19, DungeonEvents.hobgoblinPatrol) + level(3, 6, 9, 14, 17, 19, event = DungeonEvents.hobgoblinPatrol) level(20, DungeonEvents.royalGuard1) level(21, DungeonEvents.royalGuard2) level(22, DungeonEvents.hobgoblinChief) @@ -2478,16 +2410,6 @@ val authoredRylween: RylweenModel = scenario(Dungeons.ogreCave) { name("Ogre Cave") levels(7) - randomEvents( - DungeonEvents.findObject to 1, - DungeonEvents.gold to 1, - DungeonEvents.weakEncounter to 2, - DungeonEvents.deepEncounter to 1, - DungeonEvents.nothingSpecial to 1, - DungeonEvents.emptyLevel to 1, - DungeonEvents.goldChest to 1, - DungeonEvents.torches to 1, - ) level(6, DungeonEvents.orcNest) level(7, DungeonEvents.tammysPrison) } @@ -2495,18 +2417,7 @@ val authoredRylween: RylweenModel = scenario(Dungeons.erethorTemple) { name("Erethor Temple") levels(12) - randomEvents( - DungeonEvents.findObject to 1, - DungeonEvents.gold to 1, - DungeonEvents.weakEncounter to 2, - DungeonEvents.deepEncounter to 1, - DungeonEvents.nothingSpecial to 1, - DungeonEvents.emptyLevel to 1, - DungeonEvents.goldChest to 1, - DungeonEvents.torches to 1, - ) - level(3, DungeonEvents.erethorPriests) - level(7, DungeonEvents.erethorPriests) + level(3, 7, event = DungeonEvents.erethorPriests) level(12, DungeonEvents.luteChamber) } } From 74841f1191317dc826a0c9776ac083848d93565d Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:17 +0100 Subject: [PATCH 11/16] Add party and reward item placeholders 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". --- .../kotlin/rylween/dsl/AuthoringFacade.kt | 1 + core/src/main/kotlin/rylween/dsl/Dsl.kt | 3 ++ .../main/kotlin/rylween/dsl/DslValidation.kt | 6 ++-- .../rylween/dsl/impl/RuntimeContentDsl.kt | 2 +- .../rylween/dsl/impl/WorldContentDsl.kt | 11 ++++-- .../main/kotlin/rylween/game/RylweenGame.kt | 34 +++++++++---------- .../rylween/runtime/ScriptExecutorTest.kt | 14 ++++++++ 7 files changed, 48 insertions(+), 23 deletions(-) diff --git a/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt b/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt index c15c5777..3f34dff3 100644 --- a/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt +++ b/core/src/main/kotlin/rylween/dsl/AuthoringFacade.kt @@ -107,6 +107,7 @@ val BattleText: rylween.dsl.impl.BattleText get() = rylween.dsl.impl.BattleText val HuntText: rylween.dsl.impl.HuntText get() = rylween.dsl.impl.HuntText val UpkeepText: rylween.dsl.impl.UpkeepText get() = rylween.dsl.impl.UpkeepText val CampText: rylween.dsl.impl.CampText get() = rylween.dsl.impl.CampText +val PartyText: rylween.dsl.impl.PartyText get() = rylween.dsl.impl.PartyText val CastleText: rylween.dsl.impl.CastleText get() = rylween.dsl.impl.CastleText val InventoryText: rylween.dsl.impl.InventoryText get() = rylween.dsl.impl.InventoryText val TownText: rylween.dsl.impl.TownText get() = rylween.dsl.impl.TownText diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index 065155be..d4087818 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -571,6 +571,9 @@ class ScriptScope( @RylNextDsl @Suppress("unused") class ScriptRewardBuilder { + /** The item being placed, for the cant-carry and picked-up messages. */ + val itemName: TextPart = TextPart.SelectedItemName + private var goldAst: IntAst? = null private val itemIds = mutableListOf() private var applicationModel = RewardApplicationBuilder().build() diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 7a3fa3dc..1432b00d 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -1859,8 +1859,8 @@ fun validateScriptRewards( if (reward.application.overflow == RewardOverflowPolicy.PromptDropThenPlace) { check(reward.messages.cantCarry != null) { "drop-prompt reward requires cant-carry text" } } - reward.messages.cantCarry?.let { validateTextBlock(it, "reward cant-carry") } - reward.messages.pickedUp?.let { validateTextBlock(it, "reward picked-up") } + reward.messages.cantCarry?.let { validateTextBlock(it, "reward cant-carry", allowedRuntimeBindings = selectedItemTextBindings) } + reward.messages.pickedUp?.let { validateTextBlock(it, "reward picked-up", allowedRuntimeBindings = selectedItemTextBindings) } if (reward.messages.pickedUp != null) { check(reward.application.overflow == RewardOverflowPolicy.PromptDropThenPlace) { "picked-up reward text only applies to drop-prompt rewards" @@ -3044,7 +3044,7 @@ private fun validateGamePrompts(prompts: GamePromptsModel) { validateTextBlock(prompts.inventoryUse.invalidSlot, "inventory invalid-slot prompt", allowedRuntimeBindings = inventoryUseTextBindings) validateTextBlock(prompts.inventoryUse.notUsable, "inventory not-usable prompt", allowedRuntimeBindings = inventoryUseTextBindings) validateTextBlock(prompts.equipment.inventory, "equipment inventory prompt") - validateTextBlock(prompts.equipment.who, "equipment who prompt") + validateTextBlock(prompts.equipment.who, "equipment who prompt", allowedRuntimeBindings = memberChoiceTextBindings) validateTextBlock(prompts.equipment.noAvailable, "equipment no-available prompt", allowedRuntimeBindings = equipmentTextBindings) validateTextBlock(prompts.equipment.equipped, "equipment equipped prompt", allowedRuntimeBindings = selectedItemTextBindings) validateTextBlock(prompts.equipment.readyWeapons, "equipment ready-weapons prompt") diff --git a/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt index 2be49a2a..31aa0118 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt @@ -396,7 +396,7 @@ data class CharacterCreationPromptsModel( ) data class PriestSpellPromptsModel( - val who: TextBlock = literalText { line("Who? (1-", HuntText.partyMemberCount, ")") }, + val who: TextBlock = literalText { line("Who? (1-", PartyText.memberCount, ")") }, val firstSpellKey: Char = 'A', val mageCombatOnly: TextBlock = flowText("Sorry. Mage spells are combat-only."), val wrongClass: TextBlock = literalText("Wrong class."), diff --git a/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt index 849fca22..7b6d1cef 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt @@ -403,8 +403,15 @@ object HuntText { val memberName: TextPart = TextPart.HuntMemberName val memberSubjectPronoun: TextPart = TextPart.HuntMemberSubjectPronoun val foodGained: TextPart = TextPart.HuntFoodGained - val partyMemberCount: TextPart = TextPart.PartyMemberCount - val partyMemberMax: TextPart = TextPart.PartyMemberMax +} + +/** Runtime placeholders about the whole party, for any prompt that lists its members. */ +object PartyText { + /** How many members the party has, dead or alive, as in "Who? (1-4)". */ + val memberCount: TextPart = TextPart.PartyMemberCount + + /** The most members a party can have. */ + val memberMax: TextPart = TextPart.PartyMemberMax } /** Runtime placeholders available to authored camp messages. */ diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index d0d42ccb..9c788f80 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -424,7 +424,7 @@ val authoredRylween: RylweenModel = foodMax = 19 whoPrompt = literalText { - line("Who? (1-", HuntText.partyMemberCount, ")") + line("Who? (1-", PartyText.memberCount, ")") } dead = literalText("Dead.") notRanger = @@ -459,7 +459,7 @@ val authoredRylween: RylweenModel = guardPrompt = literalText("Camp.", "", "Post a guard?", "", "(Y)es", "(N)o") guardMemberPrompt = literalText { - line("Who? (1-", HuntText.partyMemberCount, ")") + line("Who? (1-", PartyText.memberCount, ")") } guardMemberDead = literalText("Dead.") standsGuard = @@ -694,7 +694,7 @@ val authoredRylween: RylweenModel = invalidInput = literalText("Choose an option.") } priest { - who = literalText { line("Who? (1-", HuntText.partyMemberCount, ")") } + who = literalText { line("Who? (1-", PartyText.memberCount, ")") } mageCombatOnly = flowText("Sorry. Mage spells are combat-only.") wrongClass = literalText("Not a spellcaster!") dead = literalText("Dead.") @@ -714,7 +714,7 @@ val authoredRylween: RylweenModel = } equipment { inventory = literalText("Ready what?") - who = literalText("Who? (1-N)") + who = literalText { line("Who? (1-", PartyText.memberCount, ")") } readyWeapons = literalText("Do you want to ready any weapons before leaving?", "", "(Y)es", "(N)o") readyArmors = literalText("Do you want to ready any armors before leaving?", "", "(Y)es", "(N)o") } @@ -3990,7 +3990,7 @@ val authoredRylween: RylweenModel = option('H') { clearText() choice.member( - literalText { line("Who? (1-", HuntText.partyMemberCount, ")") }, + literalText { line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.AliveOnly, accepting = MemberChoiceFilter.Any, ) { m -> @@ -4033,7 +4033,7 @@ val authoredRylween: RylweenModel = option('E') { clearText() choice.member( - literalText { line("Who? (1-", HuntText.partyMemberCount, ")") }, + literalText { line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.SpellcasterOnly, accepting = MemberChoiceFilter.Any, ) { m -> @@ -4072,7 +4072,7 @@ val authoredRylween: RylweenModel = option('R') { clearText() choice.member( - literalText { line("Who? (1-", HuntText.partyMemberCount, ")") }, + literalText { line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.DeadOnly, accepting = MemberChoiceFilter.Any, ) { m -> @@ -4586,7 +4586,7 @@ val authoredRylween: RylweenModel = clearText() choice.member( literalText { - line("Who wants to tell a story? (1-", HuntText.partyMemberMax, ")") + line("Who wants to tell a story? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.AliveOnly, accepting = MemberChoiceFilter.Any, @@ -4998,7 +4998,7 @@ val authoredRylween: RylweenModel = caster.mp -= cost ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.Any, ) { target -> @@ -5036,7 +5036,7 @@ val authoredRylween: RylweenModel = caster.mp -= cost ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.Any, ) { target -> @@ -5057,7 +5057,7 @@ val authoredRylween: RylweenModel = whenever(caster.mp gte cost) { ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.Any, ) { target -> @@ -5273,7 +5273,7 @@ val authoredRylween: RylweenModel = effect { ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.AliveOnly, ) { target -> @@ -5293,7 +5293,7 @@ val authoredRylween: RylweenModel = effect { ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.AliveOnly, ) { target -> @@ -5313,7 +5313,7 @@ val authoredRylween: RylweenModel = effect { ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.SpellcasterOnly, accepting = MemberChoiceFilter.AliveOnly, @@ -5427,7 +5427,7 @@ val authoredRylween: RylweenModel = effect { ask.member( literalText { - line("On Whom? (1-", HuntText.partyMemberMax, ")") + line("On Whom? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.Any, ) { target -> @@ -5484,7 +5484,7 @@ val authoredRylween: RylweenModel = effect { ask.member( literalText { - line("On Whom? (1-", HuntText.partyMemberMax, ")") + line("On Whom? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.DeadOnly, accepting = MemberChoiceFilter.Any, @@ -6477,7 +6477,7 @@ val authoredRylween: RylweenModel = reward { gold(3_000) items(Items.admtMail, Items.holyHandGrenade, Items.amberPotion, Items.fireWand, Items.crystalBowl) - promptDrop(cantCarry = "You can't carry all the") + promptDrop(cantCarry = flowText("You can't carry the ", itemName, ".")) } waitInput("after Ron's reward") } diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt index 4a2b82bf..a615fe89 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt @@ -97,6 +97,20 @@ class ScriptExecutorTest { assertEquals(1, catalog.count { line -> line.offersChoiceKey("A") }, "catalog choices must be listed once: $catalog") } + // A reward the party has no room for names the item it can't carry. + @Test + fun aFullInventoryNamesTheRewardThereIsNoRoomFor() { + val town = thordRuntime() + val sword = bundle.content.ref(CompiledHandleKind.Item, "sword") + val full = town.withParty(town.party.copy(inventory = town.party.inventory.map { slot -> slot.copy(item = sword) })) + val screen = TextCapturingScreen() + + runScript(scriptRoot(ScriptRootKind.DialogueBranch, "dialogue.ron.peasant.wife.rescued"), full, "\n".repeat(10), screen, "ron-full.log") + + val pages = screen.texts.map { lines -> lines.joinToString(" ") } + assertTrue(pages.any { page -> page.startsWith("You can't carry the Admt. Mail.") }, "$pages") + } + @Test fun appendedTextStaysBelowThePageAsItsOwnParagraph() { val screen = TextCapturingScreen() From 03671f3d0b8dfdf47b6293baa50b1dee56b9bb0b Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:17 +0100 Subject: [PATCH 12/16] Name mission squares in text instead of copying them 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. --- .../kotlin/rylween/compiled/CompiledBundle.kt | 10 ++++++++++ .../compiled/ExternalBundleArtifact.kt | 1 + .../main/kotlin/rylween/dsl/DslValidation.kt | 3 +++ .../rylween/dsl/ScriptSourceAnalysis.kt | 1 + core/src/main/kotlin/rylween/dsl/TextDsl.kt | 15 +++++++++++++++ .../kotlin/rylween/dsl/impl/StateModelsDsl.kt | 3 +++ .../main/kotlin/rylween/game/RylweenGame.kt | 19 ++++++++++++------- .../rylween/runtime/RuntimeWorldText.kt | 3 ++- .../rylween/runtime/ScriptExecutorTest.kt | 8 +++++++- 9 files changed, 54 insertions(+), 9 deletions(-) diff --git a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt index 1563b8df..d246adfb 100644 --- a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt +++ b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt @@ -125,6 +125,7 @@ import rylween.dsl.impl.TownModel import rylween.dsl.impl.Trigger import rylween.dsl.impl.WorldMapModel import rylween.dsl.impl.WorldPosition +import rylween.dsl.impl.mapCoordinates import rylween.dsl.impl.runtimeContent import rylween.runtime.CastleSessionSnapshot import rylween.runtime.DungeonSavedStep @@ -2174,6 +2175,14 @@ private class CompiledBundleCompiler( ) } + // A mission's square is fixed content, or the placed location it waits on. + private fun missionCoordinate(id: MissionId): CompiledTextPart = + when (val trigger = game.missions.singleOrNull { mission -> mission.id == id }?.trigger) { + is Trigger.AtPosition -> CompiledTextPart.Literal(strings.id(trigger.point.mapCoordinates())) + is Trigger.AtLocation -> CompiledTextPart.LocationCoordinate(locationRef(trigger.location)) + else -> error("text names the coordinates of mission ${id.slug}, which waits on no square") + } + private fun textPart(part: TextPart): CompiledTextPart = when (part) { is TextPart.Literal -> CompiledTextPart.Literal(strings.id(part.text)) @@ -2190,6 +2199,7 @@ private class CompiledBundleCompiler( is TextPart.TownName -> CompiledTextPart.TownName(townRef(part.town)) is TextPart.FuzzyTownLocation -> CompiledTextPart.FuzzyTownLocation(townRef(part.town), part.radius) is TextPart.LocationCoordinate -> CompiledTextPart.LocationCoordinate(locationRef(part.location)) + is TextPart.MissionCoordinate -> missionCoordinate(part.mission) TextPart.OfferedItemName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.OfferedItemName) TextPart.OfferedItemPrice -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.OfferedItemPrice) TextPart.SelectedItemName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.SelectedItemName) diff --git a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index 2c87331f..fce0f694 100644 --- a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt +++ b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt @@ -2569,6 +2569,7 @@ private class ExternalBundleArtifactWriter { "town" to JsonString(part.town.slug), "radius" to JsonNumber(part.radius.toString()), ) + is TextPart.MissionCoordinate -> error("mission coordinates only work in script text") is TextPart.LocationCoordinate -> jsonObject( "kind" to JsonString("locationCoordinate"), diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 1432b00d..dbfd6ad3 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -1287,6 +1287,9 @@ private fun validateTextBlock( is TextPart.LocationCoordinate -> { check(part.location.slug.isNotBlank()) { "$label references blank location" } } + is TextPart.MissionCoordinate -> { + check(part.mission.slug.isNotBlank()) { "$label references blank mission" } + } // CPD-OFF TextPart.OfferedItemName, TextPart.OfferedItemPrice, diff --git a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt index b2f0d568..9518041b 100644 --- a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt +++ b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt @@ -458,6 +458,7 @@ private class NativePathCollector { is TextPart.TownName, is TextPart.FuzzyTownLocation, is TextPart.LocationCoordinate, + is TextPart.MissionCoordinate, TextPart.OfferedItemName, TextPart.OfferedItemPrice, TextPart.SelectedItemName, diff --git a/core/src/main/kotlin/rylween/dsl/TextDsl.kt b/core/src/main/kotlin/rylween/dsl/TextDsl.kt index fe0ce120..8ddf384b 100644 --- a/core/src/main/kotlin/rylween/dsl/TextDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/TextDsl.kt @@ -84,6 +84,11 @@ sealed interface TextPart { val location: LocationId, ) : TextPart + /** The square a mission waits on, as the map shows coordinates. */ + data class MissionCoordinate( + val mission: MissionId, + ) : TextPart + object OfferedItemName : TextPart object OfferedItemPrice : TextPart @@ -183,6 +188,7 @@ fun TextPart.fallbackText(): String = is TextPart.TownName -> town.slug is TextPart.FuzzyTownLocation -> "${town.slug}.near" is TextPart.LocationCoordinate -> "{${location.slug}.coordinates}" + is TextPart.MissionCoordinate -> "{${mission.slug}.coordinates}" TextPart.OfferedItemName -> "{item_name}" TextPart.OfferedItemPrice -> "{item_price}" TextPart.SelectedItemName -> "{selected_item_name}" @@ -546,3 +552,12 @@ class LocationTextRef( /** Creates text placeholders for a [location]. */ fun location(location: LocationId): LocationTextRef = LocationTextRef(location) + +/** Text about a mission, such as the square it waits on: `mission(Missions.erethorEntry).coordinates`. */ +class MissionTextRef( + mission: MissionId, +) { + val coordinates: TextPart = TextPart.MissionCoordinate(mission) +} + +fun mission(mission: MissionId): MissionTextRef = MissionTextRef(mission) diff --git a/core/src/main/kotlin/rylween/dsl/impl/StateModelsDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/StateModelsDsl.kt index 73964b02..d4201ced 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/StateModelsDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/StateModelsDsl.kt @@ -61,6 +61,9 @@ data class GridPoint( val y: Int, ) +/** The point as the game writes map coordinates, such as `6x20`. */ +fun GridPoint.mapCoordinates(): String = "${x}x$y" + data class GridOffset( val x: Int, val y: Int, diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 9c788f80..b9ee653e 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -6257,10 +6257,11 @@ val authoredRylween: RylweenModel = """, ) showTextAndWait( - """ - One of Erethor's temples, where mad priests practice - blasphemous magic, is located at 6x20, near the western peaks. - """, + flowText( + "One of Erethor's temples, where mad priests practice blasphemous magic, is located at ", + mission(Missions.erethorEntry).coordinates, + ", near the western peaks.", + ), ) writeText( """ @@ -6268,7 +6269,9 @@ val authoredRylween: RylweenModel = but the Cloak will make its bearer almost invulnerable. """, ) - journal("Erethor's temple is situated at 6x20.") + journal { + line("Erethor's temple is situated at ", mission(Missions.erethorEntry).coordinates, ".") + } mark(Story.erethor.lute.rumorTold) waitInput("after Tybalt's offer") } @@ -6452,8 +6455,10 @@ val authoredRylween: RylweenModel = my father left me, will be yours if you rescue her. """, ) - appendText("The orcs have a cave at 42x23 in Lonewood.") - journal("The orc cavern is at 42x23.") + appendText(flowText("The orcs have a cave at ", mission(Missions.husbandCave).coordinates, " in Lonewood.")) + journal { + line("The orc cavern is at ", mission(Missions.husbandCave).coordinates, ".") + } mark(Story.peasant.wife.accepted) waitInput("after Ron names the orc cave") } diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeWorldText.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeWorldText.kt index 68e0e868..e432143d 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeWorldText.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeWorldText.kt @@ -18,6 +18,7 @@ import rylween.compiled.CompiledWorldPosition import rylween.compiled.ExternalRuntimeTextBlock import rylween.compiled.ExternalRuntimeTextPart import rylween.dsl.impl.GridPoint +import rylween.dsl.impl.mapCoordinates /** Resolves authored town, role, NPC, and location references in [content] to player-facing text. */ internal class RuntimeWorldText( @@ -245,7 +246,7 @@ internal class RuntimeWorldText( is CompiledWorldPosition.Wilderness -> "at ${pointText(position.point)}" } - private fun pointText(point: GridPoint): String = "${point.x}x${point.y}" + private fun pointText(point: GridPoint): String = point.mapCoordinates() private fun fuzzyPoint( point: GridPoint, diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt index a615fe89..71ac21f0 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt @@ -105,7 +105,13 @@ class ScriptExecutorTest { val full = town.withParty(town.party.copy(inventory = town.party.inventory.map { slot -> slot.copy(item = sword) })) val screen = TextCapturingScreen() - runScript(scriptRoot(ScriptRootKind.DialogueBranch, "dialogue.ron.peasant.wife.rescued"), full, "\n".repeat(10), screen, "ron-full.log") + runScript( + scriptRoot(ScriptRootKind.DialogueBranch, "dialogue.ron.peasant.wife.rescued"), + full, + "\n".repeat(10), + screen, + "ron-full.log", + ) val pages = screen.texts.map { lines -> lines.joinToString(" ") } assertTrue(pages.any { page -> page.startsWith("You can't carry the Admt. Mail.") }, "$pages") From 688a9d01fbd96e2010c08ae974f0fca7ada063df Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:17 +0100 Subject: [PATCH 13/16] Write drink menus once and numbers without lit() 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. --- core/src/main/kotlin/rylween/dsl/Dsl.kt | 6 + .../main/kotlin/rylween/game/RylweenGame.kt | 218 ++++++------------ .../rylween/runtime/ScriptExecutorTest.kt | 10 + 3 files changed, 81 insertions(+), 153 deletions(-) diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index d4087818..dfb18e1e 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -558,6 +558,12 @@ class ScriptScope( } } + fun pay( + amount: Int, + broke: ScriptScope.() -> Unit, + ok: ScriptScope.() -> Unit, + ): Unit = pay(lit(amount), broke, ok) + internal fun capture(body: ScriptScope.() -> Unit): List = recordStatementNodes(ctx, body) } diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index b9ee653e..331cb3d9 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -1762,7 +1762,7 @@ val authoredRylween: RylweenModel = forEachMember { whenever((thiefFound eq 0) and it.isClass(PcClass.Thief)) { writeText(flowText(partyName(it), " checks the chest for traps. {pause 1s}")) - trapChance set lit(40) - it.dexterity * 2 / 5 + trapChance set 40 - it.dexterity * 2 / 5 whenever(trapChance lt 4) { trapChance set 4 } @@ -4264,93 +4264,23 @@ val authoredRylween: RylweenModel = }, ) - clearText() choice.yesNo( "Anything to drink?", "", "(Y)es", "(N)o", yes = { - clearText() - menu( + orderDrink( "What'll it be?", - "", - "(A) Ale 2 au", - "(B) Mead 3 au", - "(C) Wine 5 au", - "(D) Whiskey 7 au", - "(E) Fanta 1 au", - "RETURN leaves.", - ) { - option('A') { - pay( - lit(2), - broke = { - writeText("No money - No drink! {pause 1s}") - }, - ok = { - playSound(Sounds.Town.drink) - writeText("Ahh...! {pause 1s}") - healLivingMembers((lit(2) / 2) + 1) - }, - ) - } - option('B') { - pay( - lit(3), - broke = { - writeText("No money - No drink! {pause 1s}") - }, - ok = { - playSound(Sounds.Town.drink) - writeText("Ahh...! {pause 1s}") - healLivingMembers((lit(3) / 2) + 1) - }, - ) - } - option('C') { - pay( - lit(5), - broke = { - writeText("No money - No drink! {pause 1s}") - }, - ok = { - playSound(Sounds.Town.drink) - writeText("Ahh...! {pause 1s}") - healLivingMembers((lit(5) / 2) + 1) - }, - ) - } - option('D') { - pay( - lit(7), - broke = { - writeText("No money - No drink! {pause 1s}") - }, - ok = { - playSound(Sounds.Town.drink) - writeText("Ahh...! {pause 1s}") - healLivingMembers((lit(7) / 2) + 1) - }, - ) - } - option('E') { - pay( - lit(1), - broke = { - writeText("No money - No drink! {pause 1s}") - }, - ok = { - writeText("The other guests giggle. {pause 1s}") - healLivingMembers((lit(1) / 2) + 1) - }, - ) - } - } + Drink('A', "Ale", price = 2, served = "Ahh...! {pause 1s}"), + Drink('B', "Mead", price = 3, served = "Ahh...! {pause 1s}"), + Drink('C', "Wine", price = 5, served = "Ahh...! {pause 1s}"), + Drink('D', "Whiskey", price = 7, served = "Ahh...! {pause 1s}"), + Drink('E', "Fanta", price = 1, served = "The other guests giggle. {pause 1s}", sound = null), + ) }, ) - clearText() choice.yesNo( "Are you in need of lodging?", "", @@ -4723,76 +4653,19 @@ val authoredRylween: RylweenModel = } option('O') { - clearText() - menu( + orderDrink( "Order:", - "", - "(A) Ale 2 au", - "(B) Mead 3 au", - "(C) Wine 4 au", - "(D) Fanta 1 au", - "RETURN leaves.", - ) { - option('A') { - pay( - lit(2), - broke = { - writeText("No money - No drink! {pause 1s}") - }, - ok = { - playSound(Sounds.Town.drink) - writeText("AAH! (your health returns). {pause 1s}") - forEachMember(includeDead = true) { - it.hp.addClamped((lit(2) / 2) + 1, it.maxHp) - } - }, - ) - } - option('B') { - pay( - lit(3), - broke = { - writeText("No money - No drink! {pause 1s}") - }, - ok = { - playSound(Sounds.Town.drink) - writeText("AAH! (your health returns). {pause 1s}") - forEachMember(includeDead = true) { - it.hp.addClamped((lit(3) / 2) + 1, it.maxHp) - } - }, - ) - } - option('C') { - pay( - lit(4), - broke = { - writeText("No money - No drink! {pause 1s}") - }, - ok = { - playSound(Sounds.Town.drink) - writeText("AAH! (your health returns). {pause 1s}") - forEachMember(includeDead = true) { - it.hp.addClamped((lit(4) / 2) + 1, it.maxHp) - } - }, - ) - } - option('D') { - pay( - lit(1), - broke = { - writeText("No money - No drink! {pause 1s}") - }, - ok = { - writeText("You are the laughing stock of the entire tavern... {pause 2s}") - forEachMember(includeDead = true) { - it.hp.addClamped((lit(1) / 2) + 1, it.maxHp) - } - }, - ) - } - } + Drink('A', "Ale", price = 2, served = "AAH! (your health returns). {pause 1s}"), + Drink('B', "Mead", price = 3, served = "AAH! (your health returns). {pause 1s}"), + Drink('C', "Wine", price = 4, served = "AAH! (your health returns). {pause 1s}"), + Drink( + 'D', + "Fanta", + price = 1, + served = "You are the laughing stock of the entire tavern... {pause 2s}", + sound = null, + ), + ) } } } @@ -5232,12 +5105,11 @@ val authoredRylween: RylweenModel = ) clearMapWindow() showBackdrop(Images.Backdrop.cave) - clearText() choice.enterOrLeave( literalText("You find a cave!", "", "(E)nter", "(L)eave"), enter = { whenever(party.timeLeft gt 10) { - discoverCave(random(5..18), Dungeons.randomCave, lit(10)) + discoverCave(random(5..18)) } otherwise { writeText( flowText( @@ -5675,7 +5547,6 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.koboldVillage) { - clearText() menu( literalText { line( @@ -5806,7 +5677,6 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.ogreCave) { - clearText() choice.enterOrLeave( literalText { line("You find the cave the half-orc told you about.") @@ -6207,7 +6077,7 @@ val authoredRylween: RylweenModel = menu("(B)uy it", "(N)o thanks") { option('B') { pay( - amount = lit(50_000), + amount = 50_000, broke = { writeText( """ @@ -6327,7 +6197,7 @@ val authoredRylween: RylweenModel = menu("(B)uy it", "(N)o thanks") { option('B') { pay( - amount = lit(10_000), + amount = 10_000, broke = { writeText( """ @@ -6730,6 +6600,48 @@ val authoredDsl: GameModel = authoredRylween.content // carrying once hit points and spell points run into the hundreds. private fun potionPoints(target: MemberRef): IntExpr = target.level * 3 + 12 +// A drink on an inn or tavern menu: it costs [price] gold, and restores half +// of that plus one hit point to every living member. +private data class Drink( + val key: Char, + val name: String, + val price: Int, + val served: String, + val sound: SoundId? = Sounds.Town.drink, +) + +// The drinks menu, one row per drink with its price, and RETURN to leave. +private fun ScriptScope.orderDrink( + prompt: String, + vararg drinks: Drink, +) { + menu( + literalText( + prompt, + "", + *drinks + .map { drink -> + "(${drink.key}) ${drink.name} ${drink.price} au" + }.toTypedArray(), + "RETURN leaves.", + ), + ) { + drinks.forEach { drink -> + option(drink.key) { + pay( + drink.price, + broke = { writeText("No money - No drink! {pause 1s}") }, + ok = { + drink.sound?.let { sound -> playSound(sound) } + writeText(drink.served) + healLivingMembers(drink.price / 2 + 1) + }, + ) + } + } + } +} + // Fire damage shared by the Fire Cloud spell and the fire wand: every monster // still standing takes caster.level * damageRoll points. private fun ScriptScope.burnEveryLivingMonster( diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt index 71ac21f0..e154fd85 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt @@ -86,6 +86,16 @@ class ScriptExecutorTest { assertEquals(after.party.members.size, after.party.counters.memberCount) } + @Test + fun theInnListsEachDrinkWithItsPrice() { + // Decline supper, then ask for a drink. + val menu = townSceneTexts("towne.inn", "NY").first { lines -> "What'll it be?" in lines } + + val ale = menu.single { line -> line.startsWith("(A)") } + assertEquals(listOf("(A) Ale", "2 au"), ale.split(TEXT_COLUMN_SEPARATOR), "the price is its own column: $menu") + assertEquals("RETURN leaves.", menu.last(), "the drinks menu ends with its way out: $menu") + } + @Test fun shopMenusSeparateProseFromKeyChoicesWithoutRepeatingThem() { // Decline the forced beer interlude, dismiss its pause, open Buy, then decline the catalog choice. From 6247f34d1463e213cbc137fedef7001438591684 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:36:18 +0100 Subject: [PATCH 14/16] Document formulas, placeholders and the new verbs 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. --- docs/dsl-authoring.md | 81 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 73 insertions(+), 8 deletions(-) diff --git a/docs/dsl-authoring.md b/docs/dsl-authoring.md index 3e64dd5d..f988855a 100644 --- a/docs/dsl-authoring.md +++ b/docs/dsl-authoring.md @@ -93,12 +93,12 @@ rylween wilderness keys / events / terrainTransitions dungeons - keys / event / scenario + keys / event / randomEvents / scenario speak standardConversation / textTables / questionAction towns townSystem - entryTax / menu / buildingServices + image / entryTax / menu / buildingServices characters randomPlacementPolicy / character monsters @@ -330,6 +330,9 @@ reward { } ``` +A reward of several items can name each one it has no room for with `itemName`: +`promptDrop(cantCarry = flowText("You can't carry the ", itemName, "."))`. + For simple player-facing resource gains, use the narrow helpers: ```kotlin @@ -419,6 +422,11 @@ what game state changes. A mission triggers `at(...)` a square or a `onTerrain(...)`, and `requires(...)` a story flag state or a condition before it runs. +Text that tells the player where a mission waits names it rather than copying +its square: `flowText("The orcs have a cave at ", mission(Missions.husbandCave).coordinates, ".")` +shows the mission's `at(...)` square, or its location's square wherever this +game placed it, so the text follows the mission when it moves. + ### Dialogue Branch ```kotlin @@ -465,6 +473,7 @@ scene(Scenes.Towne.smith) { sell { prompt("Sell what?", "") acceptsKinds(ItemKind.Weapon, ItemKind.Armor) + price = ShopPrices.formula(Formulas.sellPrice) offer { line("Ok! Give ya ", price, "!") } } } @@ -475,6 +484,10 @@ scene(Scenes.Towne.smith) { catalog too long for one screen splits into `page { ... }` blocks. Shop catalogs, sell policy, haggle text, paging, and purchase keys are authored. The runtime service loop owns live input, inventory mutation, and paging state. +A price is the item's cost (`ShopPrices.itemCost`, the default for buying), a +fixed amount (`ShopPrices.fixed(n)`), or a formula +(`ShopPrices.formula(Formulas.rationPrice)`) that sees the item's `itemCost` and +the leader's `firstLevel`. A sell section names its price. ### Runtime-System Prompt @@ -494,8 +507,54 @@ prompts { Use this pattern when a runtime loop owns the input cadence but the text is player-facing game prose. Values only the runtime knows come in through -placeholder objects: `InventoryText` (`slotName`, `itemName`), `CampText` -(`guardName`), `HuntText`, `UpkeepText`, `TownText`, and `BattleText`. +placeholder objects: `InventoryText` (`slotName`, `itemName`), `PartyText` +(`memberCount`, `memberMax`), `CampText` (`guardName`), `CastleText` +(`thiefName`), `HuntText`, `UpkeepText`, `TownText`, and `BattleText` (with +`roundNumber` for the page each round opens with). Each message is authored +whole, the runtime only filling in its values: the castle's +`trapTriesDisarm = literalText { line(CastleText.thiefName, " tries to disarm it...") }`, +not a fragment the runtime joins to a name. Where the runtime lists choices it +knows, such as party members or the stairs items the castle guardian takes, the +prompt holds only the question and the runtime adds the choices and the RETURN +line. + +### Formulas + +A game rule that works something out, rather than naming a fixed number, is a +formula, so the game author can change it without touching a runtime: + +```kotlin +formulas { + formula(Formulas.spellCost) { + value = spellBaseCost + level + } + formula(Formulas.monsterDamage) { + value = (monsterHitPoints / 6 + random(0..9) - armorClass) atLeast 1 + } +} + +realm { spellCost = Formulas.spellCost } +``` + +The system that uses a formula binds its variables: the member it is about +(`weaponSkill`, `weaponDamage`, `hitPoints`, `armorClass`, `level`, `charisma`, +`dexterity`), the monster (`monsterWeaponSkill`, `monsterHitPoints`, +`monsterSpellPower`), the encounter, the party (`firstLevel`, `livingMembers`, +`gold`), a town's `taxPercent`, a shop item's `itemCost`, or a spell's +`spellBaseCost`. `atLeast` and `atMost` clamp a value, `whenValue(condition, a, b)` +picks one, and `random(lo..hi)` draws from the game's own random numbers. A +chance is a percentage the runtime rolls 0-99 against. + +This game's rules that are formulas: what a spell costs (`realm { spellCost }`), +a party member's and a monster's chance to hit and damage, a monster's chance to +cast, the hit points a defending member regains, how encounters grow with the +leader's level (`encounterFoeCountMaxFormula`, `encounterWeaponSkillFormula`, +and the hit point range), battle experience and gold, level-up hit points, the +food the party eats (`upkeep { foodCost }`), the town entry tax +(`entryTax { amount }`), shop prices, the hunting and trap-disarm chances, and +the haggle bonus. Inside a priest spell, `withCurrentCasterCost { caster, cost -> }` +hands over the cost the formula works out; the spell's `baseCost` is declared +once, in its `spell(...)` header. ### Map Or Terrain @@ -629,18 +688,24 @@ dungeons { } } + // The mix every scenario draws its other levels from, unless it names its own. + randomEvents( + DungeonEvents.weakEncounter to 2, + DungeonEvents.goldChest to 1, + ) + scenario(Dungeons.reebarTomb) { name("Reebar Tomb") levels(20) - randomEvents( - DungeonEvents.weakEncounter to 2, - DungeonEvents.goldChest to 1, - ) level(2, DungeonEvents.cryptWarning) + level(13..19, DungeonEvents.colorRiddle) } } ``` +A scenario's own `randomEvents(...)` replaces the dungeons' mix for that +dungeon, and `level(3, 6, 9, event = ...)` puts one event on several levels. + An event's disposition decides whether it is still on its level when the party comes back: From 19fd61f7df377b0b3504ac08d0bd21b80e787c50 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:21:28 +0100 Subject: [PATCH 15/16] Tell a party that can't pay the town tax what it lacks 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. --- .../kotlin/rylween/compiled/CompiledBundle.kt | 2 + .../compiled/ExternalBundleArtifact.kt | 4 + core/src/main/kotlin/rylween/dsl/Dsl.kt | 4 +- .../main/kotlin/rylween/dsl/DslValidation.kt | 7 + .../rylween/dsl/ScriptSourceAnalysis.kt | 1 + core/src/main/kotlin/rylween/dsl/TextDsl.kt | 3 + .../rylween/dsl/impl/RuntimeContentDsl.kt | 1 + .../rylween/dsl/impl/WorldContentDsl.kt | 3 + docs/dsl-authoring.md | 6 +- .../main/kotlin/rylween/game/RylweenGame.kt | 10 ++ .../rylween/runtime/RylweenRuntimeMain.kt | 31 ++++- .../rylween/runtime/TownEntryTaxTest.kt | 129 ++++++++++++++++++ 12 files changed, 195 insertions(+), 6 deletions(-) create mode 100644 runtimes/runtime/src/test/kotlin/rylween/runtime/TownEntryTaxTest.kt diff --git a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt index d246adfb..f04a582b 100644 --- a/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt +++ b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt @@ -894,6 +894,7 @@ enum class CompiledRuntimeTextPart { CurrentTownName, TownTaxPercent, TownTaxAmount, + TownTaxShortfall, CreationMemberNumber, CreationMemberName, CreationWeaponSkill, @@ -2222,6 +2223,7 @@ private class CompiledBundleCompiler( TextPart.CurrentTownName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.CurrentTownName) TextPart.TownTaxPercent -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.TownTaxPercent) TextPart.TownTaxAmount -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.TownTaxAmount) + TextPart.TownTaxShortfall -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.TownTaxShortfall) TextPart.CreationMemberNumber -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.CreationMemberNumber) TextPart.CreationMemberName -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.CreationMemberName) TextPart.CreationWeaponSkill -> CompiledTextPart.Runtime(CompiledRuntimeTextPart.CreationWeaponSkill) diff --git a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index fce0f694..640f74c4 100644 --- a/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt +++ b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt @@ -430,6 +430,7 @@ data class ExternalTownPrompts( val entryWelcome: ExternalRuntimeTextBlock, val entryTax: ExternalRuntimeTextBlock, val entryTaxThanks: ExternalRuntimeTextBlock, + val entryTaxShortfall: ExternalRuntimeTextBlock, ) /** Town-system runtime rows consumed by direct runtimes. */ @@ -1877,6 +1878,7 @@ private class ExternalBundleArtifactWriter { textField("entryWelcome", prompts.town.entryWelcome), textField("entryTax", prompts.town.entryTax), textField("entryTaxThanks", prompts.town.entryTaxThanks), + textField("entryTaxShortfall", prompts.town.entryTaxShortfall), ), promptGroupJson( "party", @@ -2597,6 +2599,7 @@ private class ExternalBundleArtifactWriter { TextPart.CurrentTownName -> textTokenJson("currentTownName") TextPart.TownTaxPercent -> textTokenJson("townTaxPercent") TextPart.TownTaxAmount -> textTokenJson("townTaxAmount") + TextPart.TownTaxShortfall -> textTokenJson("townTaxShortfall") TextPart.CreationMemberNumber -> textTokenJson("creationMemberNumber") TextPart.CreationMemberName -> textTokenJson("creationMemberName") TextPart.CreationWeaponSkill -> textTokenJson("creationWeaponSkill") @@ -3138,6 +3141,7 @@ private class ExternalRuntimeSystemsReader( entryWelcome = town.requiredTextPrompt("entryWelcome"), entryTax = town.requiredTextPrompt("entryTax"), entryTaxThanks = town.requiredTextPrompt("entryTaxThanks"), + entryTaxShortfall = town.requiredTextPrompt("entryTaxShortfall"), ), party = ExternalPartyPrompts( diff --git a/core/src/main/kotlin/rylween/dsl/Dsl.kt b/core/src/main/kotlin/rylween/dsl/Dsl.kt index dfb18e1e..78a98346 100644 --- a/core/src/main/kotlin/rylween/dsl/Dsl.kt +++ b/core/src/main/kotlin/rylween/dsl/Dsl.kt @@ -2108,7 +2108,7 @@ class CharacterCreationPromptsBuilder( * Receiver for town-entry and town-menu prompt text. * * Designers author the reusable town menu title and entry/tax messages shared - * by the town session. + * by the town session, including the one a party that can't pay the tax sees. */ @RylNextDsl class TownPromptsBuilder( @@ -2118,6 +2118,7 @@ class TownPromptsBuilder( var entryWelcome: TextBlock = initial.entryWelcome var entryTax: TextBlock = initial.entryTax var entryTaxThanks: TextBlock = initial.entryTaxThanks + var entryTaxShortfall: TextBlock = initial.entryTaxShortfall fun menuTitle(body: StructuredTextBlockBuilder.() -> Unit) { menuTitleText = literalText(body) @@ -2129,6 +2130,7 @@ class TownPromptsBuilder( entryWelcome = entryWelcome, entryTax = entryTax, entryTaxThanks = entryTaxThanks, + entryTaxShortfall = entryTaxShortfall, ) } diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index dbfd6ad3..49dd2d92 100644 --- a/core/src/main/kotlin/rylween/dsl/DslValidation.kt +++ b/core/src/main/kotlin/rylween/dsl/DslValidation.kt @@ -180,6 +180,7 @@ private val townEntryTaxTextBindings: Set = TextPart.TownTaxPercent, TextPart.TownTaxAmount, ) +private val townEntryTaxShortfallTextBindings: Set = townEntryTaxTextBindings + TextPart.TownTaxShortfall private val battleTextBindings: Set = setOf( TextPart.BattleFoeDisplayName, @@ -1313,6 +1314,7 @@ private fun validateTextBlock( TextPart.CurrentTownName, TextPart.TownTaxPercent, TextPart.TownTaxAmount, + TextPart.TownTaxShortfall, TextPart.CreationMemberNumber, TextPart.CreationMemberName, TextPart.CreationWeaponSkill, @@ -3099,6 +3101,11 @@ private fun validateGamePrompts(prompts: GamePromptsModel) { validateTextBlock(prompts.town.entryWelcome, "town entry welcome prompt", allowedRuntimeBindings = townEntryTaxTextBindings) validateTextBlock(prompts.town.entryTax, "town entry tax prompt", allowedRuntimeBindings = townEntryTaxTextBindings) validateTextBlock(prompts.town.entryTaxThanks, "town entry tax thanks prompt") + validateTextBlock( + prompts.town.entryTaxShortfall, + "town entry tax shortfall prompt", + allowedRuntimeBindings = townEntryTaxShortfallTextBindings, + ) validateTextBlock(prompts.wilderness.pass, "wilderness pass prompt") validateTextBlock(prompts.wilderness.noMoves, "wilderness no-moves prompt") validateTextBlock(prompts.wilderness.outOfMoves, "wilderness out-of-moves prompt") diff --git a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt index 9518041b..c997b49f 100644 --- a/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt +++ b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt @@ -481,6 +481,7 @@ private class NativePathCollector { TextPart.CurrentTownName, TextPart.TownTaxPercent, TextPart.TownTaxAmount, + TextPart.TownTaxShortfall, TextPart.CreationMemberNumber, TextPart.CreationMemberName, TextPart.CreationWeaponSkill, diff --git a/core/src/main/kotlin/rylween/dsl/TextDsl.kt b/core/src/main/kotlin/rylween/dsl/TextDsl.kt index 8ddf384b..26d31e01 100644 --- a/core/src/main/kotlin/rylween/dsl/TextDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/TextDsl.kt @@ -136,6 +136,8 @@ sealed interface TextPart { object TownTaxAmount : TextPart + object TownTaxShortfall : TextPart + object CreationMemberNumber : TextPart object CreationMemberName : TextPart @@ -211,6 +213,7 @@ fun TextPart.fallbackText(): String = TextPart.CurrentTownName -> "{town}" TextPart.TownTaxPercent -> "{pct}" TextPart.TownTaxAmount -> "{amount}" + TextPart.TownTaxShortfall -> "{shortfall}" TextPart.CreationMemberNumber -> "{char_num}" TextPart.CreationMemberName -> "{name}" TextPart.CreationWeaponSkill -> "{weapon_skill}" diff --git a/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt index 31aa0118..861072cb 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt @@ -446,6 +446,7 @@ data class TownPromptsModel( val entryWelcome: TextBlock = missingPrompt("town.entry_welcome"), val entryTax: TextBlock = missingPrompt("town.entry_tax"), val entryTaxThanks: TextBlock = missingPrompt("town.entry_tax_thanks"), + val entryTaxShortfall: TextBlock = missingPrompt("town.entry_tax_shortfall"), ) data class PartyPromptsModel( diff --git a/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt index 7b6d1cef..8e1a8df6 100644 --- a/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt @@ -445,6 +445,9 @@ object TownText { val name: TextPart = TextPart.CurrentTownName val taxPercent: TextPart = TextPart.TownTaxPercent val taxAmount: TextPart = TextPart.TownTaxAmount + + /** The gold the party lacks to pay the entry tax. */ + val taxShortfall: TextPart = TextPart.TownTaxShortfall } data class RewardBundleModel( diff --git a/docs/dsl-authoring.md b/docs/dsl-authoring.md index f988855a..7a55138d 100644 --- a/docs/dsl-authoring.md +++ b/docs/dsl-authoring.md @@ -551,8 +551,10 @@ cast, the hit points a defending member regains, how encounters grow with the leader's level (`encounterFoeCountMaxFormula`, `encounterWeaponSkillFormula`, and the hit point range), battle experience and gold, level-up hit points, the food the party eats (`upkeep { foodCost }`), the town entry tax -(`entryTax { amount }`), shop prices, the hunting and trap-disarm chances, and -the haggle bonus. Inside a priest spell, `withCurrentCasterCost { caster, cost -> }` +(`entryTax { amount }`; a party with less gold than the tax is shown the +`entryTaxShortfall` prompt, with `TownText.taxShortfall`, and stays outside), +shop prices, the hunting and trap-disarm chances, and the haggle bonus. Inside a +priest spell, `withCurrentCasterCost { caster, cost -> }` hands over the cost the formula works out; the spell's `baseCost` is declared once, in its `spell(...)` header. diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 331cb3d9..91cdc99f 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -778,6 +778,16 @@ val authoredRylween: RylweenModel = " au.", ) entryTaxThanks = literalText("Thank you!") + entryTaxShortfall = + flowText( + "There is a tax of ", + TownText.taxPercent, + "% to enter ", + TownText.name, + ". You need ", + TownText.taxShortfall, + " additional au to be able to pay.", + ) } party { journalHeader = diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt index a51f6ebb..084a8bb5 100644 --- a/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt +++ b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt @@ -1725,11 +1725,24 @@ class GameRuntime private constructor( val taxed = mapOf("gold" to runtime.party.resources.gold, "tax_percent" to town.taxPercent, "first_level" to leaderLevel) val amount = content.evalFormula(formula, runtime.party, taxed).value.takeIf { gold -> gold > 0 } ?: return TownEntryTaxResult(runtime) + townSystem.image?.let(screen::showImage) + val audio = RuntimeAudio(systems.audio, screen) + val shortfall = amount - runtime.party.resources.gold + if (shortfall > 0) { + log.event("town.tax.short town=${slug(town.id)} amount=$amount gold=${runtime.party.resources.gold}") + screen.writeText( + systems.prompts.town.entryTaxShortfall + .renderRuntimeText(content, runtime, screen.textColumns) { kind -> taxValue(kind, amount, shortfall) } + .withPausePrompt(PausePrompts(systems.prompts)), + ) + input.readCommand() ?: return null + audio.cue(AudioCue.LeaveTown) + screen.renderWilderness(runtime.leaveTown(), world) + return null + } val lines = townEntryTaxLines(runtime, tax, amount, screen) log.event("town.tax.prompt town=${slug(town.id)} level=$leaderLevel amount=$amount gold=${runtime.party.resources.gold}") - townSystem.image?.let(screen::showImage) screen.writeText(lines) - val audio = RuntimeAudio(systems.audio, screen) val choice = input.readValidChoice(screen, lines, audio) { candidate -> tax.pay.matches(candidate) || tax.leave.matches(candidate) @@ -1759,13 +1772,25 @@ class GameRuntime private constructor( ): List = screen.choiceMenuLines( systems.prompts.town.entryTax - .renderRuntimeText(content, runtime, screen.textColumns) { kind -> amount.toString().takeIf { kind == "townTaxAmount" } }, + .renderRuntimeText(content, runtime, screen.textColumns) { kind -> taxValue(kind, amount) }, listOf( tax.pay.mnemonicLine(tax.pay.label), tax.leave.mnemonicLine(tax.leave.label), ), ) + /** The tax text values only the tax gate knows: the [amount] asked, and the gold the party lacks to pay it. */ + private fun taxValue( + kind: String, + amount: Int, + shortfall: Int = 0, + ): String? = + when (kind) { + "townTaxAmount" -> amount.toString() + "townTaxShortfall" -> shortfall.toString() + else -> null + } + private fun runService( runtime: RuntimeState, service: CompiledBuildingService, diff --git a/runtimes/runtime/src/test/kotlin/rylween/runtime/TownEntryTaxTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/TownEntryTaxTest.kt new file mode 100644 index 00000000..59e2c012 --- /dev/null +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/TownEntryTaxTest.kt @@ -0,0 +1,129 @@ +package rylween.runtime + +import org.junit.jupiter.api.io.TempDir +import rylween.compiled.CompiledGameBundle +import rylween.compiled.CompiledHandleKind +import rylween.compiled.CompiledIntExpr +import rylween.compiled.readExternalCompiledBundleContentHash +import rylween.compiled.readExternalCompiledGameBundle +import rylween.compiled.readExternalRuntimeSystems +import java.io.File +import java.time.LocalDate +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class TownEntryTaxTest { + private val bundleFile = File(requiredRuntimeTestProperty("rylween.runtime.bundle")) + + @TempDir + private lateinit var testTmp: File + private val bundle = bundleFile.readExternalCompiledGameBundle() + private val systems = bundleFile.readExternalRuntimeSystems() + private val content = bundle.content + private val town = content.towns.first() + private val townName = content.strings.value(town.nameString) + + // The game's tax is a share of the gold carried, so only a fixed tax can ask for more than the party has. + @Test + fun aPartyThatCannotPayTheTaxIsToldWhatItLacksAndStaysOutside() { + val screen = enterTown("tax-short", tax = 2_500, gold = 2_000) + + val pages = screen.screens.map { lines -> lines.joinToString(" ") } + val shortfall = "There is a tax of ${town.taxPercent}% to enter $townName. You need 500 additional au to be able to pay." + assertTrue(pages.any { page -> shortfall in page }, "$pages") + assertFalse(pages.any { page -> "(P)ay to Enter" in page }, "a party that can't pay is not asked to: $pages") + assertFalse(screen.screens.flatten().any { line -> line.startsWith("Entering ") }, "the town menu stays closed: $pages") + } + + @Test + fun aPartyThatCanPayTheTaxIsAskedToPayIt() { + val screen = enterTown("tax-paid", tax = 1_500, gold = 2_000) + + val pages = screen.screens.map { lines -> lines.joinToString(" ") } + assertTrue(pages.any { page -> "we must request you pay 1500 au." in page && "(P)ay to Enter" in page }, "$pages") + assertTrue(pages.any { page -> "Thank you!" in page && "Entering $townName" in page }, "$pages") + } + + /** Starts a new party with [gold], moves it onto the first town, and enters it under a fixed [tax], paying if asked. */ + private fun enterTown( + name: String, + tax: Int, + gold: Int, + ): TextScreen { + val factory = RuntimeSessionFactory.load(bundle.withTownTax(tax), systems, bundleFile.readExternalCompiledBundleContentHash()) + val saveFile = testTmp.resolve("$name.rsave").also(File::delete) + runSession(factory, name, ScriptedInput(""), NoOpRuntimeScreen(), saveFile, loadFile = null) + + val values = SaveCodec.decodeValues(saveFile.readLines()) + val prefix = values.localUserPrefix() + saveFile.writeText( + SaveCodec.encodeValues( + values + + mapOf( + "${prefix}party.x" to town.position.x.toString(), + "${prefix}party.y" to town.position.y.toString(), + "${prefix}party.gold" to gold.toString(), + ), + ), + ) + + val screen = TextScreen() + runSession(factory, "$name-enter", ScriptedInput("EP"), screen, saveFile, loadFile = saveFile) + return screen + } + + private fun CompiledGameBundle.withTownTax(tax: Int): CompiledGameBundle { + val formula = content.ref(CompiledHandleKind.Formula, checkNotNull(systems.town?.entryTax?.amount)) + val formulas = + content.formulas.map { current -> + if (current.id == + formula + ) { + current.copy(value = CompiledIntExpr.Literal(tax)) + } else { + current + } + } + return copy(content = content.copy(formulas = formulas)) + } + + private fun runSession( + factory: RuntimeSessionFactory, + name: String, + input: RuntimeInputPort, + screen: RuntimeScreenPort, + saveFile: File, + loadFile: File?, + ) { + RuntimeLog.open(testTmp.resolve("$name.log")).use { log -> + factory.start( + input = input, + screen = screen, + config = + RuntimeSessionConfig( + userId = "local", + stateSlug = "fresh-replay", + loadFile = loadFile, + saveFile = saveFile, + sessionDate = LocalDate.of(2026, 5, 11), + ), + log = log, + ) + } + } + + private fun Map.localUserPrefix(): String = + (1..getValue("users.count").toInt()) + .map { index -> "user.$index." } + .first { prefix -> get("${prefix}id") == "local" } + + /** Records each text screen the runtime writes. */ + private class TextScreen : NoOpRuntimeScreen() { + val screens = mutableListOf>() + + override fun writeText(lines: List) { + screens += lines + } + } +} From 653b1febdfecbe889a2257b175e2e688c36e6273 Mon Sep 17 00:00:00 2001 From: Marcus Lagergren <1062473+lagergren@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:27:57 +0100 Subject: [PATCH 16/16] Write flow text one way 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. --- core/src/main/kotlin/rylween/dsl/TextDsl.kt | 81 ++++++++-------- docs/dsl-authoring.md | 11 ++- .../main/kotlin/rylween/game/RylweenGame.kt | 96 +++++++++---------- game/src/test/kotlin/rylween/FlowTextTest.kt | 37 +++++++ 4 files changed, 126 insertions(+), 99 deletions(-) create mode 100644 game/src/test/kotlin/rylween/FlowTextTest.kt diff --git a/core/src/main/kotlin/rylween/dsl/TextDsl.kt b/core/src/main/kotlin/rylween/dsl/TextDsl.kt index 26d31e01..38a5359b 100644 --- a/core/src/main/kotlin/rylween/dsl/TextDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/TextDsl.kt @@ -278,16 +278,48 @@ fun literalText(body: StructuredTextBlockBuilder.() -> Unit): TextBlock = Struct /** * Creates flow text: prose the renderer wraps to its own column or pixel - * width. Single newlines in the source are spaces; a blank line starts a new - * paragraph, which renderers show with a blank line above it. + * width, from strings and runtime values, as in + * `flowText("You find ", amount, " gold.")`. A newline in a string is a + * space; a blank line starts a new paragraph, which renderers show with a + * blank line above it. */ -fun flowText(text: String): TextBlock = TextBlock.Flow(flowParagraphs(text)) +fun flowText(vararg parts: Any): TextBlock = + TextBlock.Flow( + parts + .flatMap { part -> if (part is String) part.flowPieces() else listOf(part) } + .splitAtParagraphBreaks() + .map { paragraph -> TextLine(paragraph.flatMap(::textParts).trimmedEnds()) } + .filter { paragraph -> paragraph.parts.isNotEmpty() }, + ) + +/** Where a blank line in flow text starts a new paragraph. */ +private object ParagraphBreak + +private val blankLine = Regex("""\n\s*\n""") +private val lineBreak = Regex("""\s*\n\s*""") -/** Creates a single deferred-wrap paragraph from literal and dynamic parts. */ -fun flowText(vararg parts: Any): TextBlock = TextBlock.Flow(listOf(TextLine(parts.flatMap(::textParts)))) +/** This string's paragraphs with a [ParagraphBreak] between them, each newline and the indentation around it a space. */ +private fun String.flowPieces(): List = + split(blankLine) + .map { piece -> piece.replace(lineBreak, " ") } + .flatMapIndexed { index, piece -> if (index == 0) listOf(piece) else listOf(ParagraphBreak, piece) } + +private fun List.splitAtParagraphBreaks(): List> { + val breaks = indices.filter { index -> this[index] == ParagraphBreak } + return (listOf(-1) + breaks).zip(breaks + size) { start, end -> subList(start + 1, end) } +} -/** Creates deferred-wrap text with multiple paragraphs and optional dynamic parts. */ -fun flowText(body: FlowTextBlockBuilder.() -> Unit): TextBlock = FlowTextBlockBuilder().apply(body).build() +/** A paragraph's parts without the spaces at its start and end. */ +private fun List.trimmedEnds(): List = + mapIndexed { index, part -> + when { + part !is TextPart.Literal -> part + index == 0 && index == lastIndex -> TextPart.Literal(part.text.trim()) + index == 0 -> TextPart.Literal(part.text.trimStart()) + index == lastIndex -> TextPart.Literal(part.text.trimEnd()) + else -> part + } + }.filterNot { part -> part == TextPart.Literal("") } /** * Detection rule for triple-quoted multi-line authoring: if the caller @@ -317,11 +349,6 @@ fun TextLineSink.lines(vararg lines: String) { expandMultiline(lines).forEach { line(it) } } -/** Executes a nested structured-text builder block against this sink. */ -fun T.lines(body: T.() -> Unit) { - body() -} - /** Concatenates text blocks into one structured block. */ fun combineTextBlocks(vararg blocks: TextBlock): TextBlock = combineTextBlocks(blocks.toList()) @@ -470,36 +497,6 @@ class StructuredTextBlockBuilder : TextLineSink { fun build(): TextBlock = TextBlock.Structured(lines.toList()) } -/** Builder for deferred-wrap prose paragraphs that may include dynamic text parts. */ -@RylNextDsl -class FlowTextBlockBuilder { - private val paragraphs = mutableListOf() - - /** - * Adds one paragraph. String newlines inside [parts] are normalized by the - * renderer, so use another [paragraph] call for intentional paragraph breaks. - */ - fun paragraph(vararg parts: Any) { - paragraphs += TextLine(parts.flatMap(::textParts)) - } - - /** Adds one or more literal paragraphs from triple-quoted prose. */ - fun paragraphs(text: String) { - flowParagraphs(text).forEach(paragraphs::add) - } - - fun build(): TextBlock = TextBlock.Flow(paragraphs.toList()) -} - -private fun flowParagraphs(text: String): List { - val trimmed = text.trimIndent() - return trimmed - .split(Regex("\\n\\s*\\n")) - .map { paragraph -> paragraph.trim().replace('\n', ' ') } - .filter(String::isNotEmpty) - .map { paragraph -> TextLine(literalParts(paragraph)) } -} - /** Text-placeholder helper for NPC name, job, and location. */ class CharacterTextRef private constructor( val name: TextPart, diff --git a/docs/dsl-authoring.md b/docs/dsl-authoring.md index 7a55138d..01a69605 100644 --- a/docs/dsl-authoring.md +++ b/docs/dsl-authoring.md @@ -135,11 +135,12 @@ notes: `Towns.thord`, and `Terrain.forest` instead of raw strings. - Put game prose in `writeText`, `appendText`, `showTextAndWait`, or runtime-system prompt rows. Text comes in two kinds: `flowText(...)` is prose - the renderer wraps to its own width (a plain string is flow text, and a blank - line starts a new paragraph), and `literalText(...)` is lines kept exactly as - written. Use literal lines only when each row is an intentional menu, layout, - sign or verse row; `literalText { line("You find ", amount) }` mixes in - runtime values the same way `flowText("You find ", amount, " gold.")` does. + the renderer wraps to its own width (a plain string is flow text; in its + strings a newline is a space, and a blank line or `\n\n` starts a new + paragraph), and `literalText(...)` is lines kept exactly as written. Use + literal lines only when each row is an intentional menu, layout, sign or verse + row; `literalText { line("You find ", amount) }` mixes in runtime values the + same way `flowText("You find ", amount, " gold.\n\nThe chest is empty.")` does. - Use block helpers such as `localInt { ... }`, `ask.member { ... }`, `ask.monsterAlive { ... }`, and `withCurrentCasterCost { ... }` instead of raw Kotlin temporaries in script bodies. diff --git a/game/src/main/kotlin/rylween/game/RylweenGame.kt b/game/src/main/kotlin/rylween/game/RylweenGame.kt index 91cdc99f..10c95bca 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -4245,10 +4245,11 @@ val authoredRylween: RylweenModel = loop { localInt((party.leader.level * party.leader.level) * 15) { cost -> writeText( - flowText { - paragraph(townNpcName(NpcJobs.innkeeper), ", the Innkeeper welcomes you.") - paragraph("Do you want supper, travelers?") - }, + flowText( + townNpcName(NpcJobs.innkeeper), + ", the Innkeeper welcomes you.", + "\n\nDo you want supper, travelers?", + ), ) choice.yesNo( "(Y)es", @@ -4535,10 +4536,11 @@ val authoredRylween: RylweenModel = writeText("Dead men tell no stories... {pause 2s}") } otherwise { writeText( - flowText { - paragraph(partyName(storyteller), " stands up and screams:") - paragraph("- ANYONE WHO WANNA HEAR A TRAVELER'S STORY? {pause 2s}") - }, + flowText( + partyName(storyteller), + " stands up and screams:", + "\n\n- ANYONE WHO WANNA HEAR A TRAVELER'S STORY? {pause 2s}", + ), ) playSound(Sounds.Town.crowdCheer) @@ -5830,14 +5832,12 @@ val authoredRylween: RylweenModel = encounter(Monsters.ridingHobgoblin, mandatory = true) renderMap() showTextAndWait( - flowText { - paragraph("Before you kill the last hobgoblin you ask him about the key. The foul creature blurts:") - paragraph( - "- Boss has it! In ze cave! at home, yess, ", - location(Locations.hobgoblinCave).coordinates, - "... pleeez sirs, don't kill me...", - ) - }, + flowText( + "Before you kill the last hobgoblin you ask him about the key. The foul creature blurts:", + "\n\n- Boss has it! In ze cave! at home, yess, ", + location(Locations.hobgoblinCave).coordinates, + "... pleeez sirs, don't kill me...", + ), ) showTextAndWait( "(at this point you sever his carotid artery).", @@ -6027,16 +6027,14 @@ val authoredRylween: RylweenModel = npc(Npcs.gorm) { whenState(Story.fighter.priestBook.priestTold) { showTextAndWait( - flowText { - paragraph("When you mention the book, he nods and looks a bit embarrassed.") - paragraph( - "- Yes, I know. I happened to lose it. A ", - character(Roles.wizardRobbed).job, - " called ", - character(Roles.wizardRobbed).name, - " stole it from my bedroom a week ago...", - ) - }, + flowText( + "When you mention the book, he nods and looks a bit embarrassed.", + "\n\n- Yes, I know. I happened to lose it. A ", + character(Roles.wizardRobbed).job, + " called ", + character(Roles.wizardRobbed).name, + " stole it from my bedroom a week ago...", + ), ) showTextAndWait( """ @@ -6304,16 +6302,14 @@ val authoredRylween: RylweenModel = ), ) writeText( - flowText { - paragraph( - "After breaking a few of his teeth, he also willingly reveals that the ", - character(Roles.silverKeySmith).job, - " went by the name of ", - character(Roles.silverKeySmith).name, - "... {pause}", - ) - paragraph("You let go of your grip on his collar, and he falls to the floor.") - }, + flowText( + "After breaking a few of his teeth, he also willingly reveals that the ", + character(Roles.silverKeySmith).job, + " went by the name of ", + character(Roles.silverKeySmith).name, + "... {pause}", + "\n\nYou let go of your grip on his collar, and he falls to the floor.", + ), ) waitInput("after Gotharp talks") } @@ -6514,14 +6510,12 @@ val authoredRylween: RylweenModel = whenState(Story.masterCrown.borinPaid) { writeText( - flowText { - paragraph("- I JUST CAN'T TELL YOU HOW GRATEFUL I AM! He takes the stone and smiles broadly at you.") - paragraph( - "- Very well, seekers! The Master Crown is hidden in a dungeon near ", - location(Locations.masterCrownDungeon).coordinates, - "! Fare thee well.", - ) - }, + flowText( + "- I JUST CAN'T TELL YOU HOW GRATEFUL I AM! He takes the stone and smiles broadly at you.", + "\n\n- Very well, seekers! The Master Crown is hidden in a dungeon near ", + location(Locations.masterCrownDungeon).coordinates, + "! Fare thee well.", + ), ) journal { line("The Master Crown dungeon is at ", location(Locations.masterCrownDungeon).coordinates, ".") @@ -6580,14 +6574,12 @@ val authoredRylween: RylweenModel = whenState(Story.hermit.trollTooth.extracted) { writeText( - flowText { - paragraph("You hand him the troll tooth.") - paragraph( - "- Oh YES! He cackles. At areas uncharted, near ", - location(Locations.hermitDungeon).coordinates, - " is the cave you seek. Beware of the guardian the ancients gave birth to...", - ) - }, + flowText( + "You hand him the troll tooth.", + "\n\n- Oh YES! He cackles. At areas uncharted, near ", + location(Locations.hermitDungeon).coordinates, + " is the cave you seek. Beware of the guardian the ancients gave birth to...", + ), ) journal { line("The Fire Shield Dungeon is at ", location(Locations.hermitDungeon).coordinates, ".") diff --git a/game/src/test/kotlin/rylween/FlowTextTest.kt b/game/src/test/kotlin/rylween/FlowTextTest.kt new file mode 100644 index 00000000..ab915efd --- /dev/null +++ b/game/src/test/kotlin/rylween/FlowTextTest.kt @@ -0,0 +1,37 @@ +package rylween + +import rylween.dsl.TextBlock +import rylween.dsl.TextLine +import rylween.dsl.TextPart +import rylween.dsl.flowText +import kotlin.test.Test +import kotlin.test.assertEquals + +/** How flow text turns its strings and runtime values into paragraphs. */ +class FlowTextTest { + @Test + fun aBlankLineStartsAParagraphAndTheSpacesBesideAValueStay() { + assertEquals( + TextBlock.Flow( + listOf( + TextLine(listOf(TextPart.Literal("Welcome to "), TextPart.CurrentTownName, TextPart.Literal("."))), + TextLine(listOf(TextPart.Literal("Do you want supper?"))), + ), + ), + flowText("Welcome to ", TextPart.CurrentTownName, ".\n\nDo you want supper?"), + ) + } + + @Test + fun aNewlineAndTheIndentationAroundItAreOneSpace() { + assertEquals( + flowText("He quickly fled, but I know it's him."), + flowText( + """ + He quickly fled, + but I know it's him. + """, + ), + ) + } +}