Random add & update position
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2025-12-14 18:46:58 +01:00
parent f05a6184f0
commit 96915dbc71
7 changed files with 204 additions and 30 deletions

View File

@ -11,6 +11,6 @@ serde_json = "1.0.145"
miette = { version = "7.6.0", features = ["fancy"] }
env_logger = "0.11.8"
log = "0.4.28"
derive_more = { version = "2.0.1", features = ["display", "add"] }
derive_more = { version = "2.0.1", features = ["display", "add", "mul"] }
colored = "3.0.0"
insta = "1.44.3"

View File

@ -75,7 +75,7 @@ use lib_efo::{
epoch_traits::{ConfigWritable, Diffable},
},
error::EpochError,
stats::{EntityType, FactionId, Position, StatPair, Symbols},
stats::{EntityType, FactionId, Position, PositionGrid, StatPair, Symbols},
utils::RngLevel,
};
use log::info;
@ -201,7 +201,7 @@ pub struct EditArgs {
/// Update the entity’s position using the map rules.
#[arg(long, short = 'p', group = "position")]
pub pos: Option<Position>,
pub pos: Option<PositionGrid>,
/// New duration for the entity.
#[arg(long, short)]
@ -402,9 +402,8 @@ fn handle_edit_entity(
Some(entity_args.identifier.clone()),
))?;
for stat in &entity_args.stats {
entity.change_stat(stat.clone());
}
helper_functions::update_stats(&entity_args.stats, entity_args.delta, entity);
if let Some(duration) = &entity_args.duration {
entity.modify_duration(duration.clone());
}
@ -417,6 +416,11 @@ fn handle_edit_entity(
if let Some(bounds) = &entity_args.bounds {
entity.modify_effect_bounds(bounds.clone());
}
if let Some(pos) = &entity_args.pos_exact {
entity.modify_position(pos.clone());
} else if let Some(pos) = &entity_args.pos {
entity.modify_position_grid(pos.clone());
}
entity.print_full();
let message = &crate::success::SuccessMessages::EditedEntity(

View File

@ -11,14 +11,8 @@ use crate::commands::entity_generic::AddArgs;
/// Update the given stats with the given argumenbts
/// Note that this function will not change name & id due to the usage variance between caller
pub(crate) fn update_stats(pair_list: &Vec<StatPair>, is_a_delta: bool, e: &mut Entity) {
if is_a_delta {
for stat in pair_list {
e.delta_stat(stat.clone());
}
} else {
for stat in pair_list {
e.change_stat(stat.clone());
}
for stat in pair_list {
e.change_stat_fuzzy(stat.clone(), is_a_delta);
}
}

View File

@ -4,12 +4,16 @@ use cli_table::format::{Border, HorizontalLine, Separator, VerticalLine};
use cli_table::{Style, WithTitle};
use colored::*;
use rand::distr::Distribution;
use rand::seq::{IndexedRandom, IteratorRandom};
use uuid::Uuid; // [3] - colored-rs examples
use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration};
use crate::epoch::epoch_traits::Diffable;
use crate::error::EpochError;
use crate::stats::{EntityType, GenericStat, MetaStats, OverallStats, Position, StatPair, Symbols};
use crate::stats::{
EntityType, GenericStat, ListStats, MetaStats, OverallStats, Position, PositionGrid, StatPair,
Symbols,
};
use crate::utils::RngLevel;
use crate::{Displayable, items_table};
@ -261,10 +265,87 @@ impl Entity {
/// # Arguments
/// * `pair` - The stat pair containing the key and new value.
///
pub fn change_stat(&mut self, pair: StatPair) {
pub fn change_stat_strict(&mut self, pair: StatPair) {
overwrite_stat(&mut self.stats, pair);
}
/// Mutate a statistic in a “fuzzy” way.
///
/// This method behaves like `change_stat_strict` for ordinary stats, but
/// for *meta‑stats* it applies a random modification instead of an
/// outright overwrite.
///
/// # Parameters
/// * `pair` – a `StatPair` that contains the target statistic and the
/// value that should be used for the fuzzy change.
pub fn change_stat_fuzzy(&mut self, pair: StatPair, delta: bool) {
let stats_demo = [
ListStats::Population,
ListStats::Growthrate,
ListStats::Crime,
ListStats::Happiness,
];
let stats_eco = [
ListStats::Food,
ListStats::Industry,
ListStats::Science,
ListStats::Trade,
];
let stats_soc = [
ListStats::Culture,
ListStats::Education,
ListStats::Tourism,
ListStats::Influence,
];
let stats_mil = [
ListStats::Army,
ListStats::Strength,
ListStats::Fortification,
ListStats::Threat,
];
let stats_inf = [
ListStats::Bureaucracy,
ListStats::Transportation,
ListStats::Sprawl,
ListStats::Health,
];
match pair.stat {
ListStats::Demographics => self.change_random_stats_by(&stats_demo, pair.value, delta),
ListStats::Economy => self.change_random_stats_by(&stats_eco, pair.value, delta),
ListStats::Social => self.change_random_stats_by(&stats_soc, pair.value, delta),
ListStats::Military => self.change_random_stats_by(&stats_mil, pair.value, delta),
ListStats::Infrastructure => self.change_random_stats_by(&stats_inf, pair.value, delta),
_ => self.change_stat_strict(pair),
}
}
/// Mutates a statistic in a “fuzzy” manner.
///
/// For ordinary statistics this behaves like `change_stat_strict` and
/// simply assigns the supplied value. For *meta‑stats* the function
/// chooses a random subset of the associated sub‑statistics and
/// distributes the requested change evenly among them. The selection
/// is performed using a thread‑local RNG.
fn change_random_stats_by(
&mut self,
stats_demo: &[ListStats],
amount: GenericStat,
delta: bool,
) {
let mut r = rand::rng();
let nb = (1..stats_demo.len()).choose(&mut r).unwrap_or(1);
let stats = stats_demo.choose_multiple(&mut r, nb);
let value = GenericStat(*amount / (nb as isize));
stats.for_each(|stat| {
if delta {
self.delta_stat(StatPair { stat: *stat, value });
} else {
self.change_stat_strict(StatPair { stat: *stat, value })
}
});
}
/// Change the entity's duration.
///
/// This simply replaces the current `EntityDuration` with the one supplied.
@ -328,6 +409,22 @@ impl Entity {
pub fn modify_effect_bounds(&mut self, effect: EffectBounds) {
self.effect_bounds = effect
}
/// Sets the entity’s position using a world‑space `Position`.
///
/// This method updates the internal metadata to the specified
/// world coordinates.
pub fn modify_position(&mut self, pos: Position) {
self.metadata.position = pos;
}
/// Sets the entity’s position using a grid‑space `PositionGrid`.
///
/// The supplied grid coordinates are converted to world space
/// before being stored.
pub fn modify_position_grid(&mut self, pos: PositionGrid) {
self.metadata.position = pos.to_position();
}
}
// impl Entity {

View File

@ -334,7 +334,7 @@ fn snapshot_overwrite_stat() {
let mut entity = Entity::default();
let stats = OverallStats::linear(0);
entity.stats = stats;
entity.change_stat(StatPair {
entity.change_stat_strict(StatPair {
stat: stats::ListStats::Population,
value: stats::GenericStat(33),
});

View File

@ -14,7 +14,7 @@
use crate::{error::EpochError, thin_newtype, utils::RngLevel};
use cli_table::{CellStruct, Color, Style, Table};
use colored::Colorize;
use derive_more::{Add, Display, Sub};
use derive_more::{Add, Display, Mul, Sub};
use rand::{Rng, distr::Distribution, rngs::ThreadRng};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@ -421,35 +421,82 @@ pub struct StatPair {
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, Add, Sub)]
/// A two‑dimensional point on the world map.
///
/// The struct is a thin wrapper around a pair of `isize` values
/// representing the X and Y coordinates.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Add, Sub, Mul)]
pub struct Position(isize, isize);
/// The grid size, as a static like a degenerate
/// A grid‑aligned position used for chunk look‑ups.
///
/// A `PositionGrid` stores the coordinates of a chunk in the world
/// grid. Each component is the index of the chunk in the X and Y
/// direction.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Add, Sub, Mul)]
pub struct PositionGrid(isize, isize);
/// The size of the whole world in pixels.
///
/// These constants are internal to the module; they are not part
/// of the public API.
// TODO(9): Change to be at least initialized with the world ?
const GRID_SIZE: (i32, i32) = (1920, 1080);
/// The size the map is divided into
/// The size of one world chunk in pixels.
const CHUNK_SIZE: isize = 200;
impl Position {
/// The euclidian distance between two points
fn distance(&self, other: &Self) -> isize {
/// Calculates the Euclidean distance between two points.
///
/// The distance is computed in the 2‑D Euclidean space.
pub 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 / CHUNK_SIZE, self.1 / CHUNK_SIZE)
/// Converts this point to its corresponding grid position.
///
/// The conversion divides the world coordinates by the
/// `CHUNK_SIZE` to obtain the chunk indices.
pub fn to_grid_distance(&self) -> PositionGrid {
PositionGrid(self.0 / CHUNK_SIZE, self.1 / CHUNK_SIZE)
}
/// Create a random position
/// None that there is no concept to either city or continent making this position rather unrelyable
/// Returns the inner tuple representation of the position.
///
/// This is a convenience method to obtain the raw `(isize, isize)`
/// coordinates without wrapping them in the struct.
pub fn to_inner(&self) -> (isize, isize) {
(self.0, self.1)
}
/// Generates a random position within the world bounds.
///
/// The position is chosen uniformly at random using the supplied
/// random number generator.
pub fn create_rng(r: &mut ThreadRng) -> Result<Self, EpochError> {
let x = r.random_range(0..GRID_SIZE.0);
let y = r.random_range(0..GRID_SIZE.1);
Ok(Self(x as isize, y as isize))
}
}
impl PositionGrid {
/// Calculates the Euclidean distance between two grid positions.
///
/// The distance is computed by converting both grid positions to
/// world coordinates and then using `Position::distance`.
pub fn distance(&self, other: &PositionGrid) -> isize {
self.to_position().distance(&other.to_position())
}
/// Converts the grid coordinates to world coordinates.
///
/// Each component is multiplied by `CHUNK_SIZE` to obtain the
/// corresponding world position.
pub fn to_position(&self) -> Position {
Position(CHUNK_SIZE * self.0, CHUNK_SIZE * self.1)
}
}
/// A summary of the stats, only for display purposes
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Table)]

View File

@ -2,7 +2,7 @@
use crate::{
error::EpochError,
stats::{self, ListStats, Position, StatPair},
stats::{self, ListStats, Position, PositionGrid, StatPair},
};
use std::str::FromStr;
@ -68,6 +68,38 @@ impl std::str::FromStr for Position {
}
}
/// Parse a string into a `PositionGrid`.
///
/// The string is expected to contain two signed integers separated by a comma,
/// optionally surrounded by whitespace. Each component is trimmed before
/// parsing, so leading and trailing whitespace is ignored.
///
/// The parsing logic is the same as for `Position`:
/// * Split on the comma; there must be exactly one comma.
/// * Trim each component and parse it as an `isize`.
/// * Convert the resulting `Position` to a grid distance with
/// `Position::to_grid_distance`.
///
/// # Errors
///
/// * `EpochError::InvalidPositionFormat` – the string does not contain
/// exactly one comma or there are not exactly two components.
/// * `EpochError::ParsePositionError` – one of the components cannot be
/// parsed as an `isize`. (These errors come from the underlying `Position`
/// implementation.)
impl std::str::FromStr for PositionGrid {
type Err = EpochError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse::<Position>().map(|p| PositionGrid(p.0, p.1))
}
}
/// Convert a tuple of two signed integers into a `Position`.
///
/// This implementation simply wraps the `(isize, isize)` tuple into a
/// `Position` struct. It is equivalent to `Position(x, y)` where `x` is the
/// first element and `y` is the second.
impl From<(isize, isize)> for Position {
fn from(value: (isize, isize)) -> Self {
Self(value.0, value.1)