Starts work on the diplayable trait

This commit is contained in:
Dandaedre 2025-11-30 23:56:33 +01:00
parent 9761978ad9
commit 6865de9e8c
5 changed files with 175 additions and 16 deletions

View File

@ -24,7 +24,6 @@
#![deny(clippy::unwrap_used)]
use clap::{ArgAction, Parser, Subcommand};
use lib_efo::naming::NAMING;
use crate::commands::init::InitCmd;
use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError};
@ -75,17 +74,13 @@ enum TopLevelCmd {
#[allow(clippy::unwrap_used)]
fn main() -> miette::Result<()> {
env_logger::init();
// 1. Generate a character name
let character = NAMING.generate_character_name();
println!("Character: {}", character);
// 2. Generate a town name
let town = NAMING.generate_town_name();
println!("Town: {}", town);
// 3. Pick an event idea
let event = NAMING.generate_long_character_name();
println!("Event idea: {}", event);
// let e = Entity::default();
// println!("{e:#?}");
// 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

@ -13,13 +13,16 @@
use serde::{Deserialize, Serialize};
use crate::stats::{EntityType, MetaStats, OverallStats};
pub mod implementations;
/// An entity that can be present in the game world.
///
/// Entities are mutable only through the entity system’s public API.
/// Their fields are private to prevent accidental state corruption.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Entity {
/// The name of the entity
name: String,
/// Runtime statistics that determine the entity’s behaviour.
///
/// These values are updated by the game loop and reflect the
@ -67,14 +70,14 @@ pub struct Entity {
/// been calculated to keep stats within a sane range.
///
/// `min` and `max` are inclusive.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[allow(missing_docs)]
pub struct EffectBounds {
pub min: usize,
pub max: usize,
}
/// How the entity’s effect is applied over time.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub enum EffectApplication {
/// Repeatedly applied every turn while the entity is present.
/// Use with caution, as this can produce catastrophic results
@ -88,6 +91,7 @@ pub enum EffectApplication {
/// Permanently modifies stats; the change persists after
/// the event ends.
#[default]
PermanentEffectToApply,
/// Indicates that a permanent effect has already been applied.
@ -97,7 +101,7 @@ pub enum EffectApplication {
}
/// Represents how long an entity remains active in the world.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
pub enum EntityDuration {
/// The entity persists until it is explicitly destroyed.
Permanent,
@ -110,5 +114,6 @@ pub enum EntityDuration {
/// The entity’s lifecycle has finished and it should no longer
/// be updated. This variant is typically used for one‑off
/// events or buffs that expire after their final turn.
#[default]
Done,
}

View File

@ -0,0 +1,104 @@
//! Implementation of all needed traits for the Entity struct
use cli_table::{Style, WithTitle, print_stdout};
use colored::*; // [3] – colored‑rs examples
use crate::Displayable;
use crate::entity::Entity;
// ---------- Implementation ----------
impl Displayable for Entity {
// Detailed multi‑line view (used e.g. in logs)
fn print_full(&self) {
println!(
"{:?}\n{}",
self.metadata.position, // Display
format!(
"{} | {} | {} | {:?} | {}",
self.metadata.capital,
self.metadata.governor,
self.metadata.faction,
self.metadata.links,
self.metadata.prestige
)
.blue() // colour the whole line (you can tweak colours per field)
);
let meta_ext = format!(
"{:?} | {:?} | {:?} | {:?}",
self.duration, self.effect_nature, self.effect_bounds, self.entity_type
)
.green(); // another colour
println!("{meta_ext}");
print_stdout(vec![&self.stats, &self.temp_stats].with_title().bold(true)).expect("");
}
// Short, single‑line representation
fn print_short(&self) {
println!(
"{} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?}",
self.name,
self.metadata.position,
self.duration,
self.effect_nature,
self.effect_bounds,
self.entity_type,
self.metadata.prestige
);
print_stdout(vec![&self.stats].with_title().bold(true)).expect("")
}
// One‑liner used for auto‑generation of Vec<T> displays
fn oneline_display(&self) -> String {
format!(
"{} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?}",
self.name,
self.metadata.position,
self.duration,
self.effect_nature,
self.effect_bounds,
self.entity_type,
self.metadata.capital,
self.metadata.prestige
)
}
}
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), s) };
let mut out = String::new();
out.push_str(&indent(0, "self\n"));
out.push_str(&indent(1, &format!("├─ name: {}\n", self.name)));
out.push_str(&indent(1, "├─ metadata\n"));
out.push_str(&indent(
2,
&format!("├─ position: {:?}\n", self.metadata.position),
));
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)));
out.push_str(&indent(
1,
&format!("├─ effect_nature: {:?}\n", self.effect_nature),
));
out.push_str(&indent(
1,
&format!("├─ effect_bounds: {:?}\n", self.effect_bounds),
));
out.push_str(&indent(
1,
&format!("└─ entity_type: {:?}\n", self.entity_type),
));
out
}
}

View File

@ -55,3 +55,57 @@ where
/// List all ids known to this store.
fn list_ids(&self) -> IoResult<Vec<String>>;
}
/// A trait for types that can be displayed in a command‑line tool.
///
/// Implementors should provide three levels of representation:
/// 1. **Full** – a detailed view suitable for a long‑running command.
/// 2. **Short** – a concise, user‑friendly view that fits on a single line.
/// 3. **Oneline** – a compact, machine‑friendly string that can be embedded
/// inside a `Vec<T>` representation.
///
/// ## `Vec<T>` support
///
/// The trait is implemented generically for `Vec<T>` as long as `T: Displayable`.
/// This allows you to call `full_display`, `short_display` or `oneline_display`
/// directly on a vector of displayable items.
pub trait Displayable {
/// Return a fully‑described string representation.
fn print_full(&self);
/// Return a short, user‑friendly string.
fn print_short(&self);
/// Return a one‑liner string, suitable for embedding in a collection
/// representation (e.g. a `Vec<T>`). Implementations should avoid
/// new‑lines to keep the output usable in a single line context.
fn oneline_display(&self) -> String;
/// Print oneline
fn print_oneline(&self) {
println!("{}", self.oneline_display())
}
}
/// Implement `Displayable` for vectors of displayable items.
///
/// The implementation simply delegates to the underlying `T::oneline_display`
/// method and joins the results with a comma. It works for any `T` that
/// already implements `Displayable`. This is a **blanket implementation**,
/// so you do not need to write a manual impl for each concrete type
impl<T: Displayable> Displayable for Vec<T> {
fn print_full(&self) {
self.iter().for_each(|e| e.print_full());
}
fn print_short(&self) {
self.iter().for_each(|e| e.print_short());
}
fn oneline_display(&self) -> String {
// No brackets – just a flat, comma‑separated list.
self.iter()
.map(|x| x.oneline_display())
.collect::<Vec<_>>()
.join(",")
}
}

View File

@ -362,13 +362,14 @@ pub enum ListStats {
/// The list of all types of entities
#[allow(missing_docs)]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub enum EntityType {
Character,
Player,
Town,
Monster,
Blocker,
#[default]
Event,
}