epoch_forge/lib_efo/src/naming.rs

218 lines
6.9 KiB
Rust

//! 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;
use std::io;
use std::path::{Path, PathBuf};
use crate::entity::EffectApplication;
use crate::entity::EffectBounds;
use crate::entity::EntityDuration;
use crate::stats::StatPair;
/// 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<String>,
/// Last names for characters
pub last_names: Vec<String>,
/// Good prefixes for towns
pub town_prefixes: Vec<String>,
/// Good suffixes for town names
pub town_suffixes: Vec<String>,
/// Character adjectives
pub character_adjectives: Vec<String>,
/// Name prefixes
pub character_prefixes: Vec<String>,
/// A list of event ideas and characteristic associated to it
pub event_ideas: Vec<EventDescription>,
}
#[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<StatPair>,
/// 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 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<P: AsRef<Path>>(path: P) -> io::Result<Self> {
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 = "Unnamed".into();
let first = self.first_names.choose(&mut rng).unwrap_or(&binding);
let binding = "".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 = "".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 (you can reuse this or make a dedicated method).
#[allow(clippy::unwrap_used)]
pub fn random_event_idea(&self) -> &EventDescription {
let mut rng = rand::rng();
self.event_ideas.choose(&mut rng).unwrap()
}
/// 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(" ")
}
}
/// The JSON that ships with the binary.
/// `include_str!` pulls the file at compile time.
const DEFAULT_JSON_STR: &str = include_str!("../naming.json");
/// Helper that determines the *runtime* location of the `naming.json` file.
fn naming_file_path() -> PathBuf {
PathBuf::from("naming.json")
}
/// Global instance that is lazily initialised on first use.
pub static NAMING: Lazy<NamingData> = Lazy::new(|| {
let path = naming_file_path();
NamingData::load_or_create(path).expect("Failed to load naming data")
});
#[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<ListStats, usize> = 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!()
}
}