/airdef command tree with typed arguments, live scenario names and generated help (#98, fork patch 36)
build / mod (push) Successful in 3m52s
build / mod (push) Successful in 3m52s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,275 @@
|
||||
//! The `/airdef` command tree: the one description the game's chat box (colours, errors,
|
||||
//! Tab completion), the help line and the tests read (#98). The handler in `lib.rs` still
|
||||
//! splits its line itself; this tree decides what reaches it.
|
||||
use crate::sim::{DroneKind, SamKind};
|
||||
use horizon_mod_sdk::tree::{Node, Opt, Tree, Value};
|
||||
|
||||
/// The suggestion list of the saved scenarios' names (`command::set_suggestions`).
|
||||
pub const SCENARIOS: &str = "scenarios";
|
||||
|
||||
fn on_off() -> Value {
|
||||
Value::choice(["on", "off"])
|
||||
}
|
||||
|
||||
/// `/airdef ...` as `lib.rs` accepts it.
|
||||
pub fn tree() -> Tree {
|
||||
let wave_kinds: Vec<&str> = DroneKind::ALL.iter().map(|k| k.spec().key).chain(["mix"]).collect();
|
||||
let deploy_kinds: Vec<&str> = SamKind::ALL.iter().map(|k| k.key()).collect();
|
||||
let armed: Vec<&str> = SamKind::ARMED.iter().map(|k| k.key()).chain(["all"]).collect();
|
||||
let toggle = |word: &str| Node::lit(word).then(Node::arg("on/off", on_off()).runs());
|
||||
Tree::new("airdef").runs().with([
|
||||
Node::lit("menu").runs(),
|
||||
Node::lit("monitor").runs(),
|
||||
Node::lit("grid").runs(),
|
||||
Node::lit("replay").runs().with([
|
||||
Node::lit("map").runs(),
|
||||
Node::lit("full").runs(),
|
||||
Node::lit("reel").runs(),
|
||||
Node::lit("film").runs().with([
|
||||
Node::arg("режим", Value::choice(["best", "all"])).runs(),
|
||||
Node::arg("N", Value::int_from(1)).runs(),
|
||||
]),
|
||||
// The words after `export` come in any order: a name, best/all/N, key=value options.
|
||||
Node::lit("export").runs().then(
|
||||
Node::options(
|
||||
"параметры",
|
||||
vec![
|
||||
Opt::new("fps", Value::int_from(1)),
|
||||
Opt::new("size", Value::word()),
|
||||
Opt::new("crf", Value::int_from(0)),
|
||||
Opt::new("sec", Value::Number(Some(0.0), None)),
|
||||
Opt::flag("noaudio"),
|
||||
],
|
||||
Some(vec!["best".into(), "all".into()]),
|
||||
)
|
||||
.runs(),
|
||||
),
|
||||
Node::lit("stop").runs(),
|
||||
]),
|
||||
Node::lit("scenario").with([
|
||||
Node::lit("save").then(
|
||||
Node::arg("имя", Value::word()).runs().then(Node::arg("fresh", Value::choice(["fresh"])).runs()),
|
||||
),
|
||||
Node::lit("load").then(
|
||||
Node::arg("имя", Value::names(SCENARIOS)).runs().then(Node::arg("force", Value::choice(["force"])).runs()),
|
||||
),
|
||||
Node::lit("list").runs(),
|
||||
Node::lit("delete").then(Node::arg("имя", Value::names(SCENARIOS)).runs()),
|
||||
]),
|
||||
Node::lit("why").runs().then(Node::arg("номер", Value::int_from(1)).runs()),
|
||||
Node::lit("raid").runs(),
|
||||
Node::lit("repair").runs(),
|
||||
Node::lit("import").runs(),
|
||||
toggle("ew"),
|
||||
Node::lit("flare").runs(),
|
||||
Node::lit("move").then(Node::arg("номер", Value::int_from(1)).runs()),
|
||||
Node::lit("target").then(Node::lit("here").runs()),
|
||||
Node::lit("give").runs(),
|
||||
Node::lit("deploy").then(Node::arg("комплекс", Value::choice(deploy_kinds)).runs()),
|
||||
Node::lit("wave").then(
|
||||
Node::arg("тип", Value::choice(wave_kinds)).runs().then(
|
||||
Node::arg("кол-во", Value::int(1, 80)).runs().then(Node::arg("дальность", Value::number(60.0, 800.0)).runs()),
|
||||
),
|
||||
),
|
||||
Node::lit("clear").runs(),
|
||||
Node::lit("targets").then(Node::lit("clear").runs()),
|
||||
toggle("damage"),
|
||||
toggle("truth"),
|
||||
Node::lit("shader").then(Node::arg("режим", Value::choice(["on", "off", "hd"])).runs()),
|
||||
toggle("hold"),
|
||||
Node::lit("roles").runs().then(
|
||||
Node::arg("комплекс", Value::choice(armed)).then(
|
||||
Node::arg(
|
||||
"классы",
|
||||
Value::Word(["default", "all", "drone", "jet", "cruise", "supersonic", "ballistic"].map(String::from).to_vec()),
|
||||
)
|
||||
.runs(),
|
||||
),
|
||||
),
|
||||
Node::lit("stats").runs(),
|
||||
])
|
||||
}
|
||||
|
||||
/// The help line, from the same tree.
|
||||
pub fn help() -> String {
|
||||
tree().usage()
|
||||
}
|
||||
|
||||
/// The scenario names after `name` is saved (once, in the order saved).
|
||||
pub fn names_after_save(mut all: Vec<String>, name: &str) -> Vec<String> {
|
||||
if !all.iter().any(|n| n == name) {
|
||||
all.push(name.to_string());
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
/// The scenario names after `name` is deleted.
|
||||
pub fn names_after_delete(mut all: Vec<String>, name: &str) -> Vec<String> {
|
||||
all.retain(|n| n != name);
|
||||
all
|
||||
}
|
||||
|
||||
/// Registers the tree with the game, and the scenario names it suggests.
|
||||
pub fn register(scenarios: &[String]) {
|
||||
horizon_mod_sdk::command::set_suggestions(SCENARIOS, scenarios);
|
||||
if let Err(e) = tree().register() {
|
||||
horizon_mod_sdk::warn(&format!("airdef: command tree refused: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ok(line: &str) {
|
||||
if let Err(e) = tree().parse(line) {
|
||||
panic!("`{line}` should parse: {e}");
|
||||
}
|
||||
}
|
||||
fn bad_at(line: &str) -> usize {
|
||||
match tree().parse(line) {
|
||||
Ok(_) => panic!("`{line}` should not parse"),
|
||||
Err(e) => e.at,
|
||||
}
|
||||
}
|
||||
fn complete(line: &str, scenarios: &[&str]) -> Vec<String> {
|
||||
let names: Vec<String> = scenarios.iter().map(|s| s.to_string()).collect();
|
||||
tree().complete(line, &|_| names.clone())
|
||||
}
|
||||
|
||||
/// Every branch of the old `HELP` line and of the handler's match parses, with its
|
||||
/// options.
|
||||
#[test]
|
||||
fn every_branch_of_the_handler_parses() {
|
||||
for line in [
|
||||
"", "menu", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "roles",
|
||||
"replay", "replay map", "replay full", "replay reel", "replay film", "replay film best", "replay film all",
|
||||
"replay film 3", "replay export", "replay export mine", "replay export best", "replay export all", "replay export 3",
|
||||
"replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop",
|
||||
"scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list",
|
||||
"scenario delete a", "why", "why 2", "ew on", "ew off", "move 4", "target here", "targets clear",
|
||||
"deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800",
|
||||
"wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on",
|
||||
"roles all default", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic",
|
||||
] {
|
||||
ok(line);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_trees_kinds_are_the_enums_own() {
|
||||
for k in SamKind::ALL {
|
||||
ok(&format!("deploy {}", k.key()));
|
||||
}
|
||||
for k in DroneKind::ALL {
|
||||
ok(&format!("wave {}", k.spec().key));
|
||||
}
|
||||
for k in SamKind::ARMED {
|
||||
ok(&format!("roles {} all", k.key()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_and_words_outside_what_the_handler_takes_are_refused_where_they_are() {
|
||||
assert_eq!(bad_at("wave shahed 0"), 12);
|
||||
assert_eq!(bad_at("wave shahed 81"), 12);
|
||||
assert_eq!(bad_at("wave shahed 5 59"), 14);
|
||||
assert_eq!(bad_at("wave shahed 5 801"), 14);
|
||||
assert_eq!(bad_at("wave shahed x"), 12);
|
||||
assert_eq!(bad_at("wave scud"), 5);
|
||||
assert_eq!(bad_at("wave"), 4);
|
||||
assert_eq!(bad_at("deploy tank"), 7);
|
||||
assert_eq!(bad_at("deploy"), 6);
|
||||
assert_eq!(bad_at("ew maybe"), 3);
|
||||
assert_eq!(bad_at("shader ultra"), 7);
|
||||
assert_eq!(bad_at("why 0"), 4);
|
||||
assert_eq!(bad_at("why x"), 4);
|
||||
assert_eq!(bad_at("move"), 4);
|
||||
assert_eq!(bad_at("move 0"), 5);
|
||||
assert_eq!(bad_at("scenario"), 8);
|
||||
assert_eq!(bad_at("scenario load"), 13);
|
||||
assert_eq!(bad_at("scenario wipe"), 9);
|
||||
assert_eq!(bad_at("scenario save a keep"), 16);
|
||||
assert_eq!(bad_at("target there"), 7);
|
||||
assert_eq!(bad_at("roles tank all"), 6);
|
||||
assert_eq!(bad_at("roles patriot"), 13);
|
||||
assert_eq!(bad_at("replay sideways"), 7);
|
||||
assert_eq!(bad_at("replay film best now"), 17);
|
||||
assert_eq!(bad_at("nothing"), 0);
|
||||
assert_eq!(bad_at("menu 1"), 5);
|
||||
}
|
||||
|
||||
/// The key=value options of `replay export` stay what `start_export` reads.
|
||||
#[test]
|
||||
fn export_options_are_checked_by_key_and_value() {
|
||||
assert_eq!(bad_at("replay export fps=0"), 14);
|
||||
assert_eq!(bad_at("replay export fps=x"), 14);
|
||||
assert_eq!(bad_at("replay export fps"), 14);
|
||||
assert_eq!(bad_at("replay export noaudio=1"), 14);
|
||||
assert_eq!(bad_at("replay export fps=30 fps=60"), 21);
|
||||
assert_eq!(bad_at("replay export sec=-1"), 14);
|
||||
assert_eq!(bad_at("replay export crf=-2"), 14);
|
||||
assert_eq!(bad_at("replay export size="), 14);
|
||||
let p = tree().parse("replay export mine fps=30 noaudio").unwrap();
|
||||
assert_eq!(p.get("параметры"), Some("mine fps=30 noaudio"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_offers_the_next_word_only() {
|
||||
let top = complete("", &[]);
|
||||
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
|
||||
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "roles", "stats"] {
|
||||
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
|
||||
}
|
||||
assert_eq!(top.len(), 24);
|
||||
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
|
||||
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
|
||||
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
|
||||
assert_eq!(complete("scenario ", &[]), ["delete", "list", "load", "save"]);
|
||||
assert_eq!(complete("wave ", &[]).len(), 14);
|
||||
assert!(complete("wave s", &[]).contains(&"shahed".to_string()));
|
||||
assert_eq!(complete("shader ", &[]), ["hd", "off", "on"]);
|
||||
assert_eq!(complete("replay export ", &[]), ["all", "best", "crf=", "fps=", "noaudio", "sec=", "size="]);
|
||||
assert_eq!(complete("replay export fps=30 no", &[]), ["noaudio"]);
|
||||
assert!(complete("menu ", &[]).is_empty());
|
||||
assert!(complete("wave nothing ", &[]).is_empty());
|
||||
}
|
||||
|
||||
/// The names follow the data: after a save the new name is offered, after a delete it is gone.
|
||||
#[test]
|
||||
fn scenario_names_follow_a_save_and_a_delete() {
|
||||
let mut all: Vec<String> = Vec::new();
|
||||
let names = |all: &[String]| -> Vec<String> { tree().complete("scenario load ", &|_| all.to_vec()) };
|
||||
assert!(names(&all).is_empty());
|
||||
all = names_after_save(all, "base");
|
||||
all = names_after_save(all, "night");
|
||||
all = names_after_save(all, "base");
|
||||
assert_eq!(names(&all), ["base", "night"]);
|
||||
let of = |all: &[String], line: &str| tree().complete(line, &|_| all.to_vec());
|
||||
assert_eq!(of(&all, "scenario delete n"), ["night"]);
|
||||
all = names_after_delete(all, "base");
|
||||
assert_eq!(names(&all), ["night"]);
|
||||
assert_eq!(of(&all, "scenario delete "), ["night"]);
|
||||
all = names_after_delete(all, "night");
|
||||
assert!(names(&all).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_help_line_is_the_trees() {
|
||||
let help = help();
|
||||
assert!(help.starts_with("/airdef menu | monitor | grid | replay "), "{help}");
|
||||
assert!(help.contains("scenario save <имя> [fresh]"), "{help}");
|
||||
assert!(help.contains("wave <тип> [<кол-во> [<дальность>]]"), "{help}");
|
||||
assert!(help.ends_with("| stats"), "{help}");
|
||||
assert!(help.contains("export [fps=… size=… crf=… sec=… noaudio]"), "{help}");
|
||||
assert!(help.contains("deploy <комплекс>"), "{help}");
|
||||
}
|
||||
|
||||
/// The nodes handed to the game are a tree the game accepts.
|
||||
#[test]
|
||||
fn the_nodes_are_flat_and_ordered() {
|
||||
let nodes = tree().nodes();
|
||||
assert!(nodes.len() < 512, "{}", nodes.len());
|
||||
assert!(nodes.iter().enumerate().all(|(i, n)| n.children.iter().all(|&c| c as usize > i)));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use horizon_mod_sdk::{
|
||||
};
|
||||
|
||||
mod cinema;
|
||||
mod commands;
|
||||
mod layout;
|
||||
mod film;
|
||||
mod monitor;
|
||||
@@ -1368,7 +1369,10 @@ impl AirDef {
|
||||
}
|
||||
}
|
||||
|
||||
const HELP: &str = "/airdef menu | monitor | grid | replay [map|full|reel|film [best|all|N]|export [имя] [best|all|N] [fps=60 size=1920x1080 crf=14 sec=N noaudio]|stop] | scenario save|load|list|delete | why [номер] | raid | repair | import | ew on|off | flare | move <номер> | target here | give | deploy <комплекс> | wave <тип|mix> [кол-во] [дальность] | clear | targets clear | damage on|off | truth on|off | shader on|off|hd | hold on|off | roles [комплекс классы] | stats";
|
||||
/// The help line: generated from the command tree (`commands.rs`), which the game checks lines with.
|
||||
fn help() -> String {
|
||||
commands::help()
|
||||
}
|
||||
|
||||
impl Mod for AirDef {
|
||||
fn init() -> Result<(Self, Registration), String> {
|
||||
@@ -1422,6 +1426,8 @@ impl Mod for AirDef {
|
||||
me.block_log = Some(render::world_log_start());
|
||||
me.sim.shader = true;
|
||||
me.apply_far();
|
||||
// Subcommands, typed arguments and the saved scenarios' names for the chat box (#98).
|
||||
commands::register(&scenario::saved_names());
|
||||
Ok((me, Registration::new().command("airdef").on_tick()))
|
||||
}
|
||||
|
||||
@@ -1946,7 +1952,7 @@ impl Mod for AirDef {
|
||||
self.sim.crashes,
|
||||
self.ground.world.text()
|
||||
)),
|
||||
_ => return Err(HELP.to_string()),
|
||||
_ => return Err(help()),
|
||||
};
|
||||
self.emit(out);
|
||||
Ok(reply)
|
||||
|
||||
@@ -20,6 +20,16 @@ fn valid(name: &str) -> Result<String, String> {
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// The saved scenarios' names.
|
||||
pub(crate) fn saved_names() -> Vec<String> {
|
||||
names()
|
||||
}
|
||||
|
||||
/// Tells the chat box the names now saved, so Tab offers them.
|
||||
fn publish(all: &[String]) {
|
||||
command::set_suggestions(commands::SCENARIOS, all);
|
||||
}
|
||||
|
||||
fn names() -> Vec<String> {
|
||||
storage::get(INDEX).map(|b| String::from_utf8_lossy(&b).lines().map(str::to_string).filter(|l| !l.is_empty()).collect()).unwrap_or_default()
|
||||
}
|
||||
@@ -82,11 +92,12 @@ impl AirDef {
|
||||
let fresh = flags.contains(&"fresh");
|
||||
let text = self.scenario_text(&name, fresh);
|
||||
storage::set(&key(&name), text.as_bytes()).map_err(|e| format!("Не удалось сохранить: {e}"))?;
|
||||
let mut all = names();
|
||||
if !all.contains(&name) {
|
||||
all.push(name.clone());
|
||||
let before = names();
|
||||
let all = commands::names_after_save(before.clone(), &name);
|
||||
if all != before {
|
||||
storage::set(INDEX, all.join("\n").as_bytes()).map_err(|e| format!("Не удалось записать список: {e}"))?;
|
||||
}
|
||||
publish(&all);
|
||||
Ok(format!(
|
||||
"Сценарий «{name}» сохранён: комплексов {}, объектов {}{}",
|
||||
self.sim.sams.len(),
|
||||
@@ -109,13 +120,14 @@ impl AirDef {
|
||||
}
|
||||
["delete", name] => {
|
||||
let name = valid(name)?;
|
||||
let mut all = names();
|
||||
let all = names();
|
||||
if !all.contains(&name) {
|
||||
return Err(format!("Нет сценария «{name}»"));
|
||||
}
|
||||
all.retain(|n| *n != name);
|
||||
let all = commands::names_after_delete(all, &name);
|
||||
storage::delete(&key(&name));
|
||||
storage::set(INDEX, all.join("\n").as_bytes()).map_err(|e| format!("Не удалось записать список: {e}"))?;
|
||||
publish(&all);
|
||||
Ok(format!("Сценарий «{name}» удалён"))
|
||||
}
|
||||
_ => Err("/airdef scenario save <имя> [fresh] | load <имя> [force] | list | delete <имя>".into()),
|
||||
|
||||
Reference in New Issue
Block a user