//! Autonaming generator //! Supposed to be loaded with the world if needed use once_cell::sync::Lazy; use rand::prelude::*; use serde::{Deserialize, Serialize}; use std::{fs, io, path::Path}; use crate::Displayable; use crate::entity::{EffectApplication, EffectBounds, EntityDuration}; use crate::error::EpochError; use crate::stats::{EntityType, StatPair, Symbols}; /// The structure that holds everything we need for name generation. #[derive(Debug, Serialize, Deserialize, Default)] pub struct NamingData { /// First name for characters pub first_names: Vec, /// Last names for characters pub last_names: Vec, /// Good prefixes for towns pub town_prefixes: Vec, /// Good suffixes for town names pub town_suffixes: Vec, /// Good blocker prefixes pub blocker_prefixes: Vec, /// Good blocker suffixes pub blocker_suffixes: Vec, /// Character adjectives pub character_adjectives: Vec, /// Name prefixes pub character_prefixes: Vec, // Exotics names /// Exotic name prefixes pub exotic_prefixes: Vec, /// Exotic infixes pub exotic_infixes: Vec, /// Exotic suffixes pub exotic_suffixes: Vec, /// Mighty mystical adjectives pub mystical_adjectives: Vec, /// A list of event ideas and characteristic associated to it pub event_ideas: Vec, } #[derive(Debug, Serialize, Deserialize)] /// An event with a description pub struct EventDescription { /// A short and meaninful name (an id of a sort) pub name: String, /// A short description of the event pub description: String, /// The stats affected by the event, and how much (-20 to +20) /// (100 being the maximum of a stat, event a change of -10 is meaningful) pub stats: Vec, /// The nature of the event duration pub duration: EntityDuration, /// How the event will be (re)applied pub application: EffectApplication, /// The maximum bounds of the event pub effect_bounds: EffectBounds, } impl Displayable for EventDescription { fn oneline_display(&self) -> String { let (description, _) = self.description.split_at(110.min(self.description.len())); let line1 = format!( "├─ {} {} ──────> {}{} \n\ │ ├─ {}", self.name, EntityType::Event.to_symbol(), self.duration.to_symbol(), self.effect_bounds.to_symbol(), description, ); let mut line2 = "│ └─ Stats: ".to_string(); for effect in &self.stats { line2.push_str(&format!("{}:{} ", effect.stat.to_shortest(), effect.value,)); } format!("{line1}\n{line2}") } } impl NamingData { /// Load the data from the supplied path. /// If the file does **not** exist, a default (embedded) version is written /// to that path and returned. pub fn load_or_create>(path: P) -> io::Result { let path = path.as_ref(); if path.exists() { // File exists → read & parse let contents = fs::read_to_string(path)?; let data: Self = serde_json::from_str(&contents)?; Ok(data) } else { // File does *not* exist → create from embedded default let default = serde_json::from_str(DEFAULT_JSON_STR).expect("Default JSON is malformed"); // Ensure parent dirs exist if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } let json = serde_json::to_string_pretty(&default)?; fs::write(path, json)?; Ok(default) } } /// Generate a random **character** name. pub fn generate_character_name(&self) -> String { let mut rng = rand::rng(); let binding = "Bobman".into(); let first = self.first_names.choose(&mut rng).unwrap_or(&binding); let binding = "McBobintown".into(); let last = self.last_names.choose(&mut rng).unwrap_or(&binding); format!("{} {}", first, last).trim().to_string() } /// Generate a random **town** name. pub fn generate_town_name(&self) -> String { let mut rng = rand::rng(); let binding = "Bobtown".into(); let prefix = self.town_prefixes.choose(&mut rng).unwrap_or(&binding); let suffix = self.town_suffixes.choose(&mut rng).unwrap_or(&binding); format!("{}{}", prefix, suffix).trim().to_string() } /// Pick a random event idea #[allow(clippy::unwrap_used)] pub fn random_event_idea(&self) -> Result<&EventDescription, EpochError> { let mut rng = rand::rng(); let event_desc = self .event_ideas .choose(&mut rng) .ok_or(EpochError::RNGPickError { cause: "Picking a random event".into(), help: None, })?; // let mut e = Entity::default(); // e.name = event_desc.name.clone(); // e.change_description(event_desc.description.clone()); Ok(event_desc) } /// Pick a random event name #[allow(clippy::unwrap_used)] pub fn random_event_name(&self) -> String { if let Ok(event) = self.random_event_idea() { event.name.clone() } else { "The Great Bobbening".to_owned() } } /// Generate a random **blocker** name (e.g. “Stone-Gate”, “Witch-Wall”). /// /// The name is formed by choosing a random prefix *and* suffix from the /// corresponding lists. If either list is empty, a sensible default is /// returned. pub fn generate_blocker_name(&self) -> String { let mut rng = rand::rng(); let binding = "Mystic ".to_string(); let prefix = self.blocker_prefixes.choose(&mut rng).unwrap_or(&binding); let binding = "Barrier".to_string(); let suffix = self.blocker_suffixes.choose(&mut rng).unwrap_or(&binding); format!("{} {}", prefix, suffix).trim().to_string() } /// Generate a *calamity* name. /// /// A calamity is a **complex exotic** word (prefix + 2-4 infixes + optional suffix) /// followed by a *mystical* adjective. /// /// Example output: “Umbral-Shatterfall Cataclysmic” pub fn generate_calamity_name(&self) -> String { let mut rng = rand::rng(); /* ----- 1️⃣ Build the exotic base --------------------------------- */ // Pick a prefix (or fall back to "Umbral") let prefix = self .exotic_prefixes .choose(&mut rng) .unwrap_or(&"Umbral".to_string()) .clone(); // Pick 2-4 infixes (this gives the “complex” feel) let infix_count = rng.random_range(2..=4); let infixes: String = (0..infix_count) .map(|_| { self.exotic_infixes .choose(&mut rng) .expect("exotic_infixes must not be empty") .clone() }) .collect(); // Optional suffix - if you don't have a list, this will be an empty string let suffix = self .exotic_suffixes .choose(&mut rng) .cloned() .unwrap_or_else(String::new); // Combine into the base calamity word let base = format!("{}{}{}", prefix, infixes, suffix); /* ----- 2️⃣ Append a mystical adjective --------------------------- */ let adjective = self .mystical_adjectives .choose(&mut rng) .unwrap_or(&"Cataclysmic".to_string()) .clone(); format!("{} {}", base, adjective).trim().to_string() } /// Generates something like: /// “The Magnificent Sir Aurelius Blackthorn the Swift” /// Random adjective, prefix, base name and suffix are all optional. /// If a list is empty, that part is omitted. pub fn generate_long_character_name(&self) -> String { let mut rng = rand::rng(); // Helper: get a random element or None let adjective = self.character_adjectives.choose(&mut rng).cloned(); let prefix = self.character_prefixes.choose(&mut rng).cloned(); // Base name (first + last) let base = self.generate_character_name(); // Assemble pieces let mut parts = Vec::new(); if let Some(pre) = prefix && rand::random_bool(0.3) { parts.push(pre); } parts.push(base); if let Some(adj) = adjective && rand::random_bool(0.3) { parts.push(adj); } parts.join(" ") } /// Generate a exotic character name #[allow(clippy::unwrap_used)] pub fn generate_exotic_character_name(&self) -> String { let mut rng = rand::rng(); // Pick a random number of syllables for the *first* part let first_len = rng.random_range(2..=4); let pref: &String = self.exotic_prefixes.choose(&mut rng).unwrap(); let pref2: &String = self.exotic_prefixes.choose(&mut rng).unwrap(); let first: String = (0..first_len) .map(|_| self.exotic_infixes.choose(&mut rng).unwrap()) .cloned() .collect(); // Same for the *last* part let last_len = rng.random_range(1..=3); let last: String = (0..last_len) .map(|_| self.exotic_infixes.choose(&mut rng).unwrap()) .cloned() .collect(); // Combine with a space - you could also use a hyphen or nothing format!("{pref}{first} {pref2}{last}") } } // /// Helper to capitalize the first letter of a word // fn capitalize(word: &str) -> String { // let mut chars = word.chars(); // match chars.next() { // None => String::new(), // Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(), // } // } /// The JSON that ships with the binary. /// `include_str!` pulls the file at compile time. const DEFAULT_JSON_STR: &str = include_str!("../naming.json"); /// Global naming data loaded from the JSON embedded in the binary. /// /// Generating a name is deliberately read-only and never creates files in the /// user's world repository. pub static NAMING: Lazy = Lazy::new(|| { serde_json::from_str(DEFAULT_JSON_STR).expect("embedded naming data must be valid") }); #[cfg(test)] mod tests { use super::*; use crate::stats::ListStats; use std::collections::HashMap; #[test] fn try_load() {} #[test] fn basic_testing() { // 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 character = NAMING.generate_long_character_name(); println!("Event idea: {}", character); let _ = NAMING.random_event_idea(); } #[test] // TODO[Work]: Add this to a recap function fn test_all_events() { let mut values: HashMap = HashMap::new(); for event in &NAMING.event_ideas { println!("Testing event: {:?}", event); assert!(event.stats.len() > 1); for stat in &event.stats { if let s @ (ListStats::Demographics | ListStats::Military | ListStats::Economy | ListStats::Social | ListStats::Infrastructure) = stat.stat { panic!("Bad stat used {s:?}") }; match stat.value.abs() { 0..5 => (), 5..10 => (), 10..20 => println!("Big stat"), s => panic!("The event has a stat that is way too big {s}"), } let base_value = values.get(&stat.stat).unwrap_or(&0); values.insert(stat.stat, base_value + 1); } } println!("{values:#?}"); // panic!() } #[test] fn test_most_naming() { let _ = NAMING.generate_character_name(); let _ = NAMING.generate_town_name(); let _ = NAMING.random_event_idea().expect("Couldn't generate event"); let _ = NAMING.random_event_name(); let _ = NAMING.generate_blocker_name(); let _ = NAMING.generate_calamity_name(); let _ = NAMING.generate_long_character_name(); let _ = NAMING.generate_exotic_character_name(); } #[test] fn event_description() { let event = NAMING.random_event_idea().expect("Generating event"); let _ = event.oneline_display(); } }