From b546f47f0aa36146f0c786370b7359382d35944c Mon Sep 17 00:00:00 2001 From: Caleb LeNoir Date: Fri, 30 Oct 2026 07:02:28 -0400 Subject: [PATCH] Add a fight simulator that plays fights through the engine's own turn loop fight MATCHUP.yml plays one matchup thousands of times on a throwaway in-memory arena, typing attack/go/drink/throw lines into Engine::submit (the told loop, no model) or Engine::play (the mechanics loop), and counts win, death and flight rates with 95% intervals, rounds, hit points left, and damage and blows. --replay SEED prints one fight line by line; --json prints the table as JSON. No rule is copied: the turn loop decides every blow, and a fight is read back off the records it left. tests/sim.rs holds it to the rules' exact odds, per-seed identity of the two loops on fights with no move, determinism, and the blows-to-tally check. --- Cargo.toml | 2 +- README.md | 65 +++++ sim/matchups/careful-vs-naive.yml | 10 + sim/matchups/one-l3-d10.yml | 6 + sim/matchups/three-l1-d6.yml | 6 + sim/matchups/two-l2-d10-flee.yml | 11 + src/bin/fight.rs | 139 +++++++++++ src/lib.rs | 1 + src/sim/arena.rs | 390 ++++++++++++++++++++++++++++++ src/sim/matchup.rs | 346 ++++++++++++++++++++++++++ src/sim/mod.rs | 311 ++++++++++++++++++++++++ src/sim/policy.rs | 226 +++++++++++++++++ src/sim/tally.rs | 278 +++++++++++++++++++++ tests/sim.rs | 186 ++++++++++++++ 14 files changed, 1976 insertions(+), 1 deletion(-) create mode 100644 sim/matchups/careful-vs-naive.yml create mode 100644 sim/matchups/one-l3-d10.yml create mode 100644 sim/matchups/three-l1-d6.yml create mode 100644 sim/matchups/two-l2-d10-flee.yml create mode 100644 src/bin/fight.rs create mode 100644 src/sim/arena.rs create mode 100644 src/sim/matchup.rs create mode 100644 src/sim/mod.rs create mode 100644 src/sim/policy.rs create mode 100644 src/sim/tally.rs create mode 100644 tests/sim.rs diff --git a/Cargo.toml b/Cargo.toml index ace35a7..2f23e43 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ publish = false [dependencies] regex = "1" -rusqlite = { version = "0.40.2", features = ["bundled"] } +rusqlite = { version = "0.40.2", features = ["bundled", "serialize"] } serde_json = { version = "1", features = ["preserve_order"] } sha2 = "0.10" ureq = { version = "3", default-features = false, features = ["rustls"] } diff --git a/README.md b/README.md index 9f196d5..491b21a 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,71 @@ both routes to the no-leak contract over a real socket on this machine. The kept requests of `vectors/kept_requests.json` are sent through the live client too (`tests/vectors/builders.rs`), and go out exactly as stored. +## Measuring fights + +`fight` plays one matchup thousands of times through the engine's own turn +loop and counts what happened. No model is asked, and no rule is copied: it +types fight lines (`attack`, `go`, `drink`, `throw`) into a throwaway game, +and the turn loop decides every blow. A rule is in the simulator as soon as +it is in the engine. + +```sh +cargo run --release --bin fight -- sim/matchups/one-l3-d10.yml +cargo run --release --bin fight -- sim/matchups/one-l3-d10.yml --replay 812 +``` + +``` +one-l3-d10: 2000 fights, seeds 1..2000, told driver, policy attack + rate 95% interval + won 0.230 [0.212, 0.249] + died 0.770 [0.751, 0.788] + fled 0.000 [0.000, 0.002] + rounds mean 3.72 2:118 3:748 4:774 5:301 6:54 7:5 + ... +``` + +A matchup file (`sim/matchups/*.yml`, read by `sim::matchup`) names the +seeds, the player's stat block and what they carry, the foes, and a way of +playing. Its keys are a world file's, so a stat block can be pasted from one, +and `rolled` takes a number from the engine's own roll for each seed. Any +other key of a foe, a carried thing or the story is written into that row as +given, so a column a later rule adds needs no simulator change. + +- **The arena** is the sweep's one-room world + (`parity/worlds/a-chamber-of-one-room.sql`) with the foes in its first room + and its second room written, to run to (`sim::arena`). It is built once and + kept as an image of its database, and each fight opens a fresh copy, so + nothing one fight wrote reaches the next. +- **Seeds.** A fight's playthrough id is its seed plus + `sim::arena::SEED_BASE`, and every blow's die is seeded off the + playthrough, so a seed always plays the same fight, on any number of + threads. `--replay SEED` prints that fight line by line. +- **Drivers.** `told` (the default) plays each line with `Engine::submit` in + a game the player narrates, slashed, with a `model::Replay` that holds no + replies: the loop the browser plays, which moves the story's clock five + minutes a line. `mechanics` plays `Engine::play`, a little faster, and its + clock does not move between fights. Anything that hangs on time is + measured on `told`. With no move in the fight, the two give the same fight + seed for seed. A move does not: the told loop writes its arrival before the + parting blows, so they are thrown at a later time, from other dice. +- **Policies** (`sim::policy`): `attack` the first foe standing every line; + `flee_below` (`hp: N`) to the next room; `drink_below` (`hp: N`) a healing + thing while one is carried; `throw_first`, which tries each carried + throwable once; `naive`, which drinks below 30%; and `careful`, which drinks + at half and leaves once one more round could kill (hit points at or below + the sum of the live foes' hit dice). The options combine: + `{kind: flee_below, hp: 6, drink_below: 9, throw_first: true}`. A refused + line is an error, not a turn, because it buys no riposte. +- **Results** (`sim::tally`): win, death and flight rates with Wilson 95% + intervals, rounds and hit points left (mean and histogram), and damage and + blows on each side. `--json` prints the same as JSON. `--seeds A..B`, + `--driver` and `--threads` override the file's values. + +`tests/sim.rs` holds it to four things: three matchups' exact odds, worked +out from the rules by hand, within four standard errors; per-seed identity +of the two drivers on fights with no move; the same seed playing the same +fight; and a fight's tally agreeing with its `playthrough_blows` rows. + ## Rules for changing it - Draw only from `random::Random`. Any other generator rolls different dice. diff --git a/sim/matchups/careful-vs-naive.yml b/sim/matchups/careful-vs-naive.yml new file mode 100644 index 0000000..286ad97 --- /dev/null +++ b/sim/matchups/careful-vs-naive.yml @@ -0,0 +1,10 @@ +# The dungeon studies' careful player, at the scale of one fight, against +# two level-1 foes of a rolled hit die, with one healing draught. Play it +# again with `policy: naive` to compare. +seeds: 1..2000 +player: + carrying: + - {name: healing draught, use_kind: healing} +foes: + - {count: 2, stats: {level: 1, hit_die: rolled}} +policy: careful diff --git a/sim/matchups/one-l3-d10.yml b/sim/matchups/one-l3-d10.yml new file mode 100644 index 0000000..b45e686 --- /dev/null +++ b/sim/matchups/one-l3-d10.yml @@ -0,0 +1,6 @@ +# The house body (level 3, d8, 18 hit points) against one level-3 d10 foe, +# attacking to the end. Exact P(win), worked out from the rules: 0.2338. +seeds: 1..2000 +foes: + - {count: 1, stats: {level: 3, hit_die: 10}} +policy: attack diff --git a/sim/matchups/three-l1-d6.yml b/sim/matchups/three-l1-d6.yml new file mode 100644 index 0000000..ed3cecf --- /dev/null +++ b/sim/matchups/three-l1-d6.yml @@ -0,0 +1,6 @@ +# The house body against three level-1 d6 foes, attacking the first one +# standing to the end. Exact P(win), worked out from the rules: 0.1914. +seeds: 1..2000 +foes: + - {count: 3, stats: {level: 1, hit_die: 6}} +policy: attack diff --git a/sim/matchups/two-l2-d10-flee.yml b/sim/matchups/two-l2-d10-flee.yml new file mode 100644 index 0000000..edad74a --- /dev/null +++ b/sim/matchups/two-l2-d10-flee.yml @@ -0,0 +1,11 @@ +# The house body against two level-2 d10 foes, with a healing draught and a +# brick in hand: throw the brick first, drink at 9 hit points or below, and +# run to the next room at 6 or below. +seeds: 1..1000 +player: + carrying: + - {name: healing draught, use_kind: healing} + - {name: brick, bulk: heavy} +foes: + - {count: 2, stats: {level: 2, hit_die: 10}} +policy: {kind: flee_below, hp: 6, drink_below: 9, throw_first: true} diff --git a/src/bin/fight.rs b/src/bin/fight.rs new file mode 100644 index 0000000..a2c90cb --- /dev/null +++ b/src/bin/fight.rs @@ -0,0 +1,139 @@ +//! The fight simulator (`renderedstep_engine::sim`): plays one matchup's +//! fights through the engine's own turn loop, with no model, and prints +//! what they did. +//! +//! `fight MATCHUP.yml` plays every seed the file names and prints a table: +//! how often the player won, died and got away, with 95% intervals, how +//! many rounds a fight took, the hit points the survivors kept, and the +//! damage and blows on each side. `--json` prints the same as JSON. +//! +//! `--seeds A..B`, `--driver told|mechanics` and `--threads N` stand in for +//! the file's own. +//! +//! `fight MATCHUP.yml --replay SEED` plays that one fight again and prints +//! it line by line: what was typed, every blow, and everybody's hit points. + +use renderedstep_engine::sim::{self, matchup::Matchup, tally, Driver}; +use std::path::Path; +use std::process::ExitCode; +use std::time::Instant; + +const USAGE: &str = "usage: fight MATCHUP.yml [--seeds A..B] [--driver told|mechanics] \ + [--threads N] [--json] [--replay SEED]"; + +fn main() -> ExitCode { + // SQLite counts every allocation under one lock for the whole process, + // which holds fights on several threads to the speed of about three. + // Nothing here reads the count, so it is turned off before the first + // connection opens (a later call is refused, and only costs speed). + unsafe { + rusqlite::ffi::sqlite3_config(rusqlite::ffi::SQLITE_CONFIG_MEMSTATUS, 0); + } + match run(std::env::args().skip(1).collect()) { + Ok(()) => ExitCode::SUCCESS, + Err(message) => { + eprintln!("{message}"); + ExitCode::FAILURE + } + } +} + +fn run(args: Vec) -> Result<(), String> { + let mut file = None; + let mut json = false; + let mut replay = None; + let mut seeds = None; + let mut driver = None; + let mut threads = None; + let mut args = args.into_iter(); + while let Some(arg) = args.next() { + let mut value = || { + args.next() + .ok_or_else(|| format!("{arg} needs a value\n{USAGE}")) + }; + match arg.as_str() { + "--json" => json = true, + "--replay" => { + replay = Some( + value()? + .parse::() + .map_err(|_| "--replay takes a seed".to_string())?, + ) + } + "--seeds" => seeds = Some(sim::matchup::parse_seeds(&value()?)?), + "--driver" => { + let name = value()?; + driver = Some( + Driver::parse(&name) + .ok_or_else(|| format!("--driver {name:?} is told or mechanics"))?, + ) + } + "--threads" => { + threads = Some( + value()? + .parse::() + .map_err(|_| "--threads takes a number".to_string())?, + ) + } + _ if arg.starts_with("--") || file.is_some() => return Err(USAGE.to_string()), + _ => file = Some(arg), + } + } + let file = file.ok_or(USAGE)?; + let mut matchup = Matchup::load(Path::new(&file))?; + if let Some(seeds) = seeds { + matchup.seeds = seeds; + } + if let Some(driver) = driver { + matchup.driver = driver; + } + if let Some(threads) = threads { + matchup.threads = threads; + } + + if let Some(seed) = replay { + if seed < 1 { + return Err("--replay takes a seed of 1 or more".into()); + } + let fight = sim::replay(&matchup, seed)?; + if json { + println!("{}", tally::replay_json(&fight)); + } else { + print!("{}", tally::replay(&fight)); + } + return Ok(()); + } + + let started = Instant::now(); + let fights = sim::run(&matchup, &matchup.seeds, matchup.threads)?; + let seconds = started.elapsed().as_secs_f64(); + let summary = tally::Summary::of(&fights); + let (first, last) = ( + matchup.seeds.first().copied().unwrap_or_default(), + matchup.seeds.last().copied().unwrap_or_default(), + ); + if json { + let mut out = summary.json(); + out["matchup"] = matchup.name.clone().into(); + out["driver"] = matchup.driver.as_str().into(); + out["seeds"] = format!("{first}..{last}").into(); + out["policy"] = matchup.policy.kind.clone().into(); + println!("{out}"); + } else { + let heading = format!( + "{}: {} fights, seeds {first}..{last}, {} driver, policy {}", + matchup.name, + fights.len(), + matchup.driver.as_str(), + matchup.policy.kind, + ); + print!("{}", summary.text(&heading)); + eprintln!( + " ({:.1}s, {:.0} fights/s on {} thread(s))", + seconds, + fights.len() as f64 / seconds.max(1e-9), + matchup.threads.max(1) + ); + } + Ok(()) +} diff --git a/src/lib.rs b/src/lib.rs index 9b13772..bcace85 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -74,6 +74,7 @@ pub mod roll; pub mod room; pub mod schemas; pub mod shuffle_connections; +pub mod sim; pub mod slash_menu; pub mod spot; pub mod stat_block; diff --git a/src/sim/arena.rs b/src/sim/arena.rs new file mode 100644 index 0000000..7dedaaf --- /dev/null +++ b/src/sim/arena.rs @@ -0,0 +1,390 @@ +//! The room a simulated fight is played in: the engine sweep's one-room +//! world (`parity/worlds/a-chamber-of-one-room.sql`), with the player's +//! stat block and what they carry set from the matchup, its foes standing in +//! the first room, and every room written, so that a move into the second +//! asks no room writer. +//! +//! The arena is built once and kept as an image of its database. Each fight +//! opens a fresh copy of that image in memory ([`Arena::fresh`]), so nothing +//! one fight wrote, not even a row of the world it changed, reaches the +//! next: reopening the image costs a fraction of loading the world's SQL +//! again. A world fixture at an older schema is refused when the copy is +//! opened (`store::Store::from_connection`), so the arena cannot fall +//! behind a migration unnoticed. + +use super::matchup::{Matchup, Stat, Stats}; +use super::Blow; +use crate::engine::Engine; +use crate::stat_block::{self, StatBlock}; +use rusqlite::{params, Connection, ToSql, MAIN_DB}; +use serde_json::{Map, Value}; + +/// The world every fight is played in. +pub const WORLD: &str = include_str!("../../parity/worlds/a-chamber-of-one-room.sql"); + +/// Its story's title. +pub const STORY: &str = "A Chamber of One Room (engine sweep)"; + +/// A fight's playthrough id is this plus its seed: the dice of every blow +/// are seeded off the playthrough, so the seed picks the fight. +pub const SEED_BASE: i64 = 1_000_000_000; + +/// When the rows the arena writes were made. +const WRITTEN_AT: &str = "2026-10-02 13:25:38"; + +/// A body the arena put in the fight. +#[derive(Clone, Debug)] +struct Body { + id: i64, + name: String, + stats: Stats, +} + +/// The arena's database image, and what a fight needs to know of it. +#[derive(Debug)] +pub struct Arena { + image: Vec, + pub story: i64, + /// The room the fight starts in. + pub room: i64, + /// The written room beside it, to run to. + pub exit: i64, + pub exit_name: String, + player: Body, + foes: Vec, + /// Carried things by name, and whether each one heals. + carrying: Vec<(String, bool)>, +} + +impl Arena { + /// Builds the arena for a matchup. + pub fn build(matchup: &Matchup) -> Result { + let failed = |error: rusqlite::Error| format!("the arena: {error}"); + let conn = Connection::open_in_memory().map_err(failed)?; + conn.execute_batch(WORLD).map_err(failed)?; + let story: i64 = conn + .query_row("SELECT id FROM stories WHERE title = ?1", [STORY], |row| { + row.get(0) + }) + .map_err(failed)?; + let (player, race): (i64, i64) = conn + .query_row( + "SELECT id, race_id FROM characters WHERE story_id = ?1 AND is_protagonist = 1", + [story], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .map_err(failed)?; + let rooms: Vec<(i64, String, String)> = conn + .prepare("SELECT id, name, detail_level FROM locations WHERE story_id = ?1 ORDER BY id") + .and_then(|mut statement| { + statement + .query_map([story], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))? + .collect() + }) + .map_err(failed)?; + let room = rooms + .iter() + .find(|(_, _, detail)| detail == "realized") + .map(|(id, _, _)| *id) + .ok_or("the arena has no written room to start in")?; + let (exit, exit_name) = rooms + .iter() + .find(|(id, _, _)| *id != room) + .map(|(id, name, _)| (*id, name.clone())) + .ok_or("the arena has no second room to run to")?; + conn.execute( + "UPDATE locations SET detail_level = 'realized', \ + description = COALESCE(description, teaser) WHERE story_id = ?1", + [story], + ) + .map_err(failed)?; + update(&conn, "stories", story, &matchup.story)?; + update(&conn, "characters", player, &fixed(&matchup.player))?; + let mut carrying = Vec::new(); + for thing in &matchup.carrying { + let mut values = vec![ + ("created_at".to_string(), Value::from(WRITTEN_AT)), + ("updated_at".to_string(), Value::from(WRITTEN_AT)), + ("character_id".to_string(), Value::from(player)), + ]; + values.extend(thing.iter().cloned()); + insert(&conn, "items", &values)?; + let name = |key: &str| { + thing + .iter() + .find(|(column, _)| column == key) + .and_then(|(_, value)| value.as_str()) + .map(str::to_string) + }; + carrying.push(( + name("name").unwrap_or_default(), + name("use_kind").as_deref() == Some("healing"), + )); + } + let names = matchup.foe_names(); + let specs = matchup + .foes + .iter() + .flat_map(|foes| std::iter::repeat_n(foes, foes.count)); + let mut foes = Vec::new(); + for (name, spec) in names.into_iter().zip(specs) { + let mut values = vec![ + ("created_at".to_string(), Value::from(WRITTEN_AT)), + ("updated_at".to_string(), Value::from(WRITTEN_AT)), + ("fullname".to_string(), Value::from(name.clone())), + ("hostile".to_string(), Value::from(true)), + ("is_protagonist".to_string(), Value::from(false)), + ("location_id".to_string(), Value::from(room)), + ("race_id".to_string(), Value::from(race)), + ("story_id".to_string(), Value::from(story)), + ]; + values.extend(fixed(&spec.stats)); + for (column, value) in &spec.columns { + match values.iter_mut().find(|(key, _)| key == column) { + Some(slot) => slot.1 = value.clone(), + None => values.push((column.clone(), value.clone())), + } + } + let id = insert(&conn, "characters", &values)?; + foes.push(Body { + id, + name, + stats: spec.stats.clone(), + }); + } + let image = conn.serialize(MAIN_DB).map_err(failed)?.to_vec(); + Ok(Arena { + image, + story, + room, + exit, + exit_name, + player: Body { + id: player, + name: String::new(), + stats: matchup.player.clone(), + }, + foes, + carrying, + }) + } + + /// A fresh copy of the arena for one seed: its rolled numbers thrown, + /// and the next playthrough to start numbered for the seed. + pub fn fresh(&self, seed: i64) -> Result { + let failed = |error: rusqlite::Error| format!("seed {seed}: the arena: {error}"); + let mut conn = Connection::open_in_memory().map_err(failed)?; + conn.deserialize_read_exact(MAIN_DB, &self.image[..], self.image.len(), false) + .map_err(failed)?; + for body in self.bodies() { + let rolled = rolled(&body.stats, self.roll(seed, body.id)); + update(&conn, "characters", body.id, &rolled)?; + } + conn.execute( + "UPDATE sqlite_sequence SET seq = ?1 WHERE name = 'playthroughs'", + [SEED_BASE + seed - 1], + ) + .map_err(failed)?; + Engine::from_connection(conn).map_err(|error| format!("seed {seed}: {error}")) + } + + fn bodies(&self) -> impl Iterator { + std::iter::once(&self.player).chain(&self.foes) + } + + /// The engine's own roll of a body's stat block for one seed. + fn roll(&self, seed: i64, body: i64) -> StatBlock { + let place = self.bodies().position(|b| b.id == body).unwrap_or_default(); + stat_block::roll(self.story, seed, place as i64) + } + + /// A foe's hit die in the fight a seed plays. + pub fn hit_die_of(&self, name: &str, seed: i64) -> i64 { + self.foes + .iter() + .find(|foe| foe.name == name) + .map(|foe| match foe.stats.hit_die { + Stat::Fixed(die) => die, + Stat::Rolled => self.roll(seed, foe.id).hit_die, + }) + .unwrap_or_default() + } + + /// The thing is carried and heals. + pub fn heals(&self, name: &str) -> bool { + self.carrying + .iter() + .any(|(thing, heals)| thing == name && *heals) + } + + /// The thing is carried and does not heal, so it is for throwing. + pub fn throws(&self, name: &str) -> bool { + self.carrying + .iter() + .any(|(thing, heals)| thing == name && !*heals) + } + + /// The blows this game has struck since the one numbered `seen`, which + /// moves to the last. + pub fn blows(&self, engine: &Engine, game: i64, seen: &mut i64) -> Result, String> { + let mut statement = engine + .store() + .connection() + .prepare_cached( + "SELECT b.id, a.fullname, t.fullname, b.damage, b.hp_after, b.attacker_id, \ + b.target_id FROM playthrough_blows b \ + JOIN characters a ON a.id = b.attacker_id \ + JOIN characters t ON t.id = b.target_id \ + WHERE b.playthrough_id = ?1 AND b.id > ?2 ORDER BY b.id", + ) + .map_err(|error| error.to_string())?; + let player = self.player.id; + let rows = statement + .query_map(params![game, *seen], |row| { + Ok(( + row.get::<_, i64>(0)?, + Blow { + attacker: row.get(1)?, + target: row.get(2)?, + damage: row.get(3)?, + hp_after: row.get(4)?, + by_player: row.get::<_, i64>(5)? == player, + on_player: row.get::<_, i64>(6)? == player, + }, + )) + }) + .and_then(|rows| rows.collect::, _>>()) + .map_err(|error| error.to_string())?; + if let Some((last, _)) = rows.last() { + *seen = *last; + } + Ok(rows.into_iter().map(|(_, blow)| blow).collect()) + } + + /// Every foe's hit points in a game, by name, the dead at zero. + pub fn foes_hp(&self, engine: &Engine, game: i64) -> Result, String> { + let conn = engine.store().connection(); + self.foes + .iter() + .map(|foe| { + let current: Option = conn + .query_row( + "SELECT hp_current FROM playthrough_vitals \ + WHERE playthrough_id = ?1 AND character_id = ?2", + [game, foe.id], + |row| row.get(0), + ) + .ok(); + let hp = match current { + Some(hp) => hp, + None => { + let (level, hit_die): (i64, i64) = conn + .query_row( + "SELECT level, hit_die FROM characters WHERE id = ?1", + [foe.id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .map_err(|error| error.to_string())?; + let mut row = Map::new(); + row.insert("level".into(), Value::from(level)); + row.insert("hit_die".into(), Value::from(hit_die)); + crate::playthrough::max_hp(&row).unwrap_or_default() + } + }; + Ok((foe.name.clone(), hp)) + }) + .collect() + } +} + +/// A stat block's fixed numbers as columns. +fn fixed(stats: &Stats) -> Vec<(String, Value)> { + stats + .columns() + .into_iter() + .filter_map(|(column, stat)| match stat { + Stat::Fixed(n) => Some((column.to_string(), Value::from(n))), + Stat::Rolled => None, + }) + .collect() +} + +/// A stat block's rolled numbers as columns, taken from one roll. +fn rolled(stats: &Stats, roll: StatBlock) -> Vec<(String, Value)> { + let thrown = [ + roll.level, + roll.hit_die, + roll.strength, + roll.dexterity, + roll.will, + ]; + stats + .columns() + .into_iter() + .zip(thrown) + .filter(|((_, stat), _)| *stat == Stat::Rolled) + .map(|((column, _), n)| (column.to_string(), Value::from(n))) + .collect() +} + +fn quoted(column: &str) -> String { + format!("\"{}\"", column.replace('"', "\"\"")) +} + +/// A JSON value as SQLite stores it: a flag as 0 or 1. +fn sql(value: &Value) -> rusqlite::types::Value { + use rusqlite::types::Value as Sql; + match value { + Value::Bool(flag) => Sql::Integer(i64::from(*flag)), + Value::Number(n) => n + .as_i64() + .map(Sql::Integer) + .unwrap_or_else(|| Sql::Real(n.as_f64().unwrap_or_default())), + Value::String(text) => Sql::Text(text.clone()), + _ => Sql::Null, + } +} + +fn update( + conn: &Connection, + table: &str, + id: i64, + values: &[(String, Value)], +) -> Result<(), String> { + if values.is_empty() { + return Ok(()); + } + let set: Vec = values + .iter() + .enumerate() + .map(|(n, (column, _))| format!("{} = ?{}", quoted(column), n + 1)) + .collect(); + let mut bound: Vec = values.iter().map(|(_, v)| sql(v)).collect(); + bound.push(rusqlite::types::Value::Integer(id)); + let sql_text = format!( + "UPDATE {table} SET {} WHERE id = ?{}", + set.join(", "), + values.len() + 1 + ); + let refs: Vec<&dyn ToSql> = bound.iter().map(|v| v as &dyn ToSql).collect(); + conn.execute(&sql_text, refs.as_slice()) + .map(|_| ()) + .map_err(|error| format!("the arena: {table}: {error}")) +} + +fn insert(conn: &Connection, table: &str, values: &[(String, Value)]) -> Result { + let columns: Vec = values.iter().map(|(column, _)| quoted(column)).collect(); + let marks: Vec = (1..=values.len()).map(|n| format!("?{n}")).collect(); + let bound: Vec = values.iter().map(|(_, v)| sql(v)).collect(); + let refs: Vec<&dyn ToSql> = bound.iter().map(|v| v as &dyn ToSql).collect(); + conn.execute( + &format!( + "INSERT INTO {table} ({}) VALUES ({})", + columns.join(", "), + marks.join(", ") + ), + refs.as_slice(), + ) + .map_err(|error| format!("the arena: {table}: {error}"))?; + Ok(conn.last_insert_rowid()) +} diff --git a/src/sim/matchup.rs b/src/sim/matchup.rs new file mode 100644 index 0000000..59ee806 --- /dev/null +++ b/src/sim/matchup.rs @@ -0,0 +1,346 @@ +//! A matchup file: who fights whom, how the player plays, and which seeds. +//! +//! ```yaml +//! seeds: 1..2000 # playthrough seeds; or a count, for 1..count +//! driver: told # told (default) | mechanics +//! threads: 4 # default: every core; the fights are the same +//! story: {} # columns of the arena's story, set as given +//! player: +//! stats: {level: 3, hit_die: 8, strength: 10, dexterity: rolled, will: 10} +//! carrying: [{name: healing draught, use_kind: healing}, {name: brick, bulk: heavy}] +//! foes: +//! - {count: 2, stats: {level: 2, hit_die: 10}} +//! policy: {kind: flee_below, hp: 6, drink_below: 9} +//! ``` +//! +//! The keys are a world file's: a stat block is pasted from one as it +//! stands. `rolled` takes that number from the engine's own roll +//! (`stat_block::roll`), thrown for each seed. Any other key of a foe, a +//! carried thing or the story is a column of its row and is written as +//! given, so a column a later migration adds needs no change here. + +use super::policy::Policy; +use super::Driver; +use serde_json::Value; +use std::path::Path; +use yaml_rust2::{Yaml, YamlLoader}; + +/// One number of a stat block. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stat { + Fixed(i64), + /// Thrown for each seed by `stat_block::roll`. + Rolled, +} + +/// A stat block, in `stat_block::ABILITIES` order after level and hit die. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Stats { + pub level: Stat, + pub hit_die: Stat, + pub strength: Stat, + pub dexterity: Stat, + pub will: Stat, +} + +impl Stats { + /// The house body: level 3, d8, every ability 10. + pub fn player() -> Stats { + Stats { + level: Stat::Fixed(crate::stat_block::PROTAGONIST_LEVEL), + hit_die: Stat::Fixed(crate::stat_block::PROTAGONIST_HIT_DIE), + strength: Stat::Fixed(10), + dexterity: Stat::Fixed(10), + will: Stat::Fixed(10), + } + } + + /// A foe with nothing said: level 1, d8, every ability 10. + pub fn foe() -> Stats { + Stats { + level: Stat::Fixed(crate::stat_block::STARTING_LEVEL), + ..Stats::player() + } + } + + /// The columns, in order. + pub fn columns(&self) -> [(&'static str, Stat); 5] { + [ + ("level", self.level), + ("hit_die", self.hit_die), + ("strength", self.strength), + ("dexterity", self.dexterity), + ("will", self.will), + ] + } + + fn read(defaults: Stats, yaml: &Yaml, at: &str) -> Result { + let mut stats = defaults; + if yaml.is_badvalue() || yaml.is_null() { + return Ok(stats); + } + let map = yaml + .as_hash() + .ok_or_else(|| format!("{at}.stats is not a map"))?; + for (key, value) in map { + let key = key.as_str().unwrap_or_default(); + let stat = match value { + Yaml::Integer(n) => Stat::Fixed(*n), + Yaml::String(word) if word == "rolled" => Stat::Rolled, + _ => return Err(format!("{at}.stats.{key} is a whole number or \"rolled\"")), + }; + let slot = match key { + "level" => &mut stats.level, + "hit_die" => &mut stats.hit_die, + "strength" => &mut stats.strength, + "dexterity" => &mut stats.dexterity, + "will" => &mut stats.will, + _ => return Err(format!("{at}.stats.{key} is not a stat")), + }; + *slot = stat; + } + Ok(stats) + } +} + +/// A run of identical foes. +#[derive(Clone, Debug, PartialEq)] +pub struct Foes { + pub count: usize, + /// Each one's full name is this and a letter: `Foe A`, `Foe B`. + pub name: String, + pub stats: Stats, + /// Other columns of each one's `characters` row. + pub columns: Vec<(String, Value)>, +} + +/// One fight's setup, and how many times to play it. +#[derive(Clone, Debug, PartialEq)] +pub struct Matchup { + pub name: String, + pub seeds: Vec, + pub driver: Driver, + pub threads: usize, + /// Columns of the arena's `stories` row. + pub story: Vec<(String, Value)>, + pub player: Stats, + /// Each carried thing's `items` columns; `name` is required. + pub carrying: Vec>, + pub foes: Vec, + pub policy: Policy, +} + +impl Matchup { + /// One player at the house body against `foes`, attacking to the end, + /// on the told loop, over seeds 1 to 1000, on every core. + pub fn new(name: &str, foes: Vec) -> Matchup { + Matchup { + name: name.to_string(), + seeds: (1..=1000).collect(), + driver: Driver::Told, + threads: std::thread::available_parallelism().map_or(1, |n| n.get()), + story: Vec::new(), + player: Stats::player(), + carrying: Vec::new(), + foes, + policy: Policy { + kind: "attack".into(), + ..Policy::default() + }, + } + } + + pub fn load(path: &Path) -> Result { + let source = std::fs::read_to_string(path) + .map_err(|error| format!("{}: {error}", path.display()))?; + let name = path + .file_stem() + .and_then(|stem| stem.to_str()) + .unwrap_or("matchup"); + Matchup::parse(name, &source) + } + + /// Reads a matchup from its YAML text. + pub fn parse(name: &str, source: &str) -> Result { + let inner = |source: &str| -> Result { + let document = YamlLoader::load_from_str(source) + .map_err(|error| error.to_string())? + .into_iter() + .next() + .ok_or("an empty file")?; + let mut matchup = Matchup::new(name, Vec::new()); + if !document["seeds"].is_badvalue() { + matchup.seeds = seeds(&document["seeds"])?; + } + if let Some(driver) = document["driver"].as_str() { + matchup.driver = Driver::parse(driver) + .ok_or_else(|| format!("driver {driver:?} is told or mechanics"))?; + } + if let Some(threads) = document["threads"].as_i64() { + matchup.threads = usize::try_from(threads).map_err(|_| "threads < 0")?; + } + matchup.story = columns(&document["story"], "story", &[])?; + let player = &document["player"]; + matchup.player = Stats::read(Stats::player(), &player["stats"], "player")?; + if let Some(things) = player["carrying"].as_vec() { + for (n, thing) in things.iter().enumerate() { + let at = format!("player.carrying.{n}"); + let thing = columns(thing, &at, &[])?; + if !thing.iter().any(|(key, _)| key == "name") { + return Err(format!("{at} has no name")); + } + matchup.carrying.push(thing); + } + } + let foes = document["foes"].as_vec().ok_or("foes is not a list")?; + for (n, foe) in foes.iter().enumerate() { + let at = format!("foes.{n}"); + let count = foe["count"].as_i64().unwrap_or(1); + matchup.foes.push(Foes { + count: usize::try_from(count).map_err(|_| format!("{at}.count < 0"))?, + name: foe["name"].as_str().unwrap_or("Foe").to_string(), + stats: Stats::read(Stats::foe(), &foe["stats"], &at)?, + columns: columns(foe, &at, &["count", "name", "stats"])?, + }); + } + if !document["policy"].is_badvalue() { + matchup.policy = Policy::read(&document["policy"])?; + } + Ok(matchup) + }; + inner(source).map_err(|error| format!("{name}: {error}")) + } + + /// Every foe's full name, in the order their rows are written. + pub fn foe_names(&self) -> Vec { + let mut letters = 0..; + self.foes + .iter() + .flat_map(|foes| { + let name = foes.name.clone(); + (0..foes.count).map(move |_| name.clone()) + }) + .map(|name| format!("{name} {}", letter(letters.next().unwrap_or_default()))) + .collect() + } +} + +/// A, B, ... Z, then AA, AB: a name the grammar cannot read as a number. +fn letter(n: usize) -> String { + let alphabet = b'A'..=b'Z'; + let width = alphabet.len(); + let mut n = n; + let mut name = Vec::new(); + loop { + name.insert(0, b'A' + (n % width) as u8); + if n < width { + break; + } + n = n / width - 1; + } + String::from_utf8(name).unwrap_or_default() +} + +/// `A..B` (inclusive), `A..=B`, or a count `N` for `1..N`. +pub fn seeds(yaml: &Yaml) -> Result, String> { + match yaml { + Yaml::Integer(count) => Ok((1..=*count).collect()), + Yaml::String(range) => parse_seeds(range), + _ => Err("seeds is a range A..B or a count".into()), + } +} + +/// `A..B` (inclusive), `A..=B`, or a count `N` for `1..N`. +pub fn parse_seeds(range: &str) -> Result, String> { + let bad = || format!("seeds {range:?} is a range A..B or a count"); + let seeds: Vec = match range.split_once("..") { + Some((from, to)) => { + let from: i64 = from.trim().parse().map_err(|_| bad())?; + let to: i64 = to + .trim_start_matches('=') + .trim() + .parse() + .map_err(|_| bad())?; + (from..=to).collect() + } + None => (1..=range.trim().parse::().map_err(|_| bad())?).collect(), + }; + if seeds.is_empty() || seeds[0] < 1 { + return Err(format!("seeds {range:?} must start at 1 or more")); + } + Ok(seeds) +} + +/// A map's keys as columns, less `skip`. +fn columns(yaml: &Yaml, at: &str, skip: &[&str]) -> Result, String> { + if yaml.is_badvalue() || yaml.is_null() { + return Ok(Vec::new()); + } + let map = yaml.as_hash().ok_or_else(|| format!("{at} is not a map"))?; + let mut out = Vec::new(); + for (key, value) in map { + let key = key + .as_str() + .ok_or_else(|| format!("{at} has a key that is not a word"))?; + if skip.contains(&key) { + continue; + } + let value = match value { + Yaml::Integer(n) => Value::from(*n), + Yaml::Real(text) => text + .parse::() + .map(Value::from) + .map_err(|_| format!("{at}.{key} is not a number"))?, + Yaml::String(text) => Value::from(text.clone()), + Yaml::Boolean(flag) => Value::from(*flag), + Yaml::Null => Value::Null, + _ => return Err(format!("{at}.{key} is not one value")), + }; + out.push((key.to_string(), value)); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_a_matchup() { + let matchup = Matchup::parse( + "m", + "seeds: 5..7\ndriver: mechanics\nplayer:\n stats: {level: 4, dexterity: rolled}\n \ + carrying: [{name: draught, use_kind: healing}]\nfoes:\n - {count: 2, stats: {hit_die: 10}, hostile: true}\n\ + policy: {kind: flee_below, hp: 6}\n", + ) + .unwrap(); + assert_eq!(matchup.seeds, vec![5, 6, 7]); + assert_eq!(matchup.driver, Driver::Mechanics); + assert_eq!(matchup.player.level, Stat::Fixed(4)); + assert_eq!(matchup.player.dexterity, Stat::Rolled); + assert_eq!(matchup.foes[0].count, 2); + assert_eq!(matchup.foes[0].stats.hit_die, Stat::Fixed(10)); + assert_eq!(matchup.foes[0].stats.level, Stat::Fixed(1)); + assert_eq!( + matchup.foes[0].columns, + vec![("hostile".to_string(), Value::from(true))] + ); + assert_eq!(matchup.foe_names(), vec!["Foe A", "Foe B"]); + assert_eq!(matchup.policy.flee_below, Some(6)); + } + + #[test] + fn names_past_z() { + assert_eq!(letter(0), "A"); + assert_eq!(letter(25), "Z"); + assert_eq!(letter(26), "AA"); + assert_eq!(letter(27), "AB"); + } + + #[test] + fn refuses_a_seed_below_one() { + assert!(parse_seeds("0..3").is_err()); + assert_eq!(parse_seeds("3").unwrap(), vec![1, 2, 3]); + assert_eq!(parse_seeds("2..=3").unwrap(), vec![2, 3]); + } +} diff --git a/src/sim/mod.rs b/src/sim/mod.rs new file mode 100644 index 0000000..173cbe1 --- /dev/null +++ b/src/sim/mod.rs @@ -0,0 +1,311 @@ +//! The fight simulator: fights played through the engine's own turn loop, +//! many times over, and counted. +//! +//! A fight is a throwaway game in memory ([`arena`]): a [`matchup::Matchup`] +//! puts the player and their foes in one room of a small world, with a +//! written room beside it to run to. A [`policy::Policy`] types one line a +//! turn (`attack`, `go`, `drink`, `throw`), and the line goes through +//! [`Engine::play`] (the mechanics loop, [`Driver::Mechanics`]) or +//! [`Engine::submit`] in a game the player narrates (the told loop the +//! browser plays, [`Driver::Told`]), with no model to ask. Nothing here +//! decides a blow, a riposte, a death or the end of a fight: the turn loop +//! does, and a fight is read back off the records it left. A rule that lands +//! in the engine is therefore in the simulator the moment it lands. +//! +//! A fight is named by its seed, which is its playthrough's id less +//! [`arena::SEED_BASE`]: the dice a blow throws are seeded off the +//! playthrough (`roll::Seed`), so the same seed plays the same fight again. +//! [`tally::Summary`] counts what many fights did. + +pub mod arena; +pub mod matchup; +pub mod policy; +pub mod tally; + +use crate::engine::{Engine, Error}; +use crate::model::Replay; +use crate::outcome::State; +use crate::playthrough::Mode; +use arena::Arena; +use matchup::Matchup; +use policy::{Act, View}; + +/// Which turn loop plays the lines. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Driver { + /// [`Engine::submit`] in a game the player narrates, every line + /// slashed: the loop the browser plays, which moves the story's clock. + Told, + /// [`Engine::play`]: the no-model mechanics loop. Faster, and its clock + /// stands still between fights' closings. + Mechanics, +} + +impl Driver { + pub fn parse(name: &str) -> Option { + match name { + "told" => Some(Driver::Told), + "mechanics" => Some(Driver::Mechanics), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Driver::Told => "told", + Driver::Mechanics => "mechanics", + } + } +} + +/// How a fight ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum End { + /// No foe is left fighting in the room. + Won, + /// The player is dead. + Died, + /// The player stands somewhere else. + Fled, + /// The fight was still going after [`MAX_LINES`] lines. + Stalled, +} + +impl End { + pub const ALL: [End; 4] = [End::Won, End::Died, End::Fled, End::Stalled]; + + pub fn as_str(self) -> &'static str { + match self { + End::Won => "won", + End::Died => "died", + End::Fled => "fled", + End::Stalled => "stalled", + } + } +} + +/// The most lines one fight plays before it is called stalled. +pub const MAX_LINES: usize = 200; + +/// One blow, as its `playthrough_blows` row has it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Blow { + pub attacker: String, + pub target: String, + /// The die as thrown, before the target's hit points stop it at zero. + pub damage: i64, + pub hp_after: i64, + /// The player struck it. + pub by_player: bool, + /// The player took it. + pub on_player: bool, +} + +/// One line the policy typed, and what it left. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Line { + pub typed: String, + pub blows: Vec, + /// The player's hit points after the line. + pub hp: i64, + /// Every foe's hit points after the line, by name, the dead at zero. + pub foes: Vec<(String, i64)>, +} + +/// One fight, read off the records it left. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Fight { + pub seed: i64, + pub end: End, + /// Lines typed, each one a round. + pub lines: usize, + pub max_hp: i64, + pub hp_left: i64, + /// Damage as thrown, summed over the blows the player struck and took. + pub damage_dealt: i64, + pub damage_taken: i64, + pub blows_struck: usize, + pub blows_taken: usize, + pub drinks: usize, + pub throws: usize, + /// Every line, kept only when the fight was asked for line by line. + pub log: Vec, +} + +/// Plays one fight on a fresh copy of the arena. +pub fn fight(arena: &Arena, matchup: &Matchup, seed: i64, keep_log: bool) -> Result { + let failed = |error: Error| format!("seed {seed}: {error}"); + let mut engine = arena.fresh(seed)?; + let mode = match matchup.driver { + Driver::Told => Mode::PlayerNarrates, + Driver::Mechanics => Mode::Narrated, + }; + let game = engine.start_in(arena.story, mode).map_err(failed)?; + let mut state = engine.read(game, Vec::new()).map_err(failed)?.state; + let max_hp = state.hp.ok_or_else(|| { + format!("seed {seed}: the player has no stat block, so there is nothing to fight with") + })?; + let mut fight = Fight { + seed, + end: End::Stalled, + lines: 0, + max_hp, + hp_left: max_hp, + damage_dealt: 0, + damage_taken: 0, + blows_struck: 0, + blows_taken: 0, + drinks: 0, + throws: 0, + log: Vec::new(), + }; + let mut seen = 0; + let mut thrown = Vec::new(); + while fight.lines < MAX_LINES { + if let Some(end) = ended(arena, &state) { + fight.end = end; + break; + } + let view = View { + seed, + hp: state.hp.unwrap_or_default(), + max_hp, + foes: &state.foes, + carrying: &state.carrying, + thrown: &thrown, + }; + let act = matchup.policy.choose(arena, &view); + let typed = act.line(); + play(&mut engine, matchup.driver, game, &typed, seed, fight.lines)?; + state = engine.read(game, Vec::new()).map_err(failed)?.state; + fight.lines += 1; + match act { + Act::Drink(_) => fight.drinks += 1, + Act::Throw(thing, _) => { + fight.throws += 1; + thrown.push(thing); + } + _ => {} + } + let blows = arena.blows(&engine, game, &mut seen)?; + for blow in &blows { + if blow.by_player { + fight.blows_struck += 1; + fight.damage_dealt += blow.damage; + } + if blow.on_player { + fight.blows_taken += 1; + fight.damage_taken += blow.damage; + } + } + if keep_log { + fight.log.push(Line { + typed, + blows, + hp: state.hp.unwrap_or_default(), + foes: arena.foes_hp(&engine, game)?, + }); + } + } + if fight.lines == MAX_LINES { + fight.end = ended(arena, &state).unwrap_or(End::Stalled); + } + fight.hp_left = state.hp.unwrap_or_default(); + Ok(fight) +} + +/// How the fight stands after a line, or none while it goes on. +fn ended(arena: &Arena, state: &State) -> Option { + if state.dead || state.hp == Some(0) { + Some(End::Died) + } else if state.location.as_ref().map(|room| room.id) != Some(arena.room) { + Some(End::Fled) + } else if state.foes.is_empty() { + Some(End::Won) + } else { + None + } +} + +/// Plays one typed line through the driver's turn loop. A refused line is +/// an error: it buys no riposte, so a policy that types one would stall. +fn play( + engine: &mut Engine, + driver: Driver, + game: i64, + line: &str, + seed: i64, + index: usize, +) -> Result<(), String> { + let failed = |error: Error| format!("seed {seed}: {line:?}: {error}"); + match driver { + Driver::Mechanics => { + let outcome = engine.play(game, line, &mut |_| {}).map_err(failed)?; + if let Some(refusal) = outcome.report.refusal { + return Err(format!("seed {seed}: {line:?} was refused: {refusal}")); + } + } + Driver::Told => { + let mut models = Replay::new(Vec::new()); + let token = format!("fight-{seed}-{index}"); + let submitted = engine + .submit(game, &format!("/{line}"), &token, &mut models, &mut |_| {}) + .map_err(failed)?; + if !models.calls().is_empty() { + return Err(format!( + "seed {seed}: {line:?} asked a model: {:?}", + models.calls() + )); + } + if let Some(refusal) = submitted.turned.refusal { + return Err(format!( + "seed {seed}: {line:?} was refused: {}", + refusal.fact + )); + } + } + } + Ok(()) +} + +/// Plays every seed, on `threads` threads, and returns the fights in seed +/// order: the same seeds give the same fights however many threads play +/// them. +pub fn run(matchup: &Matchup, seeds: &[i64], threads: usize) -> Result, String> { + let arena = Arena::build(matchup)?; + let threads = threads.clamp(1, seeds.len().max(1)); + let chunk = seeds.len().div_ceil(threads).max(1); + let played: Vec, String>> = std::thread::scope(|scope| { + let handles: Vec<_> = seeds + .chunks(chunk) + .map(|chunk| { + let arena = &arena; + scope.spawn(move || { + chunk + .iter() + .map(|&seed| fight(arena, matchup, seed, false)) + .collect::, _>>() + }) + }) + .collect(); + handles + .into_iter() + .map(|handle| { + handle + .join() + .unwrap_or_else(|_| Err("a fight thread panicked".into())) + }) + .collect() + }); + let mut fights = Vec::with_capacity(seeds.len()); + for chunk in played { + fights.extend(chunk?); + } + Ok(fights) +} + +/// Plays one seed line by line, for `--replay`. +pub fn replay(matchup: &Matchup, seed: i64) -> Result { + let arena = Arena::build(matchup)?; + fight(&arena, matchup, seed, true) +} diff --git a/src/sim/policy.rs b/src/sim/policy.rs new file mode 100644 index 0000000..0381ff4 --- /dev/null +++ b/src/sim/policy.rs @@ -0,0 +1,226 @@ +//! How the simulated player plays: from what they can see (their hit +//! points, the foes still fighting, what they carry) to one typed line. +//! A policy is a player's habit, never a rule: whatever it types, the turn +//! loop decides what happens. + +use super::arena::Arena; +use crate::outcome::Named; +use yaml_rust2::Yaml; + +/// A hit-point mark: a number, or a share of the player's most. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Mark { + Hp(i64), + Share(f64), +} + +impl Mark { + fn reached(self, hp: i64, max_hp: i64) -> bool { + match self { + Mark::Hp(mark) => hp <= mark, + Mark::Share(share) => (hp as f64) <= share * max_hp as f64, + } + } +} + +/// A way of playing. `attack` is the default: swing at the first foe +/// standing, every line, to the end. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Policy { + pub kind: String, + /// Leave once hit points are at or below this. + pub flee_below: Option, + /// Drink a healing thing, while one is carried, once hit points are at + /// or below this. + pub drink_below: Option, + /// Try once to throw each throwable thing carried before swinging. + pub throw_first: bool, + /// Leave once one more round could kill: hit points at or below the sum + /// of the hit dice of the foes still fighting. + pub careful: bool, +} + +impl Policy { + /// A policy by name, before its options. + pub fn named(kind: &str) -> Result { + let base = Policy { + kind: kind.to_string(), + ..Policy::default() + }; + Ok(match kind { + "attack" | "flee_below" | "drink_below" => base, + "throw_first" => Policy { + throw_first: true, + ..base + }, + // The dungeon studies' naive player, at the scale of one fight. + "naive" => Policy { + drink_below: Some(Mark::Share(0.3)), + ..base + }, + // The dungeon studies' careful player, at the scale of one fight. + "careful" => Policy { + careful: true, + drink_below: Some(Mark::Share(0.5)), + ..base + }, + _ => { + return Err(format!( + "policy {kind:?} is attack, flee_below, drink_below, throw_first, naive or careful" + )) + } + }) + } + + /// `{kind: flee_below, hp: 6, drink_below: 9}`; `hp` is the mark of the + /// policy its kind names. + pub fn read(yaml: &Yaml) -> Result { + if let Some(kind) = yaml.as_str() { + return Policy::named(kind); + } + let kind = yaml["kind"].as_str().unwrap_or("attack"); + let mut policy = Policy::named(kind)?; + let hp = yaml["hp"].as_i64(); + let mark = |key: &str| -> Result, String> { + match &yaml[key] { + Yaml::Integer(hp) => Ok(Some(Mark::Hp(*hp))), + Yaml::Real(share) => share + .parse() + .map(|share| Some(Mark::Share(share))) + .map_err(|_| format!("policy.{key} is not a number")), + Yaml::BadValue => Ok(None), + _ => Err(format!("policy.{key} is not a number")), + } + }; + match kind { + "flee_below" => { + policy.flee_below = Some(hp.ok_or("policy flee_below needs hp")?); + } + "drink_below" => { + policy.drink_below = Some(Mark::Hp(hp.ok_or("policy drink_below needs hp")?)); + } + _ => {} + } + if let Some(Mark::Hp(hp)) = mark("flee_below")? { + policy.flee_below = Some(hp); + } + if let Some(drink) = mark("drink_below")? { + policy.drink_below = Some(drink); + } + if let Some(throw) = yaml["throw_first"].as_bool() { + policy.throw_first = throw; + } + Ok(policy) + } + + /// The next line. + pub fn choose(&self, arena: &Arena, view: &View) -> Act { + let Some(foe) = view.foes.first() else { + return Act::Wait; + }; + if let Some(drink) = self.drink_below { + if drink.reached(view.hp, view.max_hp) { + if let Some(thing) = view.carrying.iter().find(|thing| arena.heals(&thing.name)) { + return Act::Drink(thing.name.clone()); + } + } + } + let flee = self.flee_below.is_some_and(|mark| view.hp <= mark); + let risky = self.careful && { + let threat: i64 = view + .foes + .iter() + .map(|foe| arena.hit_die_of(&foe.name, view.seed)) + .sum(); + view.hp <= threat + }; + if flee || risky { + return Act::Leave(arena.exit_name.clone()); + } + if self.throw_first { + if let Some(thing) = view + .carrying + .iter() + .find(|thing| arena.throws(&thing.name) && !view.thrown.contains(&thing.name)) + { + return Act::Throw(thing.name.clone(), foe.name.clone()); + } + } + Act::Attack(foe.name.clone()) + } +} + +/// What the player sees before a line. +#[derive(Clone, Copy, Debug)] +pub struct View<'a> { + pub seed: i64, + pub hp: i64, + pub max_hp: i64, + /// The foes still fighting here, sorted by name. + pub foes: &'a [Named], + pub carrying: &'a [Named], + /// What the player has already tried to throw: a failed lift leaves the + /// thing in hand, and it is not tried again. + pub thrown: &'a [String], +} + +/// One line, before it is typed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Act { + Attack(String), + Leave(String), + Drink(String), + Throw(String, String), + Wait, +} + +impl Act { + /// The line as the grammar reads it. + pub fn line(&self) -> String { + match self { + Act::Attack(foe) => format!("attack {foe}"), + Act::Leave(room) => format!("go to the {room}"), + Act::Drink(thing) => format!("drink {thing}"), + Act::Throw(thing, foe) => format!("throw {thing} at {foe}"), + Act::Wait => "wait".into(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use yaml_rust2::YamlLoader; + + fn read(source: &str) -> Policy { + Policy::read(&YamlLoader::load_from_str(source).unwrap()[0]).unwrap() + } + + #[test] + fn reads_each_kind() { + assert_eq!(read("attack"), Policy::named("attack").unwrap()); + assert_eq!(read("{kind: flee_below, hp: 6}").flee_below, Some(6)); + assert_eq!( + read("{kind: flee_below, hp: 6, drink_below: 9}").drink_below, + Some(Mark::Hp(9)) + ); + assert_eq!( + read("{kind: drink_below, hp: 4}").drink_below, + Some(Mark::Hp(4)) + ); + assert!(read("throw_first").throw_first); + assert_eq!(read("naive").drink_below, Some(Mark::Share(0.3))); + let careful = read("careful"); + assert!(careful.careful); + assert_eq!(careful.drink_below, Some(Mark::Share(0.5))); + assert!(Policy::read(&YamlLoader::load_from_str("bold").unwrap()[0]).is_err()); + } + + #[test] + fn marks() { + assert!(Mark::Hp(6).reached(6, 18)); + assert!(!Mark::Hp(6).reached(7, 18)); + assert!(Mark::Share(0.5).reached(9, 18)); + assert!(!Mark::Share(0.5).reached(10, 18)); + } +} diff --git a/src/sim/tally.rs b/src/sim/tally.rs new file mode 100644 index 0000000..3cf3f95 --- /dev/null +++ b/src/sim/tally.rs @@ -0,0 +1,278 @@ +//! What many fights of one matchup did, counted: how often the player won, +//! died, got away or was still fighting, with a 95% interval on each; how +//! many rounds a fight took and how many hit points the survivors kept; and +//! the damage and blows on each side. + +use super::{End, Fight, Line}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::fmt::Write; + +/// Fights of one matchup, counted. +#[derive(Clone, Debug, PartialEq)] +pub struct Summary { + pub fights: usize, + /// How many fights ended each way, in [`End::ALL`] order. + pub ends: Vec<(End, usize)>, + /// Rounds a fight took, and how many fights took that many. + pub rounds: BTreeMap, + /// Hit points the player kept, over the fights they survived. + pub hp_left: BTreeMap, + pub mean_rounds: f64, + pub mean_hp_left: Option, + pub mean_damage_taken: f64, + pub mean_damage_dealt: f64, + pub mean_blows_taken: f64, + pub mean_blows_struck: f64, + pub mean_drinks: f64, + pub mean_throws: f64, +} + +impl Summary { + pub fn of(fights: &[Fight]) -> Summary { + let n = fights.len(); + let mean = |f: &dyn Fn(&Fight) -> f64| { + if n == 0 { + 0.0 + } else { + fights.iter().map(f).sum::() / n as f64 + } + }; + let mut rounds = BTreeMap::new(); + let mut hp_left = BTreeMap::new(); + for fight in fights { + *rounds.entry(fight.lines).or_insert(0) += 1; + if fight.end != End::Died { + *hp_left.entry(fight.hp_left).or_insert(0) += 1; + } + } + let survivors: usize = hp_left.values().sum(); + Summary { + fights: n, + ends: End::ALL + .iter() + .map(|end| (*end, fights.iter().filter(|f| f.end == *end).count())) + .collect(), + mean_rounds: mean(&|f| f.lines as f64), + mean_hp_left: (survivors > 0).then(|| { + hp_left + .iter() + .map(|(hp, k)| (*hp * *k as i64) as f64) + .sum::() + / survivors as f64 + }), + rounds, + hp_left, + mean_damage_taken: mean(&|f| f.damage_taken as f64), + mean_damage_dealt: mean(&|f| f.damage_dealt as f64), + mean_blows_taken: mean(&|f| f.blows_taken as f64), + mean_blows_struck: mean(&|f| f.blows_struck as f64), + mean_drinks: mean(&|f| f.drinks as f64), + mean_throws: mean(&|f| f.throws as f64), + } + } + + /// How many fights ended this way. + pub fn count(&self, end: End) -> usize { + self.ends + .iter() + .find(|(e, _)| *e == end) + .map_or(0, |(_, k)| *k) + } + + /// The share of fights that ended this way. + pub fn rate(&self, end: End) -> f64 { + if self.fights == 0 { + 0.0 + } else { + self.count(end) as f64 / self.fights as f64 + } + } + + /// The table a terminal prints. + pub fn text(&self, heading: &str) -> String { + let mut out = String::new(); + let _ = writeln!(out, "{heading}"); + let _ = writeln!(out, " {:<9}{:>7} 95% interval", "", "rate"); + for (end, count) in &self.ends { + if *end == End::Stalled && *count == 0 { + continue; + } + let (low, high) = wilson(*count, self.fights); + let _ = writeln!( + out, + " {:<9}{:>7.3} [{low:.3}, {high:.3}]", + end.as_str(), + self.rate(*end) + ); + } + let _ = writeln!( + out, + " rounds mean {:.2} {}", + self.mean_rounds, + histogram(&self.rounds) + ); + match self.mean_hp_left { + Some(mean) => { + let _ = writeln!( + out, + " hp left mean {mean:.2} {} (survivors)", + histogram(&self.hp_left) + ); + } + None => { + let _ = writeln!(out, " hp left (nobody survived)"); + } + } + let _ = writeln!( + out, + " damage taken {:.2}, dealt {:.2} a fight", + self.mean_damage_taken, self.mean_damage_dealt + ); + let _ = writeln!( + out, + " blows taken {:.2}, struck {:.2} a fight", + self.mean_blows_taken, self.mean_blows_struck + ); + if self.mean_drinks > 0.0 || self.mean_throws > 0.0 { + let _ = writeln!( + out, + " used drinks {:.2}, throws {:.2} a fight", + self.mean_drinks, self.mean_throws + ); + } + out + } + + /// The same, as JSON. + pub fn json(&self) -> Value { + let ends: serde_json::Map = self + .ends + .iter() + .map(|(end, count)| { + let (low, high) = wilson(*count, self.fights); + ( + end.as_str().to_string(), + json!({"count": count, "rate": self.rate(*end), "low": low, "high": high}), + ) + }) + .collect(); + json!({ + "fights": self.fights, + "ends": ends, + "rounds": {"mean": self.mean_rounds, "histogram": keyed(&self.rounds)}, + "hp_left": {"mean": self.mean_hp_left, "histogram": keyed(&self.hp_left)}, + "damage": {"taken": self.mean_damage_taken, "dealt": self.mean_damage_dealt}, + "blows": {"taken": self.mean_blows_taken, "struck": self.mean_blows_struck}, + "used": {"drinks": self.mean_drinks, "throws": self.mean_throws}, + }) + } +} + +/// The Wilson score interval at 95% for `k` of `n`. +pub fn wilson(k: usize, n: usize) -> (f64, f64) { + if n == 0 { + return (0.0, 1.0); + } + let z = 1.96_f64; + let n = n as f64; + let p = k as f64 / n; + let centre = p + z * z / (2.0 * n); + let spread = z * (p * (1.0 - p) / n + z * z / (4.0 * n * n)).sqrt(); + let denominator = 1.0 + z * z / n; + ( + ((centre - spread) / denominator).max(0.0), + ((centre + spread) / denominator).min(1.0), + ) +} + +/// `1:12 2:40 3:7`. +fn histogram(counts: &BTreeMap) -> String { + counts + .iter() + .map(|(key, count)| format!("{key}:{count}")) + .collect::>() + .join(" ") +} + +/// A histogram as a JSON object, keyed by its numbers as text. +fn keyed(counts: &BTreeMap) -> Value { + Value::Object( + counts + .iter() + .map(|(key, count)| (key.to_string(), Value::from(*count))) + .collect(), + ) +} + +/// One fight, line by line, for `--replay`. +pub fn replay(fight: &Fight) -> String { + let mut out = String::new(); + let _ = writeln!( + out, + "seed {}: {} after {} line(s), {} of {} hp left", + fight.seed, + fight.end.as_str(), + fight.lines, + fight.hp_left, + fight.max_hp + ); + for (n, line) in fight.log.iter().enumerate() { + let Line { + typed, + blows, + hp, + foes, + } = line; + let _ = writeln!(out, "{:>3}. > {typed}", n + 1); + for blow in blows { + let _ = writeln!( + out, + " {} strikes {} for {} ({} left)", + blow.attacker, blow.target, blow.damage, blow.hp_after + ); + } + let foes: Vec = foes + .iter() + .map(|(name, hp)| format!("{name} {hp}")) + .collect(); + let _ = writeln!(out, " you {hp}; {}", foes.join(", ")); + } + out +} + +/// One fight, line by line, as JSON. +pub fn replay_json(fight: &Fight) -> Value { + json!({ + "seed": fight.seed, + "end": fight.end.as_str(), + "lines": fight.lines, + "max_hp": fight.max_hp, + "hp_left": fight.hp_left, + "damage": {"taken": fight.damage_taken, "dealt": fight.damage_dealt}, + "log": fight.log.iter().map(|line| json!({ + "typed": line.typed, + "blows": line.blows.iter().map(|blow| json!({ + "attacker": blow.attacker, + "target": blow.target, + "damage": blow.damage, + "hp_after": blow.hp_after, + })).collect::>(), + "hp": line.hp, + "foes": line.foes.iter().map(|(name, hp)| json!({"name": name, "hp": hp})).collect::>(), + })).collect::>(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wilson_interval() { + let (low, high) = wilson(460, 2000); + assert!((low - 0.2122).abs() < 0.001, "{low}"); + assert!((high - 0.2491).abs() < 0.001, "{high}"); + assert_eq!(wilson(0, 0), (0.0, 1.0)); + } +} diff --git a/tests/sim.rs b/tests/sim.rs new file mode 100644 index 0000000..35c1c79 --- /dev/null +++ b/tests/sim.rs @@ -0,0 +1,186 @@ +//! The fight simulator (`sim`) against what it must not get wrong: the +//! rules' exact odds, the two turn loops' agreement on a fight with no move +//! in it, the same seed playing the same fight, and its tally agreeing with +//! the blows the game wrote down. + +use renderedstep_engine::sim::matchup::{Foes, Matchup, Stat, Stats}; +use renderedstep_engine::sim::policy::Policy; +use renderedstep_engine::sim::{self, tally::Summary, Driver, End, Fight}; + +fn foes(count: usize, level: i64, hit_die: i64) -> Foes { + Foes { + count, + name: "Foe".into(), + stats: Stats { + level: Stat::Fixed(level), + hit_die: Stat::Fixed(hit_die), + ..Stats::foe() + }, + columns: Vec::new(), + } +} + +fn matchup(driver: Driver, count: usize, level: i64, hit_die: i64) -> Matchup { + Matchup { + driver, + ..Matchup::new("test", vec![foes(count, level, hit_die)]) + } +} + +fn threads() -> usize { + std::thread::available_parallelism().map_or(2, |n| n.get()) +} + +/// The exact chance the house body (18 hit points, d8) wins attacking to +/// the end, worked out from the rules as stated rather than played: the +/// player's blow always lands for one die at the first foe standing, then +/// every foe standing strikes once for one of its own. These are the +/// figures of the fight simulator's scope, Appendix B. A broken arena or a +/// seed that does not move the dice fails here, even if a later golden is +/// written again over it. +#[test] +fn plays_the_rules_exact_odds() { + const FIGHTS: i64 = 600; + for (count, level, hit_die, exact) in [(1, 1, 8, 0.9854), (1, 3, 10, 0.2338), (3, 1, 6, 0.1914)] + { + let matchup = matchup(Driver::Mechanics, count, level, hit_die); + let seeds: Vec = (1..=FIGHTS).collect(); + let fights = sim::run(&matchup, &seeds, threads()).unwrap(); + let won = Summary::of(&fights).rate(End::Won); + let error = (exact * (1.0 - exact) / FIGHTS as f64).sqrt(); + assert!( + (won - exact).abs() <= 4.0 * error, + "{count} x L{level} d{hit_die}: won {won:.4}, the rules say {exact:.4} (4 sd = {:.4})", + 4.0 * error + ); + } +} + +/// With no move and no clock in it, a fight is the same fight seed for seed +/// on either loop: a rule added to one loop and not the other fails here. +/// (A move is not: the told loop writes its arrival before the riposte, so +/// the parting blow is thrown at a later story time and from other dice.) +#[test] +fn the_two_loops_play_the_same_fight() { + for (count, level, hit_die) in [(1, 3, 10), (3, 1, 6)] { + let told = matchup(Driver::Told, count, level, hit_die); + let mechanics = matchup(Driver::Mechanics, count, level, hit_die); + let told_arena = sim::arena::Arena::build(&told).unwrap(); + let mechanics_arena = sim::arena::Arena::build(&mechanics).unwrap(); + for seed in 1..=40 { + let a = sim::fight(&told_arena, &told, seed, true).unwrap(); + let b = sim::fight(&mechanics_arena, &mechanics, seed, true).unwrap(); + assert_eq!(a, b, "{count} x L{level} d{hit_die}, seed {seed}"); + } + } +} + +/// The same seed plays the same fight, alone or among others, on one +/// thread or several. +#[test] +fn a_seed_plays_the_same_fight_again() { + let mut matchup = matchup(Driver::Told, 2, 1, 8); + matchup.carrying = vec![vec![ + ("name".into(), "healing draught".into()), + ("use_kind".into(), "healing".into()), + ]]; + matchup.policy = Policy::named("careful").unwrap(); + let first = sim::replay(&matchup, 17).unwrap(); + let again = sim::replay(&matchup, 17).unwrap(); + assert_eq!(first, again); + assert!(!first.log.is_empty()); + + let seeds: Vec = (1..=24).collect(); + let alone = sim::run(&matchup, &seeds, 1).unwrap(); + let shared = sim::run(&matchup, &seeds, 4).unwrap(); + assert_eq!(alone, shared); + let unlogged = Fight { + log: Vec::new(), + ..first + }; + assert_eq!(alone[16], unlogged); + assert_ne!(alone[0], alone[1], "two seeds threw the same dice"); +} + +/// A fight's tally is what its blows say: the damage on each side, the hit +/// points left, a blow struck by the player each round, and every foe of a +/// won fight at zero. +#[test] +fn the_tally_is_what_the_blows_say() { + let matchup = matchup(Driver::Told, 3, 1, 6); + let mut checked = [false; 2]; + for seed in 1..=30 { + let fight = sim::replay(&matchup, seed).unwrap(); + let blows: Vec<_> = fight.log.iter().flat_map(|line| &line.blows).collect(); + let struck: Vec<_> = blows.iter().filter(|blow| blow.by_player).collect(); + let taken: Vec<_> = blows.iter().filter(|blow| blow.on_player).collect(); + assert_eq!(fight.blows_struck, struck.len()); + assert_eq!(fight.blows_taken, taken.len()); + assert_eq!( + fight.damage_dealt, + struck.iter().map(|b| b.damage).sum::() + ); + assert_eq!( + fight.damage_taken, + taken.iter().map(|b| b.damage).sum::() + ); + assert_eq!( + fight.blows_struck, fight.lines, + "seed {seed}: one swing a round" + ); + let last_taken = taken.last().map_or(fight.max_hp, |blow| blow.hp_after); + assert_eq!(fight.hp_left, last_taken, "seed {seed}"); + assert_eq!( + fight.hp_left, + (fight.max_hp - fight.damage_taken).max(0), + "seed {seed}" + ); + let last = fight.log.last().unwrap(); + assert_eq!(last.hp, fight.hp_left); + match fight.end { + End::Won => { + assert!(last.foes.iter().all(|(_, hp)| *hp == 0), "seed {seed}"); + checked[0] = true; + } + End::Died => { + assert_eq!(fight.hp_left, 0); + assert!(last.foes.iter().any(|(_, hp)| *hp > 0), "seed {seed}"); + checked[1] = true; + } + end => panic!("seed {seed}: {end:?} in a fight with no way out taken"), + } + } + assert_eq!(checked, [true, true], "both a win and a death were checked"); +} + +/// Every way of playing types only lines the turn loop plays: none is +/// refused, none asks a model, and each ends its fights. +#[test] +fn every_policy_plays_to_an_end() { + for kind in ["attack", "throw_first", "naive", "careful"] { + for driver in [Driver::Told, Driver::Mechanics] { + let mut matchup = matchup(driver, 2, 2, 8); + matchup.carrying = vec![ + vec![ + ("name".into(), "healing draught".into()), + ("use_kind".into(), "healing".into()), + ], + vec![ + ("name".into(), "brick".into()), + ("bulk".into(), "handy".into()), + ], + ]; + matchup.policy = Policy::named(kind).unwrap(); + matchup.policy.flee_below = Some(4); + let seeds: Vec = (1..=12).collect(); + let fights = sim::run(&matchup, &seeds, threads()).unwrap(); + assert!( + fights.iter().all(|fight| fight.end != End::Stalled), + "{kind} on {driver:?}" + ); + if kind == "throw_first" { + assert!(fights.iter().all(|fight| fight.throws == 1), "{kind}"); + } + } + } +}