Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
65 changes: 65 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions sim/matchups/careful-vs-naive.yml
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions sim/matchups/one-l3-d10.yml
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions sim/matchups/three-l1-d6.yml
Original file line number Diff line number Diff line change
@@ -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
11 changes: 11 additions & 0 deletions sim/matchups/two-l2-d10-flee.yml
Original file line number Diff line number Diff line change
@@ -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}
139 changes: 139 additions & 0 deletions src/bin/fight.rs
Original file line number Diff line number Diff line change
@@ -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<String>) -> 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::<i64>()
.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::<usize>()
.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(())
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading