Some work on the display

This commit is contained in:
Dandaedre 2025-12-02 16:45:34 +01:00
parent 5c737635a6
commit 7ec2622959
5 changed files with 357 additions and 234 deletions

View File

@ -78,11 +78,17 @@ fn main() -> miette::Result<()> {
env_logger::init();
let e = Entity::default();
println!("{e:#?}");
// println!("{e:#?}");
println!("{}", e.oneline_display());
e.print_short();
e.print_full();
println!("{}", e.to_pretty_tree());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
// e.print_short();
// e.print_full();
// println!("{}", e.to_pretty_tree());
let cli = Cli::parse();
if let Err(e) = exec_dispatch(cli) {

View File

@ -4,6 +4,7 @@ use colored::*; // [3] – colored‑rs examples
use crate::Displayable;
use crate::entity::Entity;
use crate::stats::Symbols;
// ---------- Implementation ----------
impl Displayable for Entity {
@ -13,7 +14,7 @@ impl Displayable for Entity {
"{:?}\n{}",
self.metadata.position, // Display
format!(
"{} | {} | {} | {:?} | {}",
"{:?} | {:?} | {} | {:?} | {}",
self.metadata.capital,
self.metadata.governor,
self.metadata.faction,
@ -37,19 +38,53 @@ impl Displayable for Entity {
print_stdout(vec![&self.stats].with_title().bold(true)).expect("")
}
// One‑liner used for auto‑generation of Vec<T> displays
/// One‑liner used for auto‑generation of Vec<T> displays
fn oneline_display(&self) -> String {
format!(
"> {} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?}",
let capital = self
.metadata
.capital
.as_ref()
.map(|c| format!(" | 💰 {}", c))
.unwrap_or_default();
let governor = self
.metadata
.governor
.as_ref()
.map(|g| format!(" | 👑 {}", g))
.unwrap_or_default();
let prestige = if self.metadata.prestige > 0 {
format!(" | 📈 {}", self.metadata.prestige)
} else {
String::new()
};
// ---- build the two lines ----
let line1 = format!(
"├─ {} {} ──────> {} {}",
self.name,
self.metadata.position,
self.duration,
self.effect_nature,
self.effect_bounds,
self.entity_type,
self.metadata.capital,
self.metadata.prestige
)
self.entity_type.to_symbol(),
self.metadata.position.to_symbol(),
self.duration.to_symbol()
);
let line2 = format!(
"│ └─ Faction: {}{}{}{} │ Effect: {} {}, Stats: 👥 {} | 💰 {} | 🛡️ {} | 🏗️ {}{}",
self.metadata.faction,
capital,
governor,
prestige,
self.effect_nature.to_symbol(),
self.effect_bounds.to_symbol(),
self.stats.demographics,
self.stats.economy,
self.stats.military,
self.stats.infrastructure,
" "
);
format!("{}\n{}", line1, line2)
}
}

View File

@ -12,13 +12,12 @@
#![allow(dead_code)]
#![deny(clippy::missing_docs_in_private_items)]
use crate::thin_newtype;
use cli_table::Color;
use cli_table::Table;
use colored::Colorize;
use derive_more::Display;
use serde::{Deserialize, Serialize};
use crate::thin_newtype;
mod implementations;
/// Aggregated statistics for a single entity.
@ -250,7 +249,7 @@ pub struct MetaStats {
pub position: Position,
/// Identifier for the capital
pub capital: TownId,
pub capital: Option<TownId>,
// /// List of nearby resource nodes (mines, forests, farms, etc.).
// ///
@ -275,7 +274,7 @@ pub struct MetaStats {
/// **Effect** - Adds personal bonuses and may modify policies
/// or diplomatic stance.
/// **Source** - `governor = selected_leader_uuid`.
pub governor: CharacterId,
pub governor: Option<CharacterId>,
// /// The entity's classification (capital, trade hub, frontier post, etc.).
// ///
@ -355,7 +354,20 @@ pub struct SummaryStats {
infrastructure: GenericStat,
}
impl From<OverallStats> for SummaryStats {
fn from(value: OverallStats) -> Self {
Self {
demographics: value.demographics,
economy: value.economy,
military: value.military,
infrastructure: value.infrastructure,
}
}
}
/// Bridge between the CLI and the statistics logic.
///
/// Helps convert clap arguments to OverallStats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[allow(missing_docs)]
pub enum ListStats {
@ -399,6 +411,22 @@ pub enum EntityType {
Event,
}
/// Trait to implement some symbol representations
pub trait Symbols {
/// Have a small Symbol to resume it
fn to_symbol(&self) -> String;
/// Have the shortest display possible
fn to_shortest(&self) -> String {
self.to_symbol()
}
}
// impl<T: Symbols> Display for T {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// write!(f, "{}", self.to_symbol())
// }
// }
// A stat that is shown to the player *and* can be modified manually.
thin_newtype!(GenericStat, isize);
thin_newtype!(TownId, usize);
@ -407,20 +435,20 @@ thin_newtype!(FactionId, usize);
// --- TRAITS ---------------------------------------------------------------
/// A stat is a *game value* that can be converted to two different
/// normalised ranges - a 50-point range for “gaming” logic and a
/// normalised ranges - a 100-point range for “gaming” logic and a
/// 10-point range for “roll & UI” logic. The trait also exposes the
/// underlying raw value and its visibility.
///
// TODO[7]: Change this with Deref+From
pub trait GameStat {
/// Convert the raw integer to a 50-point scale.
fn to_50(&self) -> isize {
(self.get_value().clamp(0, 70) - 10).min(50)
fn to_100(&self) -> isize {
(self.get_value().clamp(0, 120) - 10).min(100)
}
/// Convert the raw integer to a 10-point scale.
fn to_10(&self) -> isize {
self.to_50() / 5
self.to_100() / 10
}
/// As a colored delta (when the stat is used as a delta)

View File

@ -2,13 +2,19 @@
use std::str::FromStr;
use crate::entity::EffectApplication;
use crate::entity::EffectBounds;
use crate::entity::EntityDuration;
use crate::error::EpochError;
use crate::stats;
use crate::stats::EntityType;
use crate::stats::GameStat;
use crate::stats::GenericStat;
use crate::stats::ListStats;
use crate::stats::OverallStats;
use crate::stats::Position;
use crate::stats::StatPair;
use crate::stats::Symbols;
/// Creates a thin, deref-able wrapper around an inner type.
#[macro_export]
@ -233,215 +239,54 @@ impl FromStr for StatPair {
}
}
#[cfg(test)]
pub(crate) mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::stats::GameStat;
use crate::stats::GenericStat;
use std::str::FromStr;
struct Person {
name: GenericStat,
age: GenericStat,
email: GenericStat,
}
/// Helper that asserts that a string parses to the expected ListStats variant.
fn assert_stat_ok(input: &str, expected: ListStats) {
let parsed = ListStats::from_str(input).expect("should parse");
assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input);
}
field_accessor!(Person { name, age, email });
#[test]
fn test_field_accessors() {
let person = Person {
name: GenericStat(10),
age: GenericStat(20),
email: GenericStat(70),
};
let name = person.get_field("name").unwrap();
let email = person.get_field("email").unwrap();
let age = person.get_field("age").unwrap();
assert_eq!(name.to_50(), 0);
assert_eq!(age.to_50(), 10);
assert_eq!(email.to_50(), 50);
}
#[test]
fn test_clap_serialisation() {}
/// Helper that asserts that a stat pair string parses to the expected `StatPair`.
fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) {
let pair = StatPair::from_str(input).expect("should parse");
assert_eq!(pair.stat, expected_stat, "stat mismatch");
assert_eq!(pair.value.0, expected_val, "value mismatch");
}
#[test]
fn test_stat_pair_parsing() {
// Colon syntax
assert_pair_ok("cri:10", ListStats::Crime, 10);
assert_pair_ok("POP:-5", ListStats::Population, -5);
assert_pair_ok("growth:0", ListStats::Growthrate, 0);
// Space syntax (clap concatenates two separate args into one string)
assert_pair_ok("cri 10", ListStats::Crime, 10);
assert_pair_ok("Pop -5", ListStats::Population, -5);
assert_pair_ok("grow 0", ListStats::Growthrate, 0);
}
#[test]
fn test_list_stats_all_aliases() {
let stats = OverallStats::default();
// Demographics
assert_stat_ok("dem", ListStats::Demographics);
assert_stat_ok("Demog", ListStats::Demographics);
assert_stat_ok("DEMOGRAPHICS", ListStats::Demographics);
assert_stat_ok("Demo", ListStats::Demographics);
stats.get_field(ListStats::Demographics.into());
// Population
assert_stat_ok("pop", ListStats::Population);
assert_stat_ok("Popul", ListStats::Population);
assert_stat_ok("POPULATIONS", ListStats::Population);
stats.get_field(ListStats::Population.into());
// Growthrate
assert_stat_ok("grow", ListStats::Growthrate);
assert_stat_ok("GRW", ListStats::Growthrate);
assert_stat_ok("Growth", ListStats::Growthrate);
stats.get_field(ListStats::Growthrate.into());
// Crime
assert_stat_ok("cri", ListStats::Crime);
assert_stat_ok("CRIM", ListStats::Crime);
assert_stat_ok("Crimes", ListStats::Crime);
stats.get_field(ListStats::Crime.into());
// Happiness
assert_stat_ok("hapn", ListStats::Happiness);
assert_stat_ok("HAPPINES", ListStats::Happiness);
assert_stat_ok("hap", ListStats::Happiness);
stats.get_field(ListStats::Happiness.into());
// Economy
assert_stat_ok("eco", ListStats::Economy);
assert_stat_ok("Economy", ListStats::Economy);
assert_stat_ok("econ", ListStats::Economy);
stats.get_field(ListStats::Economy.into());
// Food
assert_stat_ok("food", ListStats::Food);
assert_stat_ok("fo", ListStats::Food);
assert_stat_ok("agr", ListStats::Food);
assert_stat_ok("agri", ListStats::Food);
stats.get_field(ListStats::Food.into());
// Industry
assert_stat_ok("industry", ListStats::Industry);
assert_stat_ok("Indus", ListStats::Industry);
assert_stat_ok("ind", ListStats::Industry);
stats.get_field(ListStats::Industry.into());
// Science
assert_stat_ok("science", ListStats::Science);
assert_stat_ok("sci", ListStats::Science);
assert_stat_ok("sc", ListStats::Science);
stats.get_field(ListStats::Science.into());
// Trade
assert_stat_ok("trade", ListStats::Trade);
assert_stat_ok("trd", ListStats::Trade);
assert_stat_ok("tr", ListStats::Trade);
stats.get_field(ListStats::Trade.into());
// Social
assert_stat_ok("social", ListStats::Social);
assert_stat_ok("soc", ListStats::Social);
assert_stat_ok("sl", ListStats::Social);
stats.get_field(ListStats::Social.into());
// Culture
assert_stat_ok("culture", ListStats::Culture);
assert_stat_ok("cul", ListStats::Culture);
assert_stat_ok("cl", ListStats::Culture);
stats.get_field(ListStats::Culture.into());
// Education
assert_stat_ok("education", ListStats::Education);
assert_stat_ok("edu", ListStats::Education);
assert_stat_ok("ed", ListStats::Education);
stats.get_field(ListStats::Education.into());
// Tourism
assert_stat_ok("tourism", ListStats::Tourism);
assert_stat_ok("tour", ListStats::Tourism);
assert_stat_ok("tm", ListStats::Tourism);
stats.get_field(ListStats::Tourism.into());
// Influence
assert_stat_ok("influence", ListStats::Influence);
assert_stat_ok("infl", ListStats::Influence);
assert_stat_ok("influ", ListStats::Influence);
stats.get_field(ListStats::Influence.into());
// Military
assert_stat_ok("military", ListStats::Military);
assert_stat_ok("mil", ListStats::Military);
assert_stat_ok("mt", ListStats::Military);
stats.get_field(ListStats::Military.into());
// Army
assert_stat_ok("army", ListStats::Army);
assert_stat_ok("arm", ListStats::Army);
assert_stat_ok("ar", ListStats::Army);
stats.get_field(ListStats::Army.into());
// Strength
assert_stat_ok("strength", ListStats::Strength);
assert_stat_ok("str", ListStats::Strength);
assert_stat_ok("st", ListStats::Strength);
stats.get_field(ListStats::Strength.into());
// Fortification
assert_stat_ok("fortification", ListStats::Fortification);
assert_stat_ok("fort", ListStats::Fortification);
assert_stat_ok("ft", ListStats::Fortification);
stats.get_field(ListStats::Fortification.into());
// Threat
assert_stat_ok("threat", ListStats::Threat);
assert_stat_ok("thr", ListStats::Threat);
assert_stat_ok("th", ListStats::Threat);
stats.get_field(ListStats::Threat.into());
// Infrastructure
assert_stat_ok("infrastructure", ListStats::Infrastructure);
assert_stat_ok("infra", ListStats::Infrastructure);
assert_stat_ok("infr", ListStats::Infrastructure);
stats.get_field(ListStats::Infrastructure.into());
// Bureaucracy
assert_stat_ok("bureaucracy", ListStats::Bureaucracy);
assert_stat_ok("bureau", ListStats::Bureaucracy);
assert_stat_ok("bur", ListStats::Bureaucracy);
stats.get_field(ListStats::Bureaucracy.into());
// Transportation
assert_stat_ok("transportation", ListStats::Transportation);
assert_stat_ok("trans", ListStats::Transportation);
assert_stat_ok("trns", ListStats::Transportation);
stats.get_field(ListStats::Transportation.into());
// Sprawl
assert_stat_ok("sprawl", ListStats::Sprawl);
assert_stat_ok("spr", ListStats::Sprawl);
assert_stat_ok("spra", ListStats::Sprawl);
stats.get_field(ListStats::Sprawl.into());
// Health
assert_stat_ok("health", ListStats::Health);
assert_stat_ok("hlth", ListStats::Health);
assert_stat_ok("hlt", ListStats::Health);
stats.get_field(ListStats::Health.into());
impl Symbols for EntityType {
fn to_symbol(&self) -> String {
match self {
EntityType::Character => "[C]".to_string(),
EntityType::Player => "[P]".to_string(),
EntityType::Town => "[T]".to_string(),
EntityType::Monster => "[M]".to_string(),
EntityType::Blocker => "[B]".to_string(),
EntityType::Event => "[E]".to_string(),
}
}
}
impl Symbols for EffectApplication {
fn to_symbol(&self) -> String {
match self {
EffectApplication::Recurring => "⟳".to_string(),
EffectApplication::WhenPresent => "⥯".to_string(),
EffectApplication::PermanentEffectToApply => "☈".to_string(),
EffectApplication::PermanentEffectApplied => "✓".to_string(),
}
}
}
impl Symbols for Position {
fn to_symbol(&self) -> String {
format!("⚓({},{})", self.0, self.1)
}
fn to_shortest(&self) -> String {
format!("{},{}", self.0, self.1)
}
}
impl Symbols for EntityDuration {
fn to_symbol(&self) -> String {
match self {
EntityDuration::Permanent => "∞".to_string(),
EntityDuration::Duration(t) => format!("⧗{}", t),
EntityDuration::Done => "✔".to_string(),
}
}
}
impl Symbols for EffectBounds {
fn to_symbol(&self) -> String {
format!("({}⭾{})", self.min, self.max)
}
}
#[cfg(test)]
pub(crate) mod test;

View File

@ -0,0 +1,209 @@
#![allow(clippy::unwrap_used)]
use super::*;
use crate::stats::GameStat;
use crate::stats::GenericStat;
use std::str::FromStr;
struct Person {
name: GenericStat,
age: GenericStat,
email: GenericStat,
}
/// Helper that asserts that a string parses to the expected ListStats variant.
fn assert_stat_ok(input: &str, expected: ListStats) {
let parsed = ListStats::from_str(input).expect("should parse");
assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input);
}
field_accessor!(Person { name, age, email });
#[test]
fn test_field_accessors() {
let person = Person {
name: GenericStat(10),
age: GenericStat(20),
email: GenericStat(120),
};
let name = person.get_field("name").unwrap();
let email = person.get_field("email").unwrap();
let age = person.get_field("age").unwrap();
assert_eq!(name.to_100(), 0);
assert_eq!(age.to_100(), 10);
assert_eq!(email.to_100(), 100);
}
#[test]
fn test_clap_serialisation() {}
/// Helper that asserts that a stat pair string parses to the expected `StatPair`.
fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) {
let pair = StatPair::from_str(input).expect("should parse");
assert_eq!(pair.stat, expected_stat, "stat mismatch");
assert_eq!(pair.value.0, expected_val, "value mismatch");
}
#[test]
fn test_stat_pair_parsing() {
// Colon syntax
assert_pair_ok("cri:10", ListStats::Crime, 10);
assert_pair_ok("POP:-5", ListStats::Population, -5);
assert_pair_ok("growth:0", ListStats::Growthrate, 0);
// Space syntax (clap concatenates two separate args into one string)
assert_pair_ok("cri 10", ListStats::Crime, 10);
assert_pair_ok("Pop -5", ListStats::Population, -5);
assert_pair_ok("grow 0", ListStats::Growthrate, 0);
}
#[test]
fn test_list_stats_all_aliases() {
let stats = OverallStats::default();
// Demographics
assert_stat_ok("dem", ListStats::Demographics);
assert_stat_ok("Demog", ListStats::Demographics);
assert_stat_ok("DEMOGRAPHICS", ListStats::Demographics);
assert_stat_ok("Demo", ListStats::Demographics);
stats.get_field(ListStats::Demographics.into());
// Population
assert_stat_ok("pop", ListStats::Population);
assert_stat_ok("Popul", ListStats::Population);
assert_stat_ok("POPULATIONS", ListStats::Population);
stats.get_field(ListStats::Population.into());
// Growthrate
assert_stat_ok("grow", ListStats::Growthrate);
assert_stat_ok("GRW", ListStats::Growthrate);
assert_stat_ok("Growth", ListStats::Growthrate);
stats.get_field(ListStats::Growthrate.into());
// Crime
assert_stat_ok("cri", ListStats::Crime);
assert_stat_ok("CRIM", ListStats::Crime);
assert_stat_ok("Crimes", ListStats::Crime);
stats.get_field(ListStats::Crime.into());
// Happiness
assert_stat_ok("hapn", ListStats::Happiness);
assert_stat_ok("HAPPINES", ListStats::Happiness);
assert_stat_ok("hap", ListStats::Happiness);
stats.get_field(ListStats::Happiness.into());
// Economy
assert_stat_ok("eco", ListStats::Economy);
assert_stat_ok("Economy", ListStats::Economy);
assert_stat_ok("econ", ListStats::Economy);
stats.get_field(ListStats::Economy.into());
// Food
assert_stat_ok("food", ListStats::Food);
assert_stat_ok("fo", ListStats::Food);
assert_stat_ok("agr", ListStats::Food);
assert_stat_ok("agri", ListStats::Food);
stats.get_field(ListStats::Food.into());
// Industry
assert_stat_ok("industry", ListStats::Industry);
assert_stat_ok("Indus", ListStats::Industry);
assert_stat_ok("ind", ListStats::Industry);
stats.get_field(ListStats::Industry.into());
// Science
assert_stat_ok("science", ListStats::Science);
assert_stat_ok("sci", ListStats::Science);
assert_stat_ok("sc", ListStats::Science);
stats.get_field(ListStats::Science.into());
// Trade
assert_stat_ok("trade", ListStats::Trade);
assert_stat_ok("trd", ListStats::Trade);
assert_stat_ok("tr", ListStats::Trade);
stats.get_field(ListStats::Trade.into());
// Social
assert_stat_ok("social", ListStats::Social);
assert_stat_ok("soc", ListStats::Social);
assert_stat_ok("sl", ListStats::Social);
stats.get_field(ListStats::Social.into());
// Culture
assert_stat_ok("culture", ListStats::Culture);
assert_stat_ok("cul", ListStats::Culture);
assert_stat_ok("cl", ListStats::Culture);
stats.get_field(ListStats::Culture.into());
// Education
assert_stat_ok("education", ListStats::Education);
assert_stat_ok("edu", ListStats::Education);
assert_stat_ok("ed", ListStats::Education);
stats.get_field(ListStats::Education.into());
// Tourism
assert_stat_ok("tourism", ListStats::Tourism);
assert_stat_ok("tour", ListStats::Tourism);
assert_stat_ok("tm", ListStats::Tourism);
stats.get_field(ListStats::Tourism.into());
// Influence
assert_stat_ok("influence", ListStats::Influence);
assert_stat_ok("infl", ListStats::Influence);
assert_stat_ok("influ", ListStats::Influence);
stats.get_field(ListStats::Influence.into());
// Military
assert_stat_ok("military", ListStats::Military);
assert_stat_ok("mil", ListStats::Military);
assert_stat_ok("mt", ListStats::Military);
stats.get_field(ListStats::Military.into());
// Army
assert_stat_ok("army", ListStats::Army);
assert_stat_ok("arm", ListStats::Army);
assert_stat_ok("ar", ListStats::Army);
stats.get_field(ListStats::Army.into());
// Strength
assert_stat_ok("strength", ListStats::Strength);
assert_stat_ok("str", ListStats::Strength);
assert_stat_ok("st", ListStats::Strength);
stats.get_field(ListStats::Strength.into());
// Fortification
assert_stat_ok("fortification", ListStats::Fortification);
assert_stat_ok("fort", ListStats::Fortification);
assert_stat_ok("ft", ListStats::Fortification);
stats.get_field(ListStats::Fortification.into());
// Threat
assert_stat_ok("threat", ListStats::Threat);
assert_stat_ok("thr", ListStats::Threat);
assert_stat_ok("th", ListStats::Threat);
stats.get_field(ListStats::Threat.into());
// Infrastructure
assert_stat_ok("infrastructure", ListStats::Infrastructure);
assert_stat_ok("infra", ListStats::Infrastructure);
assert_stat_ok("infr", ListStats::Infrastructure);
stats.get_field(ListStats::Infrastructure.into());
// Bureaucracy
assert_stat_ok("bureaucracy", ListStats::Bureaucracy);
assert_stat_ok("bureau", ListStats::Bureaucracy);
assert_stat_ok("bur", ListStats::Bureaucracy);
stats.get_field(ListStats::Bureaucracy.into());
// Transportation
assert_stat_ok("transportation", ListStats::Transportation);
assert_stat_ok("trans", ListStats::Transportation);
assert_stat_ok("trns", ListStats::Transportation);
stats.get_field(ListStats::Transportation.into());
// Sprawl
assert_stat_ok("sprawl", ListStats::Sprawl);
assert_stat_ok("spr", ListStats::Sprawl);
assert_stat_ok("spra", ListStats::Sprawl);
stats.get_field(ListStats::Sprawl.into());
// Health
assert_stat_ok("health", ListStats::Health);
assert_stat_ok("hlth", ListStats::Health);
assert_stat_ok("hlt", ListStats::Health);
stats.get_field(ListStats::Health.into());
}