434 lines
16 KiB
Rust
434 lines
16 KiB
Rust
//! Module that holds all statistics for an entity and the helper methods that operate on them.
|
|
//!
|
|
//! The statistics are grouped into thematic sections (Demographics, Economy, Social, Military,
|
|
//! Infrastructure). Each field is a `GenericStat`, an internal wrapper around a numeric value
|
|
//! that provides convenience methods such as `max()`, `clamp()`, and arithmetic ops.
|
|
//!
|
|
//! The documentation for each field follows the same three-part template:
|
|
//! * **Purpose** - What the stat represents.
|
|
//! * **Effect** - Gameplay consequence of the stat.
|
|
//! * **Source** - Formula or function that generates the stat value.
|
|
|
|
#![allow(dead_code)]
|
|
#![deny(clippy::missing_docs_in_private_items)]
|
|
|
|
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.
|
|
///
|
|
/// The struct is intentionally flat to keep access fast; the fields are logically grouped
|
|
/// by comment blocks that describe each thematic section.
|
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
// Derive more
|
|
#[derive(Table)]
|
|
// #[derive(Add, Sub)]
|
|
pub struct OverallStats {
|
|
// ──────────────────────── Demographics ────────────────────────
|
|
/// Total economic health of the entity.
|
|
///
|
|
/// **Purpose** - A single value summarizing all economic indicators.
|
|
/// **Effect** - Drives tax revenue, spending power, and overall economic influence.
|
|
/// **Source** - Sum of `industry`, `science`, `trade`, and other economic contributors.
|
|
pub demographics: GenericStat,
|
|
/// Population count.
|
|
///
|
|
/// **Purpose** - The number of citizens living in the entity.
|
|
/// **Effect** - Determines resource consumption, tax base, and potential unrest.
|
|
/// **Source** - Updated by the growth/decay formulas each turn.
|
|
pub population: GenericStat,
|
|
|
|
/// Per-turn change in population.
|
|
///
|
|
/// **Purpose** - The growth rate of the population.
|
|
/// **Effect** - Predicts future needs and signals potential social unrest.
|
|
/// **Source** - Derived from `population`, `happiness`, and `stability`.
|
|
pub growth_rate: GenericStat,
|
|
|
|
/// Crime level (0-1 scale).
|
|
///
|
|
/// **Purpose** - How frequently crimes occur.
|
|
/// **Effect** - Can trigger riots and reduce stability.
|
|
/// **Source** - Result of the crime function (influenced by class disparity and law enforcement).
|
|
pub crime: GenericStat,
|
|
|
|
/// Base happiness of the population (0-1 scale).
|
|
///
|
|
/// **Purpose** - A measure of citizen contentment.
|
|
/// **Effect** - Influences productivity, tax compliance, and unrest.
|
|
/// **Source** - Output of the happiness function (affected by class, war, infrastructure).
|
|
pub happiness: GenericStat,
|
|
|
|
// ──────────────────────── Economy ────────────────────────
|
|
/// Aggregate economic health of the entity.
|
|
///
|
|
/// **Purpose** - A single value summarizing all economic metrics.
|
|
/// **Effect** - Drives revenue, spending, and empire-wide economic influence.
|
|
/// **Source** - Sum of `food`, `industry`, `science`, `trade`, etc.
|
|
pub economy: GenericStat,
|
|
|
|
/// Food produced by the entity.
|
|
///
|
|
/// **Purpose** - Amount of consumable resources available.
|
|
/// **Effect** - Keeps the population alive and productive.
|
|
/// **Source** - `food = farm_yield + tech_level`.
|
|
pub food: GenericStat,
|
|
|
|
/// Strength of the industry.
|
|
///
|
|
/// **Purpose** - Industrial production capacity.
|
|
/// **Effect** - Drives tax revenue and unit production.
|
|
/// **Source** - `industry = factory_output + tech_level`.
|
|
pub industry: GenericStat,
|
|
|
|
/// Scientific output.
|
|
///
|
|
/// **Purpose** - Rate of research progress.
|
|
/// **Effect** - Determines how quickly new technologies are unlocked.
|
|
/// **Source** - `science = research_center_output + tech_level`.
|
|
pub science: GenericStat,
|
|
|
|
/// Trade volume / exports.
|
|
///
|
|
/// **Purpose** - Measure of export activity.
|
|
/// **Effect** - Influences influence and wealth.
|
|
/// **Source** - `trade = trade_network_output`.
|
|
pub trade: GenericStat,
|
|
// // ──────────────────────── Social ────────────────────────
|
|
// /// Overall social prestige.
|
|
// ///
|
|
// /// **Purpose** - Reflects the cultural standing of the entity.
|
|
// /// **Effect** - Affects diplomacy and citizen morale.
|
|
// /// **Source** - Sum of `culture`, `education`, `tourism`, etc.
|
|
// pub social: GenericStat,
|
|
|
|
// /// Cultural output from arts, theatres, museums, etc.
|
|
// ///
|
|
// /// **Purpose** - Measure of cultural production.
|
|
// /// **Effect** - Drives tourism, prestige, and happiness.
|
|
// /// **Source** - `culture = Σ(cultural_building_output)`.
|
|
// pub culture: GenericStat,
|
|
|
|
// /// Level of education/literacy.
|
|
// ///
|
|
// /// **Purpose** - Measure of the citizenry's knowledge.
|
|
// /// **Effect** - Improves productivity, science output, and reduces unrest.
|
|
// /// **Source** - `education = Σ(education_building_output)`.
|
|
// pub education: GenericStat,
|
|
|
|
// /// Tourism revenue.
|
|
// ///
|
|
// /// **Purpose** - Income generated by visitors.
|
|
// /// **Effect** - Provides an additional income stream.
|
|
// /// **Source** - `tourism = number_of_tourists x price_per_tourist`.
|
|
// pub tourism: GenericStat,
|
|
|
|
// /// Cultural influence over the region.
|
|
// ///
|
|
// /// **Purpose** - Measure of soft power.
|
|
// /// **Effect** - Grants diplomatic bonuses and increases sway in the empire.
|
|
// /// **Source** - `influence = culture x population`.
|
|
// pub influence: GenericStat,
|
|
|
|
// ──────────────────────── Military ────────────────────────
|
|
/// Overall military power.
|
|
///
|
|
/// **Purpose** - Composite measure of combat capability.
|
|
/// **Effect** - Determines defensive and offensive strength.
|
|
/// **Source** - Sum of `army`, `strength`, `fortification`, etc.
|
|
pub military: GenericStat,
|
|
|
|
/// Number of battle-ready units.
|
|
///
|
|
/// **Purpose** - Size of the active army.
|
|
/// **Effect** - Directly dictates defense and attack potential.
|
|
/// **Source** - Sum of all trained and equipped units.
|
|
pub army: GenericStat,
|
|
|
|
/// Composite strength of the army.
|
|
///
|
|
/// **Purpose** - Tech, training, and equipment bonuses aggregated.
|
|
/// **Effect** - Determines combat effectiveness and required force to defeat an enemy.
|
|
/// **Source** - `strength = Σ(unit_strength) x tech_bonus x training_bonus`.
|
|
pub strength: GenericStat,
|
|
|
|
/// Defensive bonus from fortifications.
|
|
///
|
|
/// **Purpose** - Wall and tower defenses.
|
|
/// **Effect** - Adds a multiplier to overall defense.
|
|
/// **Source** - `fortification = Σ(fortification_building_bonus)`.
|
|
pub fortification: GenericStat,
|
|
|
|
/// Threat level facing the entity.
|
|
///
|
|
/// **Purpose** - Likelihood of being attacked.
|
|
/// **Effect** - Triggers early warning alerts and strategic decisions.
|
|
/// **Source** - `threat = (enemy_proximity + enemy_strength) / defense`.
|
|
pub threat: GenericStat,
|
|
|
|
// ──────────────────────── Infrastructure ────────────────────────
|
|
/// Total infrastructure power.
|
|
///
|
|
/// **Purpose** - Overall built-environment capacity.
|
|
/// **Effect** - Supports population size and efficiency.
|
|
/// **Source** - Sum of all infrastructure components.
|
|
pub infrastructure: GenericStat,
|
|
|
|
/// Bureaucratic power.
|
|
///
|
|
/// **Purpose** - Efficiency of the city's administrative machinery.
|
|
/// **Effect** - Improves resource management and policy implementation.
|
|
/// **Source** - `bureaucracy = Σ(bureaucracy_building_output)`.
|
|
pub bureaucracy: GenericStat,
|
|
|
|
/// Transportation level.
|
|
///
|
|
/// **Purpose** - Availability and quality of transport infrastructure.
|
|
/// **Effect** - Impacts logistics, mobility, and trade.
|
|
/// **Source** - `transportation = Σ(transport_building_output)`.
|
|
pub transportation: GenericStat,
|
|
|
|
/// Sprawl / urban density.
|
|
///
|
|
/// **Purpose** - Measure of city sprawl and clutter.
|
|
/// **Effect** - Affects health, happiness, and infrastructure efficiency.
|
|
/// **Source** - `sprawl = Σ(sprawl_factor)`.
|
|
pub sprawl: GenericStat,
|
|
|
|
/// Health infrastructure quality.
|
|
///
|
|
/// **Purpose** - Public health capacity.
|
|
/// **Effect** - Affects population health and can generate unrest.
|
|
/// **Source** - `health = output_of_health_function` (influenced by sanitation, disease spread, etc.).
|
|
pub health: GenericStat,
|
|
}
|
|
|
|
/// Strategic context and meta-data for an entity.
|
|
///
|
|
/// All fields are intentionally simple - the logic that interprets them
|
|
/// lives in separate modules (e.g. `map`, `network`, `governance`).
|
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
pub struct MetaStats {
|
|
// ──── Location & Spatial Data (hidden) ───────────────────────────────
|
|
/// Cartesian coordinates of the entity on the world map.
|
|
///
|
|
/// **Purpose** - Position of the entity in the simulation grid.
|
|
/// **Effect** - Used for distance calculations, visibility, and
|
|
/// map-based event logic.
|
|
/// **Source** - Supplied by the map generator.
|
|
pub position: Position,
|
|
|
|
/// Identifier for the capital
|
|
pub capital: TownId,
|
|
|
|
// /// List of nearby resource nodes (mines, forests, farms, etc.).
|
|
// ///
|
|
// /// **Purpose** - Resource map around the entity.
|
|
// /// **Effect** - Drives the entity's specialization and determines
|
|
// /// the default output mix.
|
|
// /// **Source** - `resources = filter(resource_list, distance ≤ detection_radius)`.
|
|
// pub resources: Vec<String>,
|
|
|
|
// /// The entity's chosen specialization tag
|
|
// /// (e.g., “Agricultural Hub”, “Industrial Center”).
|
|
// ///
|
|
// /// **Purpose** - Identity that dictates default production multipliers.
|
|
// /// **Effect** - Alters output curves and trade attractiveness.
|
|
// /// **Source** - `specialization = tag_assigned_by_player_or_ai`.
|
|
// pub specialization: String,
|
|
|
|
// ──── Strategic Positioning (hidden + public) ─────────────────────
|
|
/// Current governor or leader assigned to the entity.
|
|
///
|
|
/// **Purpose** - Leadership identity.
|
|
/// **Effect** - Adds personal bonuses and may modify policies
|
|
/// or diplomatic stance.
|
|
/// **Source** - `governor = selected_leader_uuid`.
|
|
pub governor: CharacterId,
|
|
|
|
// /// The entity's classification (capital, trade hub, frontier post, etc.).
|
|
// ///
|
|
// /// **Purpose** - Functional role within the empire.
|
|
// /// **Effect** - Alters base production, tax rates, and
|
|
// /// certain event probabilities.
|
|
// /// **Source** - `role = tag_assigned_by_player_or_ai`.
|
|
// pub role: String,
|
|
/// The faction or empire to which the entity currently belongs.
|
|
///
|
|
/// **Purpose** - Political affiliation.
|
|
/// **Effect** - Determines diplomatic relations, war status,
|
|
/// and access to empire-wide bonuses.
|
|
/// **Source** - `faction = current_faction_uuid`.
|
|
pub faction: FactionId,
|
|
|
|
/// UIDs of all entities the entity is linked to (roads, trade routes,
|
|
/// alliances, war declarations, etc.).
|
|
///
|
|
/// **Purpose** - Connectivity network.
|
|
/// **Effect** - Influences economic, military, and diplomatic
|
|
/// interactions.
|
|
/// **Source** - `links = Vec<Uuid>` collected from the entity's
|
|
/// network manager.
|
|
pub links: Vec<TownId>,
|
|
|
|
/// Prestige / reputation of the entity in the eyes of the empire
|
|
/// and foreign powers.
|
|
///
|
|
/// **Purpose** - Social standing metric.
|
|
/// **Effect** - Affects diplomatic influence, trade bonuses,
|
|
/// and event outcomes.
|
|
/// **Source** - `prestige = calculate_prestige(...)`.
|
|
pub prestige: usize,
|
|
}
|
|
|
|
/// A generic stat pair with (stat, value), used mainly for clap
|
|
/// Accepts two forms
|
|
/// 1. "cri 10" (two separate tokens)
|
|
/// 2. "cri:10" (one token with a separator)
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
pub struct StatPair {
|
|
/// The stat selected
|
|
pub stat: ListStats,
|
|
/// The value of the modifier
|
|
pub value: GenericStat,
|
|
}
|
|
|
|
/// Structure used to indicate position, possess nice helper methods to use as is in the program
|
|
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
|
pub struct Position(isize, isize);
|
|
|
|
impl Position {
|
|
/// The euclidian distance between two points
|
|
fn distance(&self, other: &Self) -> isize {
|
|
((self.0 - other.0).pow(2) + (self.1 * other.1).pow(2)).isqrt()
|
|
}
|
|
|
|
/// The position in grid coordinates
|
|
fn to_grid_distance(&self) -> (isize, isize) {
|
|
(self.0 / 200, self.1 / 200)
|
|
}
|
|
}
|
|
/// A summary of the stats, only for display purposes
|
|
#[allow(clippy::missing_docs_in_private_items)]
|
|
#[derive(Table)]
|
|
pub struct SummaryStats {
|
|
#[table(title = "Demo")]
|
|
demographics: GenericStat,
|
|
#[table(title = "Eco")]
|
|
economy: GenericStat,
|
|
// #[table(title = "Social")]
|
|
// social: GenericStat,
|
|
#[table(title = "Milit")]
|
|
military: GenericStat,
|
|
#[table(title = "Infra")]
|
|
infrastructure: GenericStat,
|
|
}
|
|
|
|
/// Bridge between the CLI and the statistics logic.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
|
#[allow(missing_docs)]
|
|
pub enum ListStats {
|
|
Demographics,
|
|
Population,
|
|
Growthrate,
|
|
Crime,
|
|
Happiness,
|
|
Economy,
|
|
Food,
|
|
Industry,
|
|
Science,
|
|
Trade,
|
|
Social,
|
|
Culture,
|
|
Education,
|
|
Tourism,
|
|
Influence,
|
|
Military,
|
|
Army,
|
|
Strength,
|
|
Fortification,
|
|
Threat,
|
|
Infrastructure,
|
|
Bureaucracy,
|
|
Transportation,
|
|
Sprawl,
|
|
Health,
|
|
}
|
|
|
|
/// The list of all types of entities
|
|
#[allow(missing_docs)]
|
|
#[derive(Serialize, Deserialize)]
|
|
pub enum EntityType {
|
|
Character,
|
|
Player,
|
|
Town,
|
|
Monster,
|
|
Blocker,
|
|
Event,
|
|
}
|
|
|
|
// A stat that is shown to the player *and* can be modified manually.
|
|
thin_newtype!(GenericStat, isize);
|
|
thin_newtype!(TownId, usize);
|
|
thin_newtype!(CharacterId, usize);
|
|
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
|
|
/// 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)
|
|
}
|
|
|
|
/// Convert the raw integer to a 10-point scale.
|
|
fn to_10(&self) -> isize {
|
|
self.to_50() / 5
|
|
}
|
|
|
|
/// As a colored delta (when the stat is used as a delta)
|
|
fn to_delta(&self) -> String {
|
|
let get_value = self.get_value();
|
|
if get_value < 0 {
|
|
format!("{}", get_value.to_string().red())
|
|
} else {
|
|
format!("{}", get_value.to_string().green())
|
|
}
|
|
}
|
|
|
|
/// Return the raw integer value, always bound to 0-70
|
|
fn get_value(&self) -> isize;
|
|
|
|
/// Return the raw integer value, always bound to 0-70
|
|
fn change_value(&mut self, value: isize);
|
|
|
|
/// Create a Gamestat from it's underlying value
|
|
fn from_value(value: isize) -> Self
|
|
where
|
|
Self: Sized;
|
|
}
|
|
|
|
/// Trait for objects that can expose a stat via a string key.
|
|
/// The trait returns a *boxed* trait object so callers do not need to know
|
|
/// the concrete type that was stored.
|
|
pub trait Accessible {
|
|
/// Return the requested stat as a `Box<dyn GameStat>`.
|
|
/// `None` if the key does not exist.
|
|
fn get_val(&self, key: &str) -> Option<Box<dyn GameStat>>;
|
|
}
|
|
|
|
// pub trait Displayable {
|
|
// fn summary(&self) -> String;
|
|
// fn full_description(&self) -> String;
|
|
// }
|