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/CompiledBundle.kt b/core/src/main/kotlin/rylween/compiled/CompiledBundle.kt index 1cc8ddf6..f04a582b 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 @@ -134,6 +135,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. @@ -881,6 +884,7 @@ enum class CompiledRuntimeTextPart { HuntFoodGained, UpkeepMemberName, CampGuardName, + CastleThiefName, PartyMemberCount, PartyMemberMax, WildernessDungeonName, @@ -890,6 +894,7 @@ enum class CompiledRuntimeTextPart { CurrentTownName, TownTaxPercent, TownTaxAmount, + TownTaxShortfall, CreationMemberNumber, CreationMemberName, CreationWeaponSkill, @@ -906,6 +911,7 @@ enum class CompiledRuntimeTextPart { BattleLootName, BattleLevelMemberName, BattleLevelsGained, + BattleRoundNumber, } /** Screen/view command emitted from scripts and interpreted by runtime renderers. */ @@ -999,7 +1005,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 +1018,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. */ @@ -1239,18 +1247,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 } @@ -2105,6 +2108,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'") } @@ -2171,12 +2176,21 @@ 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)) 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)) @@ -2186,6 +2200,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) @@ -2198,6 +2213,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) @@ -2207,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) @@ -2223,6 +2240,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 = @@ -2345,11 +2363,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/compiled/ExternalBundleArtifact.kt b/core/src/main/kotlin/rylween/compiled/ExternalBundleArtifact.kt index 3c246c34..640f74c4 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. */ @@ -430,18 +430,22 @@ data class ExternalTownPrompts( val entryWelcome: ExternalRuntimeTextBlock, val entryTax: ExternalRuntimeTextBlock, val entryTaxThanks: ExternalRuntimeTextBlock, + val entryTaxShortfall: ExternalRuntimeTextBlock, ) /** 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, ) @@ -579,6 +583,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. */ @@ -705,6 +711,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, @@ -740,16 +748,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, @@ -760,28 +767,23 @@ 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, ) /** 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, @@ -809,9 +811,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, ) @@ -842,7 +842,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, @@ -1112,7 +1113,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?, @@ -1131,7 +1132,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, ) @@ -1584,6 +1585,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), @@ -1610,10 +1613,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 @@ -1624,6 +1625,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()), @@ -1631,26 +1633,21 @@ 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), ) 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), @@ -1678,9 +1675,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), ) @@ -1714,6 +1709,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 -> @@ -1728,7 +1724,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()), @@ -1882,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", @@ -2289,9 +2286,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), ), @@ -2492,7 +2493,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(), @@ -2511,7 +2512,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)), ) @@ -2548,6 +2549,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 -> @@ -2569,6 +2571,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"), @@ -2586,6 +2589,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") @@ -2595,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") @@ -2611,6 +2616,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)) @@ -3135,6 +3141,7 @@ private class ExternalRuntimeSystemsReader( entryWelcome = town.requiredTextPrompt("entryWelcome"), entryTax = town.requiredTextPrompt("entryTax"), entryTaxThanks = town.requiredTextPrompt("entryTaxThanks"), + entryTaxShortfall = town.requiredTextPrompt("entryTaxShortfall"), ), party = ExternalPartyPrompts( @@ -3335,6 +3342,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")) @@ -3343,7 +3351,7 @@ private class ExternalRuntimeSystemsReader( private fun JsonObject.readTownEntryTax(): ExternalTownEntryTax = ExternalTownEntryTax( - minimumLeaderLevel = requiredInt("minimumLeaderLevel"), + amount = optionalNullableString("amount"), pay = requiredObject("pay").readBinding(), leave = requiredObject("leave").readBinding(), ) @@ -3480,7 +3488,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"), @@ -3499,7 +3507,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") }, ) @@ -3674,6 +3682,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() }, @@ -3701,15 +3711,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"), @@ -3721,15 +3730,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"), ) }, @@ -3737,10 +3743,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(), @@ -3768,9 +3772,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(), ) @@ -3812,6 +3814,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 @@ -3827,7 +3830,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"), @@ -4892,11 +4895,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..3f34dff3 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 @@ -106,6 +107,8 @@ 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 val ShopResources: rylween.dsl.impl.ShopResources get() = rylween.dsl.impl.ShopResources @@ -143,7 +146,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 7e8fd894..78a98346 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() @@ -253,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")) } } @@ -328,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( @@ -564,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) } @@ -577,6 +577,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() @@ -829,17 +832,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)) } } @@ -2104,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( @@ -2114,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) @@ -2125,6 +2130,7 @@ class TownPromptsBuilder( entryWelcome = entryWelcome, entryTax = entryTax, entryTaxThanks = entryTaxThanks, + entryTaxShortfall = entryTaxShortfall, ) } @@ -2625,6 +2631,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 @@ -2651,7 +2663,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, ) @@ -2795,6 +2811,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() } @@ -3089,6 +3121,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() } @@ -3115,6 +3150,7 @@ class TownSystemBuilder { buildingServices = buildingServiceModels, leavePrompts = leavePromptCommands, entryTax = entryTaxModel, + image = image, nativeServices = listOf( EngineServiceUse(EngineService.KeyboardInput, "town menu command selection"), @@ -3132,20 +3168,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, ) @@ -3475,10 +3512,35 @@ 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") + + // 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") + + // 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, diff --git a/core/src/main/kotlin/rylween/dsl/DslValidation.kt b/core/src/main/kotlin/rylween/dsl/DslValidation.kt index 1346d82d..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, @@ -191,6 +192,7 @@ private val battleTextBindings: Set = TextPart.BattleLootName, TextPart.BattleLevelMemberName, TextPart.BattleLevelsGained, + TextPart.BattleRoundNumber, ) private val characterCreationStatsTextBindings: Set = setOf( @@ -323,7 +325,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, 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 -> @@ -331,6 +333,31 @@ 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.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" } @@ -433,18 +460,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" } @@ -458,22 +473,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" } @@ -488,10 +487,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, @@ -519,9 +516,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) -> @@ -837,7 +832,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,9 +847,10 @@ 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)) text.floorNames.forEachIndexed { index, floor -> check(floor.isNotBlank()) { "$label floor name ${index + 1} is blank" } } @@ -996,9 +991,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") @@ -1189,7 +1181,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" @@ -1214,6 +1206,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 +1228,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) { @@ -1280,6 +1288,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, @@ -1293,6 +1304,7 @@ private fun validateTextBlock( TextPart.HuntFoodGained, TextPart.UpkeepMemberName, TextPart.CampGuardName, + TextPart.CastleThiefName, TextPart.PartyMemberCount, TextPart.PartyMemberMax, TextPart.WildernessDungeonName, @@ -1302,6 +1314,7 @@ private fun validateTextBlock( TextPart.CurrentTownName, TextPart.TownTaxPercent, TextPart.TownTaxAmount, + TextPart.TownTaxShortfall, TextPart.CreationMemberNumber, TextPart.CreationMemberName, TextPart.CreationWeaponSkill, @@ -1318,6 +1331,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" @@ -1330,6 +1344,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 +1359,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 +1374,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) } } @@ -1742,6 +1761,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, @@ -1844,8 +1864,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" @@ -1901,18 +1921,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}" } } } @@ -3037,7 +3049,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") @@ -3089,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/ExpressionDsl.kt b/core/src/main/kotlin/rylween/dsl/ExpressionDsl.kt index 63215ec7..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() @@ -185,7 +204,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 +317,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 +352,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/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt b/core/src/main/kotlin/rylween/dsl/ItemRealmDsl.kt index 655c5acb..d32aa562 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, ) } @@ -199,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 @@ -246,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/ScriptSourceAnalysis.kt b/core/src/main/kotlin/rylween/dsl/ScriptSourceAnalysis.kt index 98f5bc3d..c997b49f 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( @@ -455,6 +448,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, @@ -464,6 +458,7 @@ private class NativePathCollector { is TextPart.TownName, is TextPart.FuzzyTownLocation, is TextPart.LocationCoordinate, + is TextPart.MissionCoordinate, TextPart.OfferedItemName, TextPart.OfferedItemPrice, TextPart.SelectedItemName, @@ -476,6 +471,7 @@ private class NativePathCollector { TextPart.HuntFoodGained, TextPart.UpkeepMemberName, TextPart.CampGuardName, + TextPart.CastleThiefName, TextPart.PartyMemberCount, TextPart.PartyMemberMax, TextPart.WildernessDungeonName, @@ -485,6 +481,7 @@ private class NativePathCollector { TextPart.CurrentTownName, TextPart.TownTaxPercent, TextPart.TownTaxAmount, + TextPart.TownTaxShortfall, TextPart.CreationMemberNumber, TextPart.CreationMemberName, TextPart.CreationWeaponSkill, @@ -501,6 +498,7 @@ private class NativePathCollector { TextPart.BattleLootName, TextPart.BattleLevelMemberName, TextPart.BattleLevelsGained, + TextPart.BattleRoundNumber, -> Unit } } @@ -662,8 +660,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 { @@ -770,7 +768,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. */ @@ -794,8 +792,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/TextDsl.kt b/core/src/main/kotlin/rylween/dsl/TextDsl.kt index 1cdfe61f..38a5359b 100644 --- a/core/src/main/kotlin/rylween/dsl/TextDsl.kt +++ b/core/src/main/kotlin/rylween/dsl/TextDsl.kt @@ -32,12 +32,21 @@ 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, ) : 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 @@ -75,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 @@ -101,6 +115,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 @@ -119,6 +136,8 @@ sealed interface TextPart { object TownTaxAmount : TextPart + object TownTaxShortfall : TextPart + object CreationMemberNumber : TextPart object CreationMemberName : TextPart @@ -150,6 +169,8 @@ sealed interface TextPart { object BattleLevelMemberName : TextPart object BattleLevelsGained : TextPart + + object BattleRoundNumber : TextPart } /** Returns a deterministic placeholder used when no runtime renderer is available. */ @@ -159,6 +180,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}" @@ -168,6 +190,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}" @@ -180,6 +203,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}" @@ -189,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}" @@ -205,6 +230,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. */ @@ -240,7 +266,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)) }) @@ -252,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) } -/** Creates deferred-wrap text with multiple paragraphs and optional dynamic parts. */ -fun flowText(body: FlowTextBlockBuilder.() -> Unit): TextBlock = FlowTextBlockBuilder().apply(body).build() +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) } +} + +/** 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 @@ -291,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()) @@ -325,28 +378,50 @@ 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 { - 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 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)) } - text.substring(rest).takeIf(String::isNotEmpty)?.let { after -> parts += TextPart.Literal(after) } - return parts } -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()) } -/** One step of text shown with `{pause}` beats: the text so far, then the pause after it; the last step has none. */ +/** + * 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, val pauseMillis: Int?, @@ -355,7 +430,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 +441,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 +461,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 = @@ -424,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, @@ -509,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/CastleDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/CastleDsl.kt index a7a56a80..62387f84 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, @@ -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(), ) @@ -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 @@ -498,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() @@ -510,7 +514,7 @@ class CastleTextBuilder( fun build(): CastleTextModel = CastleTextModel( roomMonster = roomMonster, - trapTriesDisarmSuffix = trapTriesDisarmSuffix, + trapTriesDisarm = trapTriesDisarm, trapDisarmSucceed = trapDisarmSucceed, trapDisarmFail = trapDisarmFail, pitfallIllustration = pitfallIllustration, @@ -529,7 +533,7 @@ class CastleTextBuilder( stairsLeave = stairsLeave, teleportVortex = teleportVortex, teleportOutside = teleportOutside, - giveMenu = giveMenu, + givePrompt = givePrompt, stairsGuardianGrateful = stairsGuardianGrateful, floorNames = floorNames.toList(), ) diff --git a/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/CombatDsl.kt index 622c8e1c..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,21 +81,18 @@ 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, ) 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 +109,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 +131,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, @@ -158,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 } /** @@ -198,6 +193,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 +245,10 @@ class StandardBattleBuilder { requiredStandardBattle(encounterHitPointMinFormula, "encounterHitPointMinFormula = ..."), encounterHitPointMaxFormula = requiredStandardBattle(encounterHitPointMaxFormula, "encounterHitPointMaxFormula = ..."), + encounterFoeCountMaxFormula = + requiredStandardBattle(encounterFoeCountMaxFormula, "encounterFoeCountMaxFormula = ..."), + encounterWeaponSkillFormula = + requiredStandardBattle(encounterWeaponSkillFormula, "encounterWeaponSkillFormula = ..."), victoryImage = victoryImage, defeatImage = defeatImage, nativeServices = defaultNativeServices, @@ -298,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 @@ -329,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) { @@ -499,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) } @@ -521,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"), @@ -552,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"), ) @@ -743,21 +722,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 +762,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 83312ca8..27ba9b12 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. */ @@ -103,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, @@ -117,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/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/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/RuntimeContentDsl.kt index 2be49a2a..861072cb 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."), @@ -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/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/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/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt b/core/src/main/kotlin/rylween/dsl/impl/WorldContentDsl.kt index dd3db9b2..8e1a8df6 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"), ) @@ -402,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. */ @@ -412,6 +420,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. */ @@ -431,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 b77c41c8..01a69605 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 @@ -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. @@ -172,11 +173,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 +206,17 @@ 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. + +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 @@ -323,6 +331,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 @@ -331,6 +342,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: @@ -401,6 +423,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 @@ -447,6 +474,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, "!") } } } @@ -457,6 +485,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 @@ -476,8 +508,56 @@ 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 }`; 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. ### Map Or Terrain @@ -611,18 +691,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: @@ -704,7 +790,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/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 49b60542..10c95bca 100644 --- a/game/src/main/kotlin/rylween/game/RylweenGame.kt +++ b/game/src/main/kotlin/rylween/game/RylweenGame.kt @@ -397,10 +397,11 @@ 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 { - foodCostLeaderDiv = 4 + foodCost = Formulas.foodUpkeep foodTickEvery = 5 starveFoodThreshold = 0 starveDamage = 2 @@ -423,7 +424,7 @@ val authoredRylween: RylweenModel = foodMax = 19 whoPrompt = literalText { - line("Who? (1-", HuntText.partyMemberCount, ")") + line("Who? (1-", PartyText.memberCount, ")") } dead = literalText("Dead.") notRanger = @@ -458,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 = @@ -577,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, @@ -588,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 @@ -614,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( """ @@ -698,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.") @@ -718,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") } @@ -782,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 = @@ -794,7 +800,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.") @@ -1324,13 +1330,71 @@ 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) + } + // 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 + } + // 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) } } @@ -1366,6 +1430,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) @@ -1394,13 +1460,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!") } @@ -1439,13 +1511,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.") } @@ -1461,23 +1535,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, ) } @@ -1700,10 +1771,8 @@ 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() - trapChance set lit(40) - it.dexterity * 2 / 5 + writeText(flowText(partyName(it), " checks the chest for traps. {pause 1s}")) + trapChance set 40 - it.dexterity * 2 / 5 whenever(trapChance lt 4) { trapChance set 4 } @@ -1712,10 +1781,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 +1826,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 +2220,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) }, @@ -2288,35 +2353,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) } @@ -2324,16 +2382,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) @@ -2343,78 +2391,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) @@ -2423,16 +2420,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) } @@ -2440,18 +2427,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) } } @@ -2750,8 +2726,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 +2738,9 @@ val authoredRylween: RylweenModel = """ You spend a very exhausting hour upstairs. - (PERVERT!) ;-) + (PERVERT!) ;-) {pause 2s} """, ) - pause2s() }, ) }, @@ -2841,10 +2815,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") } @@ -3823,7 +3799,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( @@ -3835,7 +3811,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( @@ -3858,7 +3834,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( @@ -3891,7 +3867,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: @@ -3922,10 +3898,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 +3937,9 @@ val authoredRylween: RylweenModel = """, ) playSound(Sounds.Combat.monsterDissolve) - pause2s() + pause(2_000) appendText(literalText("dust...")) waitInput("after Ydarg turns to dust") - clearText() writeText( """ CONGRATULATIONS! @@ -4026,38 +4000,38 @@ 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 -> 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}", + ), + ) }, ) } @@ -4069,39 +4043,34 @@ 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 -> 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() }, ) } @@ -4113,34 +4082,25 @@ 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 -> 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() + m.revive() 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}")) }, ) } @@ -4260,6 +4220,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, "!") @@ -4283,12 +4244,12 @@ val authoredRylween: RylweenModel = loop { localInt((party.leader.level * party.leader.level) * 15) { cost -> - clearText() 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", @@ -4297,140 +4258,46 @@ 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() }, ) }, ) - 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 = { - clearText() - writeText("No money - No drink!") - pause1s() - }, - ok = { - clearText() - playSound(Sounds.Town.drink) - writeText("Ahh...!") - pause1s() - healLivingMembers((lit(2) / 2) + 1) - }, - ) - } - option('B') { - pay( - lit(3), - broke = { - clearText() - writeText("No money - No drink!") - pause1s() - }, - ok = { - clearText() - playSound(Sounds.Town.drink) - writeText("Ahh...!") - pause1s() - healLivingMembers((lit(3) / 2) + 1) - }, - ) - } - option('C') { - pay( - lit(5), - broke = { - clearText() - writeText("No money - No drink!") - pause1s() - }, - ok = { - clearText() - playSound(Sounds.Town.drink) - writeText("Ahh...!") - pause1s() - healLivingMembers((lit(5) / 2) + 1) - }, - ) - } - option('D') { - pay( - lit(7), - broke = { - clearText() - writeText("No money - No drink!") - pause1s() - }, - ok = { - clearText() - playSound(Sounds.Town.drink) - writeText("Ahh...!") - pause1s() - healLivingMembers((lit(7) / 2) + 1) - }, - ) - } - option('E') { - pay( - lit(1), - broke = { - clearText() - writeText("No money - No drink!") - pause1s() - }, - ok = { - clearText() - writeText("The other guests giggle.") - pause1s() - 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?", "", "(Y)es", "(N)o", yes = { - clearText() writeText { line("A room is ", cost, " gold/night.") line("") @@ -4442,21 +4309,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 +4347,6 @@ val authoredRylween: RylweenModel = }, no = { loop { - clearText() writeText("The innkeeper leaves.") menu("(C)hitchat with guests", "(L)eave") { option('C') { @@ -4556,7 +4417,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.")) @@ -4566,7 +4427,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( @@ -4583,6 +4444,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, "!") @@ -4596,9 +4458,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 +4473,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 +4498,6 @@ val authoredRylween: RylweenModel = localInt(0) { rumors -> loop { - clearText() writeText( flowText( "- Welcome! Have a seat ", @@ -4670,28 +4527,24 @@ 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, ) { 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?") - }, + flowText( + partyName(storyteller), + " stands up and screams:", + "\n\n- 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 +4571,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 +4588,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 +4610,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,121 +4637,47 @@ 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") } } 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 = { - clearText() - writeText("No money - No drink!") - pause1s() - }, - ok = { - clearText() - playSound(Sounds.Town.drink) - writeText("AAH! (your health returns).") - pause1s() - forEachMember(includeDead = true) { - it.hp.addClamped((lit(2) / 2) + 1, it.maxHp) - } - }, - ) - } - option('B') { - pay( - lit(3), - broke = { - clearText() - writeText("No money - No drink!") - pause1s() - }, - ok = { - clearText() - playSound(Sounds.Town.drink) - writeText("AAH! (your health returns).") - pause1s() - forEachMember(includeDead = true) { - it.hp.addClamped((lit(3) / 2) + 1, it.maxHp) - } - }, - ) - } - option('C') { - pay( - lit(4), - broke = { - clearText() - writeText("No money - No drink!") - pause1s() - }, - ok = { - clearText() - playSound(Sounds.Town.drink) - writeText("AAH! (your health returns).") - pause1s() - forEachMember(includeDead = true) { - it.hp.addClamped((lit(4) / 2) + 1, it.maxHp) - } - }, - ) - } - option('D') { - pay( - lit(1), - broke = { - clearText() - writeText("No money - No drink!") - pause1s() - }, - ok = { - clearText() - writeText("You are the laughing stock of the entire tavern...") - pause2s() - 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, + ), + ) } } } @@ -4948,10 +4719,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 +4745,11 @@ 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() + target.wound(damage) + whenever(target.dead) { + writeText("...KILLED! {pause 600ms}") } } } @@ -5001,12 +4764,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,48 +4780,41 @@ 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 + target.kill() } } } 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 +4824,28 @@ 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 + target.wound(damage) + whenever(target.dead) { appendText { - line("\u001B[31m", partyName(target), " DIES!\u001B[37m") + line("{red}", partyName(target), " DIES! {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() - target.hp -= damage - whenever(target.hp lte 0) { - target.hp set 0 - target.dead set true + writeText(flowText(partyName(target), " is burnt for ", damage, " damage pts! {pause 1s}")) + target.wound(damage) + whenever(target.dead) { writeText { - line("\u001B[31m", partyName(target), " DIES!\u001B[37m") + line("{red}", partyName(target), " DIES! {pause 1s}") } - pause1s() } } } @@ -5112,10 +4856,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 +4867,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 } @@ -5135,80 +4877,78 @@ 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 ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.Any, ) { 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() } } } 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 ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, 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() } } } 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( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.Any, ) { target -> whenever(target.dead) { caster.mp -= cost - target.dead set false - party.memberCount += 1 - target.hp set 1 - clearText() + target.revive() writeText( flowText( partyName(target), @@ -5216,31 +4956,27 @@ 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() } } } 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) { caster.mp -= cost - clearText() writeText( flowText( partyName(caster), @@ -5252,11 +4988,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 +4999,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,32 +5009,24 @@ val authoredRylween: RylweenModel = """, ), ) - waitInput("after banish no target") - clearText() } } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } } 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) { 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 +5035,7 @@ val authoredRylween: RylweenModel = } } } otherwise { - writeText( + showTextAndWait( flowText( """ This spell can be used in dungeons only, where there @@ -5318,22 +5043,18 @@ val authoredRylween: RylweenModel = """, ), ) - waitInput("after revelation dungeon-only") - clearText() } } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } } 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 - clearText() writeText( flowText( partyName(caster), @@ -5344,8 +5065,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 +5075,6 @@ val authoredRylween: RylweenModel = " wants you to teleport to.", ), ) - waitInput("after teleport slab") - clearText() ask.wildernessDirection( literalText( "Teleport :", @@ -5371,47 +5089,40 @@ 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() } } } spell(Spells.Priest.earthquake, slot = 7, baseCost = 55, name = "Earthquake") { - withCurrentCasterCost(55) { caster, cost -> + withCurrentCasterCost { 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() 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 { - clearText() writeText( flowText( """ @@ -5432,8 +5143,7 @@ val authoredRylween: RylweenModel = }, ) } otherwise { - writeText("Not enough spell pts!") - pause1s() + writeText("Not enough spell pts! {pause 1s}") clearText() } } @@ -5447,16 +5157,15 @@ val authoredRylween: RylweenModel = effect { ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.AliveOnly, ) { target -> 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() } } } @@ -5468,21 +5177,15 @@ val authoredRylween: RylweenModel = effect { ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.AliveOnly, ) { target -> consumeActiveItem() localInt(potionPoints(target)) { points -> - target.hp -= points - writeText(flowText(partyName(target), " is poisoned for ", points, " hit points.")) - } - whenever(target.hp lte 0) { - target.hp set 0 - target.dead set true - party.memberCount -= 1 + target.wound(points) + writeText(flowText(partyName(target), " is poisoned for ", points, " hit points. {pause 1s}")) } - pause1s() } } } @@ -5494,7 +5197,7 @@ val authoredRylween: RylweenModel = effect { ask.member( literalText { - line("Who? (1-", HuntText.partyMemberMax, ")") + line("Who? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.SpellcasterOnly, accepting = MemberChoiceFilter.AliveOnly, @@ -5502,9 +5205,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,17 +5219,20 @@ 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() - - target.hp -= damage + writeText( + flowText( + partyName(caster), + " chills ", + monsterName(target), + " for ", + damage, + " damage pts. {pause 1s}", + ), + ) - whenever(target.hp lte 0) { - target.hp set 0 - writeText("...KILLED!") - pause600ms() - target.dead set true + target.wound(damage) + whenever(target.dead) { + writeText("...KILLED! {pause 600ms}") } } } @@ -5553,16 +5258,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 +5276,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,13 +5295,9 @@ 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() - target.dead set true - target.hp set 0 + writeText(flowText(partyName(caster), " summons death to take a ", monsterName(target), " away... {pause 2s}")) + writeText("...KILLED! {pause 600ms}") + target.kill() clearText() } } @@ -5616,7 +5311,7 @@ val authoredRylween: RylweenModel = effect { ask.member( literalText { - line("On Whom? (1-", HuntText.partyMemberMax, ")") + line("On Whom? (1-", PartyText.memberCount, ")") }, filter = MemberChoiceFilter.Any, ) { target -> @@ -5624,8 +5319,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 +5330,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 +5351,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) { @@ -5680,7 +5368,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, @@ -5688,17 +5376,14 @@ 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 + target.revive() consumeActiveItem() } otherwise { writeText { - line(partyName(target), " is not dead.") + line(partyName(target), " is not dead. {pause 1s}") } - pause1s() battle.actionRetry set true } } @@ -5711,24 +5396,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 +5423,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 +5443,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 +5480,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 +5488,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 +5495,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 +5516,6 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.thunTemple) { - clearText() showTextAndWait( """ You stand before the ancient temple of Thun. Around you are @@ -5868,11 +5538,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 @@ -5891,7 +5559,6 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.koboldVillage) { - clearText() menu( literalText { line( @@ -5904,18 +5571,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 +5587,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 +5597,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 +5610,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 @@ -6032,7 +5689,6 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.ogreCave) { - clearText() choice.enterOrLeave( literalText { line("You find the cave the half-orc told you about.") @@ -6042,7 +5698,6 @@ val authoredRylween: RylweenModel = line("(L)eave") }, enter = { - clearText() writeText( """ You enter the cave. Piles of treasure are thrown all around. @@ -6053,7 +5708,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 +5719,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 +5763,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 +5771,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 +5781,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 +5797,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 +5819,6 @@ val authoredRylween: RylweenModel = } scene(Scenes.Missions.hobgoblinCaravan) { - clearText() showTextAndWait( "Just before you is a caravan of hobgoblins on white, well-bred horses.", ) @@ -6188,16 +5831,13 @@ 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:") - 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).", @@ -6224,7 +5864,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 +5889,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) @@ -6396,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( """ @@ -6428,8 +6057,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 @@ -6457,7 +6085,7 @@ val authoredRylween: RylweenModel = menu("(B)uy it", "(N)o thanks") { option('B') { pay( - amount = lit(50_000), + amount = 50_000, broke = { writeText( """ @@ -6507,10 +6135,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( """ @@ -6518,14 +6147,15 @@ 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") } 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!!! @@ -6575,7 +6205,7 @@ val authoredRylween: RylweenModel = menu("(B)uy it", "(N)o thanks") { option('B') { pay( - amount = lit(10_000), + amount = 10_000, broke = { writeText( """ @@ -6672,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") } @@ -6703,8 +6331,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") } @@ -6728,7 +6358,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") } @@ -6781,11 +6411,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 ", @@ -6883,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, ".") @@ -6905,10 +6530,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 @@ -6950,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, ".") @@ -6980,6 +6602,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( @@ -6989,17 +6653,11 @@ 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() - - foe.hp -= damage + writeText(flowText(partyName(caster), " burns ", monsterName(foe), " for ", damage, " pts! {pause 1s}")) - whenever(foe.hp lte 0) { - foe.hp set 0 - writeText("...KILLED!") - pause600ms() - foe.dead set true + foe.wound(damage) + whenever(foe.dead) { + writeText("...KILLED! {pause 600ms}") } } } 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. + """, + ), + ) + } +} diff --git a/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt b/game/src/test/kotlin/rylween/RylweenCompiledGameLedgerTest.kt index eb722b2c..ee3f7677 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 == 22) check(nextDsl.rewards.size == 1) check( nextDsl.rewards @@ -210,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) @@ -357,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") @@ -490,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 @@ -545,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()) { @@ -566,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 } == @@ -2457,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" @@ -2942,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/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/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/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/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/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-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/BattleRunner.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/BattleRunner.kt index d9afe576..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 @@ -102,6 +103,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, @@ -360,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(), ) @@ -391,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(), ) @@ -404,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) @@ -447,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) @@ -493,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 @@ -569,7 +564,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 +578,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 +589,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), ) } @@ -602,13 +597,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) @@ -628,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 += @@ -638,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)) @@ -662,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))) } @@ -780,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 -> @@ -812,7 +812,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() } @@ -875,7 +882,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, ) @@ -957,34 +964,43 @@ 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()) } + // 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 @@ -1091,17 +1107,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) @@ -1109,6 +1117,7 @@ internal class BattleRunner( private fun spellChoiceLines( member: CompiledPartyMember, spells: List, + party: PartyState, ): List = screen.choiceMenuLines( prompt = emptyList(), @@ -1116,7 +1125,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 = @@ -1207,9 +1218,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/main/kotlin/rylween/runtime/CastleRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/CastleRuntime.kt index 6ecb6a62..60af782a 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 = @@ -211,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) @@ -341,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.mapTo(mutableSetOf()) { stair -> stair.digit } + 5 - 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/main/kotlin/rylween/runtime/DungeonRuntime.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/DungeonRuntime.kt index ec9c3b09..ba2c2a5d 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, @@ -375,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/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/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/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/RuntimeSecrets.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RuntimeSecrets.kt index c33ad933..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) @@ -165,5 +168,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/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/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/RylweenRuntimeMain.kt index cd5f252b..084a8bb5 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 @@ -87,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 @@ -1085,89 +1086,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} " + @@ -1672,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 == '!') { @@ -1718,15 +1718,31 @@ 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) + 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}") - screen.showImage(TOWN_MAIN_STREET_IMAGE) 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) @@ -1751,17 +1767,30 @@ 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 -> 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, @@ -1803,7 +1832,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) { @@ -1824,8 +1852,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)} " + @@ -1902,12 +1929,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) } @@ -2344,6 +2367,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/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 f92a5464..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 } @@ -899,8 +896,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) @@ -915,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..3f421dbb 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 { @@ -611,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( diff --git a/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt b/runtimes/runtime/src/main/kotlin/rylween/runtime/UtilityActions.kt index 94f523cc..df605853 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) } @@ -296,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, ) @@ -401,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) @@ -543,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 9805d2fc..3bc515dc 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 { @@ -663,49 +657,51 @@ 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, 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, ) } @@ -745,7 +741,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) { @@ -866,6 +872,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/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) 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 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/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/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/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/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), + ) + } } 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/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt index 59fcec84..e154fd85 100644 --- a/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt +++ b/runtimes/runtime/src/test/kotlin/rylween/runtime/ScriptExecutorTest.kt @@ -66,6 +66,36 @@ 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 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. @@ -77,6 +107,26 @@ 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() @@ -97,6 +147,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 +179,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 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 + } + } +} 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) 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")