292 lines
9.2 KiB
Rust
292 lines
9.2 KiB
Rust
//! Autonaming generator
|
|
//! Supposed to be loaded with the world if needed
|
|
use crate::stats::Symbols;
|
|
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::Displayable;
|
|
use crate::entity::EffectApplication;
|
|
use crate::entity::EffectBounds;
|
|
use crate::entity::EntityDuration;
|
|
use crate::error::EpochError;
|
|
use crate::stats::EntityType;
|
|
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>,
|
|
|
|
// Exotics names
|
|
/// Exotic name prefixes
|
|
pub exotic_prefixes: Vec<String>,
|
|
/// Exotic infixes
|
|
pub exotic_infixes: Vec<String>,
|
|
/// Exotic suffixes
|
|
pub exotic_suffixes: 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 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<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 = "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();
|
|
self.event_ideas
|
|
.choose(&mut rng)
|
|
.ok_or(EpochError::RNGPickError {
|
|
cause: "Picking a random event".into(),
|
|
help: None,
|
|
})
|
|
}
|
|
|
|
/// 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}{} {pref2}{}", &first, &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");
|
|
|
|
/// 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!()
|
|
}
|
|
}
|