Temps stats optionnal & Better display
Build Failed The build failed
Gitea/epoch_forge/pipeline/head There was a failure building this commit
Details
Build Failed The build failed
Gitea/epoch_forge/pipeline/head There was a failure building this commit
Details
This commit is contained in:
parent
1c02a37f66
commit
f475ae146b
|
|
@ -41,7 +41,7 @@ pub struct Entity {
|
|||
/// `temp_stats` is recalculated each turn and does not persist
|
||||
/// beyond the entity's lifetime.
|
||||
#[serde(skip)]
|
||||
temp_stats: OverallStats,
|
||||
temp_stats: Option<OverallStats>,
|
||||
|
||||
/// Non-statistical metadata such as name, rarity, and faction.
|
||||
///
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
//! Implementation of all needed traits for the Entity struct
|
||||
use cli_table::format::{Border, HorizontalLine, Separator, VerticalLine};
|
||||
use cli_table::{Style, WithTitle, print_stdout};
|
||||
use cli_table::{Style, WithTitle};
|
||||
use colored::*;
|
||||
use rand::distr::Distribution;
|
||||
use uuid::Uuid; // [3] - colored-rs examples
|
||||
|
|
@ -16,37 +16,18 @@ use crate::utils::RngLevel;
|
|||
impl Displayable for Entity {
|
||||
// Detailed multi-line view (used e.g. in logs)
|
||||
fn print_full(&self) {
|
||||
println!(
|
||||
"{}\n{}",
|
||||
self.to_pretty_tree(),
|
||||
format!("{:?} | {:?}", self.metadata.governor, self.metadata.faction).blue() // colour the whole line (you can tweak colours per field)
|
||||
);
|
||||
print_stdout(
|
||||
vec![&self.stats, &self.temp_stats]
|
||||
.with_title()
|
||||
.bold(true)
|
||||
.border(
|
||||
Border::builder()
|
||||
.top(HorizontalLine::new('┌', '┐', '┬', '─'))
|
||||
.bottom(HorizontalLine::new('└', '┘', '┴', '─'))
|
||||
.left(VerticalLine::new('│'))
|
||||
.right(VerticalLine::new('│'))
|
||||
.build(),
|
||||
)
|
||||
.separator(
|
||||
Separator::builder()
|
||||
.column(Some(VerticalLine::new('│')))
|
||||
.row(Some(HorizontalLine::new('├', '┤', '┼', '─')))
|
||||
.build(),
|
||||
),
|
||||
)
|
||||
.expect("");
|
||||
println!("{}", self.to_pretty_tree(),);
|
||||
if let Ok(c) = self.stats_to_table() {
|
||||
println!("{c}");
|
||||
}
|
||||
}
|
||||
|
||||
// Short, single-line representation
|
||||
fn print_short(&self) {
|
||||
println!("{}", self.to_pretty_tree());
|
||||
print_stdout(vec![&self.stats].with_title().bold(true)).expect("")
|
||||
if let Ok(c) = self.stats_to_table() {
|
||||
println!("{c}");
|
||||
}
|
||||
}
|
||||
|
||||
/// One-liner used for auto-generation of Vec<T> displays
|
||||
|
|
@ -65,7 +46,7 @@ impl Displayable for Entity {
|
|||
.map(|g| format!(" | 👑 {:>2}", g))
|
||||
.unwrap_or_default();
|
||||
|
||||
let prestige = if self.metadata.prestige > 0 {
|
||||
let prestige = if *self.metadata.prestige > 0 {
|
||||
format!(" {:2}{}", self.metadata.prestige, "📈".yellow())
|
||||
} else {
|
||||
String::new()
|
||||
|
|
@ -101,62 +82,176 @@ impl Displayable for Entity {
|
|||
}
|
||||
|
||||
impl Entity {
|
||||
/// Just show a pretty tree
|
||||
pub fn to_pretty_tree(&self) -> String {
|
||||
// Helper that indents a line
|
||||
let indent = |level: usize, s: &str| -> String {
|
||||
format!(" {}{}", "│ ".repeat(level.saturating_sub(1)), s)
|
||||
// Display the entity’s statistics in a pretty table.
|
||||
///
|
||||
/// The table contains both the permanent and temporary statistics of the
|
||||
/// entity. The table is formatted with a custom border and separator
|
||||
/// using the `cli_table` crate.
|
||||
///
|
||||
/// # Returns
|
||||
/// A `Result` containing the table display on success, or an `EpochError` if the
|
||||
/// conversion to a table string fails.
|
||||
pub fn full_stats_to_table(&self) -> Result<cli_table::TableDisplay, EpochError> {
|
||||
let items = if let Some(t) = &self.temp_stats {
|
||||
vec![&self.stats, t]
|
||||
} else {
|
||||
vec![&self.stats]
|
||||
};
|
||||
self.stat_to_table(items)
|
||||
}
|
||||
|
||||
/// Display the entity’s statistics in a pretty table (same format as
|
||||
/// `full_stats_to_table`).
|
||||
///
|
||||
/// This method is provided for backward compatibility and forwards all
|
||||
/// work to `full_stats_to_table`.
|
||||
///
|
||||
/// # Returns
|
||||
/// A `Result` containing the table display on success, or an `EpochError` if the
|
||||
/// conversion to a table string fails.
|
||||
pub fn stats_to_table(&self) -> Result<cli_table::TableDisplay, EpochError> {
|
||||
let items = if let Some(t) = &self.temp_stats {
|
||||
vec![t]
|
||||
} else {
|
||||
vec![&self.stats]
|
||||
};
|
||||
self.stat_to_table(items)
|
||||
}
|
||||
|
||||
/// Display the entity’s statistics in a pretty table (same format as
|
||||
/// `full_stats_to_table`).
|
||||
///
|
||||
/// This method is provided for backward compatibility and forwards all
|
||||
/// work to `full_stats_to_table`.
|
||||
///
|
||||
/// # Returns
|
||||
/// A `Result` containing the table display on success, or an `EpochError` if the
|
||||
/// conversion to a table string fails.
|
||||
///
|
||||
fn stat_to_table(
|
||||
&self,
|
||||
items: Vec<&OverallStats>,
|
||||
) -> Result<cli_table::TableDisplay, EpochError> {
|
||||
items
|
||||
.with_title()
|
||||
.bold(true)
|
||||
.border(
|
||||
Border::builder()
|
||||
.top(HorizontalLine::new('┌', '┐', '┬', '─'))
|
||||
.bottom(HorizontalLine::new('└', '┘', '┴', '─'))
|
||||
.left(VerticalLine::new('│'))
|
||||
.right(VerticalLine::new('│'))
|
||||
.build(),
|
||||
)
|
||||
.separator(
|
||||
Separator::builder()
|
||||
.column(Some(VerticalLine::new('│')))
|
||||
.row(Some(HorizontalLine::new('├', '┤', '┼', '─')))
|
||||
.build(),
|
||||
)
|
||||
.display()
|
||||
.map_err(|_e| EpochError::TableStringConversionError {
|
||||
name: self.name.clone(),
|
||||
id: self.id,
|
||||
})
|
||||
}
|
||||
|
||||
/// Pretty‑print the entity as a coloured tree.
|
||||
///
|
||||
/// The output is a `String` that visualises the entity’s metadata, type,
|
||||
/// duration, effect bounds, and any links. Colours are applied using
|
||||
/// `colored::Colorize`.
|
||||
///
|
||||
/// # Returns
|
||||
/// A `String` containing the formatted tree.
|
||||
pub fn to_pretty_tree(&self) -> String {
|
||||
// Helper that prefixes a line with the correct amount of vertical bars.
|
||||
fn indent(level: usize, line: &str) -> String {
|
||||
let bars = "│ ".repeat(level);
|
||||
format!(" {}{}", bars, line)
|
||||
}
|
||||
|
||||
let mut out = String::new();
|
||||
|
||||
// out.push_str(&indent(0, "self\n"));
|
||||
out.push_str(&indent(0, &format!("├─ name: {}\n", self.name)));
|
||||
out.push_str(&indent(1, &format!("├─ {}\n", "metadata")));
|
||||
out.push_str(&indent(
|
||||
2,
|
||||
&format!("├─ position: {:?}\n", self.metadata.position),
|
||||
// ── Top line: <entity_type> <name>
|
||||
out.push_str(&format!(
|
||||
"[{} {}]\n",
|
||||
self.entity_type.to_symbol().blue().bold(), // entity type
|
||||
self.name.cyan().bold() // name
|
||||
));
|
||||
out.push_str(&indent(
|
||||
2,
|
||||
&format!("├─ capital: {:?}\n", self.metadata.capital),
|
||||
));
|
||||
out.push_str(&indent(
|
||||
2,
|
||||
&format!("└─ prestige: {:?}\n", self.metadata.prestige),
|
||||
));
|
||||
out.push_str(&indent(1, &format!("├─ duration: {:?}\n", self.duration)));
|
||||
|
||||
// ── Metadata section
|
||||
out.push_str(&indent(0, "├─ metadata\n"));
|
||||
out.push_str(&indent(
|
||||
1,
|
||||
&format!("├─ position: {}\n", self.metadata.position.to_symbol()),
|
||||
));
|
||||
out.push_str(&indent(
|
||||
1,
|
||||
&format!("├─ capital: {:?}\n", self.metadata.capital),
|
||||
));
|
||||
out.push_str(&indent(
|
||||
1,
|
||||
&format!("└─ prestige: {}\n", self.metadata.prestige),
|
||||
));
|
||||
|
||||
// ── Other top‑level fields
|
||||
out.push_str(&indent(
|
||||
0,
|
||||
&format!("├─ duration: {}\n", self.duration.to_symbol().magenta()),
|
||||
));
|
||||
out.push_str(&indent(
|
||||
0,
|
||||
&format!("├─ effect_nature: {:?}\n", self.effect_nature),
|
||||
));
|
||||
out.push_str(&indent(
|
||||
1,
|
||||
&format!("├─ effect_bounds: {:?}\n", self.effect_bounds),
|
||||
0,
|
||||
&format!("├─ effect_bounds: {}\n", self.effect_bounds.to_symbol()),
|
||||
));
|
||||
|
||||
// ── Optional links
|
||||
if !self.metadata.links.is_empty() {
|
||||
out.push_str(&indent(1, &format!("├─ {}\n", "links")));
|
||||
for link in &self.metadata.links {
|
||||
out.push_str(&indent(2, &format!("├─ {:?}\n", link)));
|
||||
out.push_str(&indent(0, "├─ links\n"));
|
||||
for (i, link) in self.metadata.links.iter().enumerate() {
|
||||
let last = i == self.metadata.links.len() - 1;
|
||||
let symbol = if last { "└─" } else { "├─" };
|
||||
out.push_str(&indent(
|
||||
1,
|
||||
&format!("{} {}", symbol.cyan(), link.to_string().yellow()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Entity type again at the end (if you want it back here)
|
||||
out.push_str(&indent(
|
||||
1,
|
||||
&format!("└─ entity_type: {:?}\n", self.entity_type),
|
||||
0,
|
||||
&format!("└─ entity_type: {}", self.entity_type.to_shortest()),
|
||||
));
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Create an entity using Special Rng Levels
|
||||
/// Create an entity using a specific RNG level.
|
||||
///
|
||||
/// The entity is initialised with random statistics, a random position,
|
||||
/// and a random prestige value derived from the supplied `RngLevel`.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `e_type` – The type of entity to create.
|
||||
/// * `rng` – The RNG level to use when generating random values.
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(Self)` – The newly created entity.
|
||||
/// * `Err(EpochError)` – Propagated from any randomisation failure.
|
||||
///
|
||||
pub fn create_rng(e_type: &EntityType, rng: &RngLevel) -> Result<Self, EpochError> {
|
||||
let mut r = rand::rng();
|
||||
Ok(Self {
|
||||
id: Uuid::new_v4(),
|
||||
stats: OverallStats::create_rng(rng, &mut r)?,
|
||||
temp_stats: OverallStats::default(),
|
||||
temp_stats: None,
|
||||
metadata: MetaStats {
|
||||
prestige: (rng.to_rng()?.sample(&mut r) as usize),
|
||||
prestige: GenericStat(rng.to_rng()?.sample(&mut r) as isize),
|
||||
position: Position::create_rng(&mut r)?,
|
||||
..Default::default()
|
||||
},
|
||||
|
|
@ -165,13 +260,26 @@ impl Entity {
|
|||
})
|
||||
}
|
||||
|
||||
// TODO: Redoc
|
||||
/// Change a stat with a given statpair
|
||||
/// Change one of the entity’s statistics.
|
||||
///
|
||||
/// The stat identified by `pair` is replaced with the new value specified in
|
||||
/// the `StatPair`. This is a direct overwrite and does not apply any delta.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `pair` – The stat pair containing the key and new value.
|
||||
///
|
||||
pub fn change_stat(&mut self, pair: StatPair) {
|
||||
overwrite_stat(&mut self.stats, pair);
|
||||
}
|
||||
|
||||
/// Applies a delta to all the stats
|
||||
/// Apply a delta to all of the entity’s statistics.
|
||||
///
|
||||
/// The delta specified by `pair` is added to each of the statistics in
|
||||
/// `self.stats`. Positive values increase the stat, negative values
|
||||
/// decrease it.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `pair` – The stat pair representing the change to apply.
|
||||
pub fn delta_stat(&mut self, pair: StatPair) {
|
||||
add_to_stat(&mut self.stats, pair);
|
||||
}
|
||||
|
|
@ -214,7 +322,7 @@ impl Diffable for Entity {
|
|||
Self {
|
||||
name,
|
||||
stats: self.stats.clone() - other.stats.clone(),
|
||||
temp_stats: self.temp_stats.clone() - other.temp_stats.clone(),
|
||||
temp_stats: self.temp_stats.delta(&other.temp_stats),
|
||||
metadata: self.metadata.delta(&other.metadata),
|
||||
entity_type: self.entity_type.clone(),
|
||||
duration: self.duration.clone(),
|
||||
|
|
@ -225,6 +333,17 @@ impl Diffable for Entity {
|
|||
}
|
||||
}
|
||||
|
||||
impl Diffable for Option<OverallStats> {
|
||||
fn delta(&self, other: &Self) -> Self {
|
||||
match (self, other) {
|
||||
(None, None) => None,
|
||||
(None, Some(a)) => Some(a.clone()),
|
||||
(Some(a), None) => Some(a.clone()),
|
||||
(Some(a), Some(b)) => Some(a.clone() - b.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Diffable for MetaStats {
|
||||
fn delta(&self, other: &Self) -> Self {
|
||||
diff_fields!(self, other, capital, governor);
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
|
||||
use derive_more::Display;
|
||||
use std::{num::ParseIntError, path::PathBuf};
|
||||
use uuid::Uuid;
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
|
|
@ -268,9 +269,20 @@ pub enum EpochError {
|
|||
|
||||
/// One of the components failed to parse as an `isize`.
|
||||
#[error("Failed to parse integer: {0}")]
|
||||
#[diagnostic(code(EpochError::ParseInt))]
|
||||
#[diagnostic(code(EpochError::ParsePositionError))]
|
||||
#[help("Ensure that the input is a valid integer.")]
|
||||
ParsePositionError(String),
|
||||
|
||||
/// Failed to render a table into its string representation.
|
||||
#[error("Failed to render table {name} [{id}] as string")]
|
||||
#[diagnostic(code(EpochError::TableStringConversion))]
|
||||
#[help("Verify that the table data and schema are compatible with string rendering.")]
|
||||
TableStringConversionError {
|
||||
/// The logical name of the table that failed to convert.
|
||||
name: String,
|
||||
/// The UUID that uniquely identifies the table instance.
|
||||
id: Uuid,
|
||||
},
|
||||
}
|
||||
|
||||
/// A small enum of explicit user-facing error messages.
|
||||
|
|
|
|||
|
|
@ -365,7 +365,7 @@ pub struct MetaStats {
|
|||
/// **Effect** - Affects diplomatic influence, trade bonuses,
|
||||
/// and event outcomes.
|
||||
/// **Source** - `prestige = calculate_prestige(...)`.
|
||||
pub prestige: usize,
|
||||
pub prestige: GenericStat,
|
||||
}
|
||||
|
||||
/// A generic stat pair with (ListStats, GenericStat), used mainly for clap
|
||||
|
|
|
|||
|
|
@ -418,7 +418,7 @@ impl Symbols for EntityDuration {
|
|||
|
||||
impl Symbols for EffectBounds {
|
||||
fn to_symbol(&self) -> String {
|
||||
format!("({}⭾{})", self.min, self.max)
|
||||
format!("({} ⭾ {})", self.min, self.max)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue