Work on 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 19:55:44 +01:00
parent 96915dbc71
commit 9a6c3ff058
8 changed files with 143 additions and 26 deletions

View File

@ -75,7 +75,7 @@ use lib_efo::{
epoch_traits::{ConfigWritable, Diffable},
},
error::EpochError,
stats::{EntityType, FactionId, Position, PositionGrid, StatPair, Symbols},
stats::{EntityType, FactionId, Position, PositionGrid, PositionIdentifier, StatPair, Symbols},
utils::RngLevel,
};
use log::info;
@ -151,17 +151,30 @@ pub struct AddArgs {
/// How to initialise *missing* stats. See the `--rng` option
/// description for the valid values.
#[arg(value_enum, long, short, default_value_t = RngLevel::Zero)]
#[arg(value_enum, long, short, default_value_t = RngLevel::Med)]
pub rng: RngLevel,
/// Place the new entity at an exact position – this ignores
/// any map‑specific coordinate transformations.
#[arg(long, short = 'P', group = "position")]
pub pos_exact: Option<Position>,
// /// Place the new entity at an exact position – this ignores
// /// any map‑specific coordinate transformations.
// #[arg(long, short = 'P', group = "position")]
// pub pos_exact: Option<Position>,
/// Place the new entity using the map’s position rules.
#[arg(long, short = 'p', group = "position")]
pub pos: Option<Position>,
// /// Place the new entity using the map’s position rules.
// #[arg(long, short = 'p', group = "position")]
// pub pos: Option<Position>,
// /// Update the position with an entity position
// ///
// /// Note that if a name is supplied instead of a tag, only towns will be looked over
// #[arg(long, short = 'e', group = "position")]
// pub entity_position: Option<EntityIdentifier>,
/// A position Identifier, either a grid position, and exact position or a tag
#[arg(short, long)]
pub position: PositionIdentifier,
/// Updates the reach of the entity
#[arg(long, short = 'R')]
pub reach: Option<String>,
/// Lifespan of the entity – see the `--duration` description.
#[arg(long, short)]
@ -173,7 +186,7 @@ pub struct AddArgs {
pub bounds: Option<EffectBounds>,
/// How the effect is applied – see the `--effect` description.
#[arg(long, short)]
#[arg(long, short = 'a')]
pub effect: Option<EffectApplication>,
/// One or more `key:value` pairs that set the entity’s stats.
@ -203,6 +216,16 @@ pub struct EditArgs {
#[arg(long, short = 'p', group = "position")]
pub pos: Option<PositionGrid>,
/// Update the position with an entity position
///
/// Note that if a name is supplied instead of a tag, only towns will be looked over
#[arg(long, short = 'e', group = "position")]
pub entity_position: Option<EntityIdentifier>,
/// Updates the reach of the entity
#[arg(long, short = 'R')]
pub reach: Option<String>,
/// New duration for the entity.
#[arg(long, short)]
pub duration: Option<EntityDuration>,
@ -273,15 +296,12 @@ pub(crate) fn handle_create_entity(
Err(EpochError::EntityAlreadyExist(ident))?;
};
let vec_entities: &mut Vec<Entity> = helper_functions::vec_entities_mut(e_type, epoch_info);
let mut entity = Entity::create_rng(e_type, &entity_args.rng)?;
helper_functions::update_position(&entity_args.position, &mut entity, epoch_info)?;
helper_functions::update_stats(&entity_args.stats, false, &mut entity);
// Specifying a name means the name needs to be changed
// Specifying an id however means nothing and should be ignored
helper_functions::update_defaults(entity_args, &mut entity);
let vec_entities: &mut Vec<Entity> = helper_functions::vec_entities_mut(e_type, epoch_info);
info!("Created character: {:#?}", entity);
entity.print_full();
let message = &crate::success::SuccessMessages::CreatedEntity(

View File

@ -2,9 +2,10 @@
use lib_efo::{
entity::{EffectBounds, Entity, EntityIdentifier},
epoch::EpochInfo,
error::EpochError,
naming::NAMING,
stats::{EntityType, StatPair},
stats::{EntityType, PositionIdentifier, StatPair},
};
use crate::commands::entity_generic::AddArgs;
@ -195,3 +196,23 @@ pub(crate) fn update_defaults(entity_args: &AddArgs, e: &mut Entity) {
e.modify_effect_bounds(bounds);
}
}
/// Updates an entity’s position using a [`PositionIdentifier`].
pub(crate) fn update_position(
position: &PositionIdentifier,
entity: &mut Entity,
epoch: &EpochInfo,
) -> Result<(), EpochError> {
match position {
PositionIdentifier::Exact(pos) => entity.modify_position(pos.clone()),
PositionIdentifier::Grid(pos) => entity.modify_position_grid(pos.clone()),
PositionIdentifier::Id(ident) => {
// TODO: Consider another than find that could return any
let entity_identifier = Some(ident.clone());
let entity_source = find_entity(&entity_identifier, &EntityType::Town, epoch)?;
entity.modify_position(entity_source.position().clone());
}
}
Ok(())
}

View File

@ -125,7 +125,7 @@ impl FromStr for EffectApplication {
"todo" => Ok(EffectApplication::PermanentEffectToApply),
_ => Err(EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "The argument could't be made into a EffectApplication",
while_parsing: "EffectApplication",
}),
}
}

View File

@ -1,5 +1,7 @@
//! Implementation of all needed traits for the Entity struct
mod from_impl;
use std::cmp::{max, min};
use cli_table::format::{Border, HorizontalLine, Separator, VerticalLine};
use cli_table::{Style, WithTitle};
use colored::*;
@ -335,14 +337,22 @@ impl Entity {
delta: bool,
) {
let mut r = rand::rng();
let nb = (1..stats_demo.len()).choose(&mut r).unwrap_or(1);
let nb = (1..stats_demo.len() + 1).choose(&mut r).unwrap_or(1);
let stats = stats_demo.choose_multiple(&mut r, nb);
let value = GenericStat(*amount / (nb as isize));
let (a, b) = (*amount / 2, *amount);
let (a, b) = (min(a, b), max(a, b));
let mut value = || GenericStat((a..b).choose(&mut r).unwrap_or(1));
stats.for_each(|stat| {
if delta {
self.delta_stat(StatPair { stat: *stat, value });
self.delta_stat(StatPair {
stat: *stat,
value: value(),
});
} else {
self.change_stat_strict(StatPair { stat: *stat, value })
self.change_stat_strict(StatPair {
stat: *stat,
value: value(),
})
}
});
}
@ -425,6 +435,11 @@ impl Entity {
pub fn modify_position_grid(&mut self, pos: PositionGrid) {
self.metadata.position = pos.to_position();
}
/// Returns a **read‑only reference** to the entity’s current position.
pub fn position(&self) -> &Position {
&self.metadata.position
}
}
// impl Entity {

View File

@ -11,7 +11,7 @@
#![deny(clippy::missing_docs_in_private_items)]
#![allow(dead_code)]
use crate::{error::EpochError, thin_newtype, utils::RngLevel};
use crate::{entity::EntityIdentifier, error::EpochError, thin_newtype, utils::RngLevel};
use cli_table::{CellStruct, Color, Style, Table};
use colored::Colorize;
use derive_more::{Add, Display, Mul, Sub};
@ -640,3 +640,25 @@ pub trait Accessible {
/// `None` if the key does not exist.
fn get_val(&self, key: &str) -> Option<Box<dyn GameStat>>;
}
/// Represents a position that can be identified in three different ways.
///
/// The string format is deliberately simple and is designed to be easy to write
/// by hand while still being unambiguous to a machine.
///
/// | Variant | Syntax in a string |
/// |---------|--------------------|
/// | `Exact` | `X,Y` |
/// | `Grid` | `~X,Y` or `gX,Y` |
/// | `Id` | `@{uuid}` |
#[derive(Debug, Clone)]
pub enum PositionIdentifier {
/// Exact position specified as `X,Y`.
Exact(Position),
/// Grid‑aligned position specified as `~X,Y` or `gX,Y`.
Grid(PositionGrid),
/// Reference to an epoch by UUID, written as `@{uuid}`.
Id(EntityIdentifier),
}

View File

@ -118,7 +118,7 @@ impl FromStr for ListStats {
"strength" | "str" | "st" => Ok(ListStats::Strength),
"fortification" | "fort" | "ft" => Ok(ListStats::Fortification),
"threat" | "thr" | "th" => Ok(ListStats::Threat),
"infrastructure" | "infra" | "infr" => Ok(ListStats::Infrastructure),
"ifr" | "inf" | "infrastructure" | "infra" | "infr" => Ok(ListStats::Infrastructure),
"bureaucracy" | "bureau" | "bur" => Ok(ListStats::Bureaucracy),
"transportation" | "trans" | "trns" => Ok(ListStats::Transportation),
"sprawl" | "spr" | "spra" => Ok(ListStats::Sprawl),
@ -419,7 +419,7 @@ impl FromStr for FactionId {
.parse::<usize>()
.map_err(|_| EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "The argument could't be made into a FactionId",
while_parsing: "FactionId",
})?;
Ok(FactionId(inner))
}

View File

@ -2,7 +2,7 @@
use crate::{
error::EpochError,
stats::{self, ListStats, Position, PositionGrid, StatPair},
stats::{self, ListStats, Position, PositionGrid, PositionIdentifier, StatPair},
};
use std::str::FromStr;
@ -95,6 +95,39 @@ impl std::str::FromStr for PositionGrid {
}
}
impl FromStr for PositionIdentifier {
type Err = EpochError;
/// Parses a string into one of the three variants.
///
/// The parsing rules are described in the table above.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.trim();
if let Some(_rest) = s.find('@') {
let id = s.parse().map_err(|_| EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "PositionIdentifier::EpochId",
})?;
return Ok(Self::Id(id));
}
if let Some(rest) = s.strip_prefix('~').or_else(|| s.strip_prefix('g')) {
let grid = rest.parse().map_err(|_| EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "PositionIdentifier::PositionGrid",
})?;
return Ok(Self::Grid(grid));
}
let exact = s.parse().map_err(|_| EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "PositionIdentifier::Position",
})?;
Ok(Self::Exact(exact))
}
}
/// Convert a tuple of two signed integers into a `Position`.
///
/// This implementation simply wraps the `(isize, isize)` tuple into a

View File

@ -31,6 +31,10 @@ pub enum RngLevel {
Mixed,
/// All non specified are either high or low
Flawed,
/// All non‑specified values are apocalyptic
Apocaliptic,
/// All non‑specified values are doomed
Doom,
}
impl RngLevel {
@ -43,7 +47,9 @@ impl RngLevel {
RngLevel::High => 20..50,
RngLevel::Legendary => 40..70,
RngLevel::Mixed => 0..70,
RngLevel::Flawed => 0..100,
RngLevel::Flawed => -20..30,
RngLevel::Apocaliptic => -50..30,
RngLevel::Doom => -70..40,
}
}