Adds generic entities

This commit is contained in:
Dandaedre 2025-11-30 14:56:10 +01:00
parent 087425f4e8
commit 45d2cc495c
5 changed files with 144 additions and 55 deletions

19
lib_efo/src/entity.rs Normal file
View File

@ -0,0 +1,19 @@
//! All the structs and logic surrounding entities
//!
//!
use serde::{Deserialize, Serialize};
use crate::stats::{EntityType, MetaStats, OverallStats};
/// Fundamentaly everything is an entity, this can be error prone but the reduction of code duplication makes it worth it right now
/// Traits and thin structs could solve this but this will be added later and will be greatly simplified by the existence of the sub structs holding all the logic
#[derive(Serialize, Deserialize)]
pub struct Entity {
/// The stats of the entity, holding all the logic
stats: OverallStats,
/// Meta information
metadata: MetaStats,
/// Enum listing all entity types, this is bound to disapear in favor Typed Etities lateer
entity_type: EntityType,
}

View File

@ -20,11 +20,11 @@
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
#![deny(clippy::unwrap_used)]
pub mod epoch;
pub mod stats;
pub mod town;
#[macro_use]
pub mod error;
pub mod entity;
pub mod epoch;
pub mod stats;
pub mod utils;
use std::io::Result as IoResult;

View File

@ -16,7 +16,8 @@ use cli_table::Table;
use colored::Colorize;
use derive_more::Display;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::thin_newtype;
mod implementations;
/// Aggregated statistics for a single entity.
@ -27,7 +28,7 @@ mod implementations;
// Derive more
#[derive(Table)]
// #[derive(Add, Sub)]
struct OverallStats {
pub struct OverallStats {
// ──────────────────────── Demographics ────────────────────────
/// Total economic health of the entity.
///
@ -211,8 +212,8 @@ struct OverallStats {
///
/// All fields are intentionally simple – the logic that interprets them
/// lives in separate modules (e.g. `map`, `network`, `governance`).
#[derive(Debug, Clone, Default)]
pub struct Strategics {
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MetaStats {
// ──── Location & Spatial Data (hidden) ───────────────────────────────
/// Cartesian coordinates of the entity on the world map.
///
@ -220,31 +221,26 @@ pub struct Strategics {
/// **Effect** – Used for distance calculations, visibility, and
/// map‑based event logic.
/// **Source** – Supplied by the map generator.
pub position: (usize, usize),
pub position: Position,
/// Euclidean distance to the empire’s capital (in tile units).
///
/// **Purpose** – Metric of remoteness from the political centre.
/// **Effect** – Influences trade costs, supply‑line strength,
/// and the range of early‑warning signals.
/// **Source** – `distance_to_capital = dist(position, capital_position)`.
pub distance_to_capital: usize,
/// 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>,
// /// 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,
// /// 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.
@ -253,23 +249,22 @@ pub struct Strategics {
/// **Effect** – Adds personal bonuses and may modify policies
/// or diplomatic stance.
/// **Source** – `governor = selected_leader_uuid`.
pub governor: Uuid,
/// 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,
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: Uuid,
pub faction: FactionId,
/// UIDs of all entities the entity is linked to (roads, trade routes,
/// alliances, war declarations, etc.).
@ -279,7 +274,7 @@ pub struct Strategics {
/// interactions.
/// **Source** – `links = Vec<Uuid>` collected from the entity’s
/// network manager.
pub links: Vec<Uuid>,
pub links: Vec<TownId>,
/// Prestige / reputation of the entity in the eyes of the empire
/// and foreign powers.
@ -291,6 +286,21 @@ pub struct Strategics {
pub prestige: usize,
}
/// 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)]
@ -338,19 +348,31 @@ pub enum ListStats {
Health,
}
// fn print_generic_stat()
/// A stat that is shown to the player *and* can be modified manually.
/// The list of all types of entities
#[allow(missing_docs)]
#[derive(Debug, Clone, Default, Serialize, Deserialize, Display)]
pub struct GenericStat {
pub value: isize,
#[derive(Serialize, Deserialize)]
pub enum EntityType {
Character,
Player,
Town,
Monster,
Blocker,
Event,
}
/// --- TRAITS ---------------------------------------------------------------
// 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 {

View File

@ -9,6 +9,55 @@ use crate::stats::GenericStat;
use crate::stats::ListStats;
use crate::stats::OverallStats;
/// Creates a thin, deref‑able wrapper around an inner type.
#[macro_export]
macro_rules! thin_newtype {
($name:ident, $inner:ty) => {
/// Thin wrapper that derefs to the inner type.
/// Ideal for zero‑overhead new‑type patterns.
#[repr(transparent)]
#[derive(
Debug,
Clone,
Default,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
Serialize,
Deserialize,
Display,
)]
pub struct $name(pub $inner);
impl std::ops::Deref for $name {
type Target = $inner;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<$inner> for $name {
fn from(v: $inner) -> Self {
$name(v)
}
}
impl From<$name> for $inner {
fn from(v: $name) -> Self {
v.0
}
}
};
}
/// Generates an `impl GameStat for <TYPE>` where the only difference between
/// multiple implementations is the visibility level.
///
@ -19,18 +68,18 @@ macro_rules! impl_game_stat {
($type:ident) => {
impl GameStat for $type {
fn get_value(&self) -> isize {
self.value
self.0
}
fn change_value(&mut self, value: isize) {
self.value = value;
self.0 = value;
}
fn from_value(value: isize) -> Self
where
Self: Sized,
{
Self { value }
Self(value)
}
}
};
@ -181,7 +230,7 @@ impl FromStr for StatPair {
let value: isize = val_str
.parse()
.map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?;
Ok(StatPair(stat, stats::GenericStat { value }))
Ok(StatPair(stat, stats::GenericStat(value)))
}
}
@ -210,9 +259,9 @@ pub(crate) mod test {
#[test]
fn test_field_accessors() {
let person = Person {
name: GenericStat { value: 10 },
age: GenericStat { value: 20 },
email: GenericStat { value: 70 },
name: GenericStat(10),
age: GenericStat(20),
email: GenericStat(70),
};
let name = person.get_field("name").unwrap();
let email = person.get_field("email").unwrap();
@ -228,7 +277,7 @@ pub(crate) mod test {
fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) {
let pair = StatPair::from_str(input).expect("should parse");
assert_eq!(pair.0, expected_stat, "stat mismatch");
assert_eq!(pair.1.value, expected_val, "value mismatch");
assert_eq!(pair.1.0, expected_val, "value mismatch");
}
#[test]
fn test_stat_pair_parsing() {

View File

@ -1 +0,0 @@
//! All the structs and logic surrounding towns