dnd_character/
lib.rs

1#[cfg(feature = "api")]
2pub mod api;
3
4pub mod abilities;
5pub mod classes;
6
7use abilities::AbilityScore;
8use anyhow::bail;
9use lazy_static::lazy_static;
10#[cfg(feature = "serde")]
11use serde::{Deserialize, Serialize};
12use std::cell::RefCell;
13use std::cmp::Ordering;
14use std::collections::HashMap;
15use std::fmt;
16use std::rc::Rc;
17
18use crate::abilities::Abilities;
19use crate::classes::Classes;
20
21#[cfg(feature = "serde")]
22mod abilities_score_serde {
23    use crate::abilities::Abilities;
24    use serde::{Deserialize, Deserializer, Serialize, Serializer};
25    use std::cell::RefCell;
26    use std::rc::Rc;
27
28    pub fn serialize<S>(
29        abilities: &Rc<RefCell<Abilities>>,
30        serializer: S,
31    ) -> Result<S::Ok, S::Error>
32    where
33        S: Serializer,
34    {
35        abilities.borrow().serialize(serializer)
36    }
37
38    pub fn deserialize<'de, D>(deserializer: D) -> Result<Rc<RefCell<Abilities>>, D::Error>
39    where
40        D: Deserializer<'de>,
41    {
42        let abilities = Abilities::deserialize(deserializer)?;
43        Ok(Rc::new(RefCell::new(abilities)))
44    }
45}
46
47#[cfg(feature = "serde")]
48mod classes_serde {
49    use crate::abilities::Abilities;
50    use crate::classes::Classes;
51    use serde::de::Error;
52    use serde::{Deserialize, Deserializer, Serialize, Serializer};
53    use std::cell::RefCell;
54    use std::rc::Rc;
55
56    pub fn serialize<S>(classes: &Classes, serializer: S) -> Result<S::Ok, S::Error>
57    where
58        S: Serializer,
59    {
60        classes.serialize(serializer)
61    }
62
63    pub fn deserialize<'de, D>(
64        deserializer: D,
65        abilities_ref: &Rc<RefCell<Abilities>>,
66    ) -> Result<Classes, D::Error>
67    where
68        D: Deserializer<'de>,
69    {
70        // First deserialize into a serde_json::Value
71        let value = serde_json::Value::deserialize(deserializer)
72            .map_err(|e| D::Error::custom(format!("Failed to deserialize classes: {}", e)))?;
73
74        // Use the custom deserializer that takes the shared abilities reference
75        Classes::deserialize_with_abilities(value, abilities_ref.clone())
76            .map_err(|e| D::Error::custom(format!("Failed to deserialize with abilities: {}", e)))
77    }
78}
79
80lazy_static! {
81    pub static ref GRAPHQL_API_URL: String = std::env::var("DND_GRAPHQL_API_URL")
82        .unwrap_or_else(|_| "https://www.dnd5eapi.co/graphql/2014".to_string());
83}
84
85#[derive(Debug)]
86pub struct UnexpectedAbility;
87
88impl fmt::Display for UnexpectedAbility {
89    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90        write!(f, "The ability isn't present in the character's abilities")
91    }
92}
93
94impl std::error::Error for UnexpectedAbility {}
95
96#[derive(Debug)]
97#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
98#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
99#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
100#[cfg_attr(feature = "serde", serde(from = "CharacterDeserializeHelper"))]
101pub struct Character {
102    /// Indexes from https://www.dnd5eapi.co/api/classes/
103    pub classes: Classes,
104    pub name: String,
105    pub age: u16,
106    /// Index from https://www.dnd5eapi.co/api/races/
107    pub race_index: String,
108    /// Index from https://www.dnd5eapi.co/api/subraces/
109    pub subrace_index: String,
110    /// Index from https://www.dnd5eapi.co/api/alignments/
111    pub alignment_index: String,
112    /// Physical description
113    pub description: String,
114    /// Index from https://www.dnd5eapi.co/api/backgrounds/
115    pub background_index: String,
116    /// Background description
117    pub background_description: String,
118
119    experience_points: u32,
120
121    pub money: u32,
122
123    #[cfg_attr(feature = "serde", serde(with = "abilities_score_serde"))]
124    pub abilities_score: Rc<RefCell<Abilities>>,
125
126    //Health related stuff
127    pub hp: u16,
128    #[serde(default = "default_hit_dice")]
129    pub hit_dice_result: u16,
130
131    pub inventory: HashMap<String, u16>,
132
133    pub other: Vec<String>,
134}
135
136/// For parsing legacy support
137fn default_hit_dice() -> u16 {
138    12
139}
140
141#[cfg(feature = "serde")]
142#[derive(Deserialize)]
143#[serde(rename_all = "camelCase")]
144struct CharacterDeserializeHelper {
145    name: String,
146    age: u16,
147    race_index: String,
148    subrace_index: String,
149    alignment_index: String,
150    description: String,
151    background_index: String,
152    background_description: String,
153    experience_points: u32,
154    money: u32,
155    abilities_score: Abilities,
156    hp: u16,
157    #[serde(default = "default_hit_dice")]
158    hit_dice_result: u16,
159    inventory: HashMap<String, u16>,
160    other: Vec<String>,
161    #[serde(default)]
162    classes: serde_json::Value,
163}
164
165#[cfg(feature = "serde")]
166impl From<CharacterDeserializeHelper> for Character {
167    fn from(helper: CharacterDeserializeHelper) -> Self {
168        // Create the shared abilities reference
169        let abilities_score = Rc::new(RefCell::new(helper.abilities_score));
170
171        // Deserialize classes with the shared abilities reference
172        let classes =
173            match Classes::deserialize_with_abilities(helper.classes, abilities_score.clone()) {
174                Ok(classes) => classes,
175                Err(_) => Classes::default(),
176            };
177
178        Self {
179            classes,
180            name: helper.name,
181            age: helper.age,
182            race_index: helper.race_index,
183            subrace_index: helper.subrace_index,
184            alignment_index: helper.alignment_index,
185            description: helper.description,
186            background_index: helper.background_index,
187            background_description: helper.background_description,
188            experience_points: helper.experience_points,
189            money: helper.money,
190            abilities_score,
191            hp: helper.hp,
192            hit_dice_result: helper.hit_dice_result,
193            inventory: helper.inventory,
194            other: helper.other,
195        }
196    }
197}
198
199#[cfg(feature = "utoipa")]
200pub mod utoipa_addon {
201    use utoipa::openapi::OpenApi;
202    use utoipa::{Modify, PartialSchema, ToSchema};
203
204    pub struct ApiDocDndCharacterAddon;
205
206    impl Modify for ApiDocDndCharacterAddon {
207        fn modify(&self, openapi: &mut OpenApi) {
208            if let Some(components) = openapi.components.as_mut() {
209                components.schemas.insert(
210                    super::classes::ClassProperties::name().to_string(),
211                    super::classes::ClassProperties::schema(),
212                );
213                components.schemas.insert(
214                    super::classes::ClassSpellCasting::name().to_string(),
215                    super::classes::ClassSpellCasting::schema(),
216                );
217                components.schemas.insert(
218                    super::classes::Class::name().to_string(),
219                    super::classes::Class::schema(),
220                );
221                components
222                    .schemas
223                    .insert(super::Classes::name().to_string(), super::Classes::schema());
224                components.schemas.insert(
225                    super::classes::UsableSlots::name().to_string(),
226                    super::classes::UsableSlots::schema(),
227                );
228                components.schemas.insert(
229                    super::Abilities::name().to_string(),
230                    super::Abilities::schema(),
231                );
232                components.schemas.insert(
233                    super::abilities::AbilityScore::name().to_string(),
234                    super::abilities::AbilityScore::schema(),
235                );
236                components.schemas.insert(
237                    super::Character::name().to_string(),
238                    super::Character::schema(),
239                );
240            }
241        }
242    }
243}
244
245const LEVELS: [u32; 19] = [
246    300, 900, 2_700, 6_500, 14_000, 23_000, 34_000, 48_000, 64_000, 85_000, 100_000, 120_000,
247    140_000, 165_000, 195_000, 225_000, 265_000, 305_000, 355_000,
248];
249
250impl Character {
251    pub fn new(
252        main_class: String,
253        name: String,
254        age: u16,
255        race_index: String,
256        subrace_index: String,
257        alignment_index: String,
258        description: String,
259        background_index: String,
260        background_description: String,
261    ) -> Self {
262        // Create the shared abilities reference
263        let abilities_score = Rc::new(RefCell::new(Abilities::default()));
264
265        // Create classes with the default implementation
266        let mut classes = Classes::new(main_class);
267
268        // Update all class properties to use the shared abilities reference
269        for class in classes.0.values_mut() {
270            class.1.abilities_modifiers = abilities_score.clone();
271        }
272
273        Self {
274            classes,
275            name,
276            age,
277            race_index,
278            subrace_index,
279            alignment_index,
280            description,
281            background_index,
282            background_description,
283            experience_points: 0,
284            money: 0,
285            inventory: HashMap::new(),
286
287            abilities_score,
288            hp: 0,
289            hit_dice_result: 0,
290            other: vec![],
291        }
292    }
293
294    pub fn class_armor(&self) -> i8 {
295        // Get the first class and its name
296        let first_class = self.classes.0.iter().next().unwrap();
297        let class_name = first_class.0.as_str();
298
299        let abilities_score = self.abilities_score.borrow();
300
301        // Calculate the base armor class based on the class type
302        let mut base = match class_name {
303            "monk" => {
304                10 + abilities_score.dexterity.modifier(0) + abilities_score.wisdom.modifier(0)
305            }
306            "sorcerer" => 13 + abilities_score.dexterity.modifier(0),
307            "barbarian" => {
308                10 + abilities_score.dexterity.modifier(0)
309                    + abilities_score.constitution.modifier(0)
310            }
311            _ => 10 + abilities_score.dexterity.modifier(0),
312        };
313
314        // Check if the character has the "Fighting Style: Defense" feature
315        let has_defense_style = first_class
316            .1
317            .1
318            .fighting_style
319            .as_ref()
320            .map(|s| s.contains("defense"))
321            .unwrap_or(false)
322            || first_class
323                .1
324                .1
325                .additional_fighting_style
326                .as_ref()
327                .map(|s| s.contains("defense"))
328                .unwrap_or(false);
329
330        // Add bonus if the character has the defense fighting style
331        if has_defense_style {
332            base += 1;
333        }
334
335        base
336    }
337
338    /// Return current level of the character
339    pub fn level(&self) -> u8 {
340        LEVELS
341            .iter()
342            .filter(|&&x| x <= self.experience_points)
343            .count() as u8
344            + 1
345    }
346
347    /// Returns the experience points of the character
348    pub fn experience_points(&self) -> u32 {
349        self.experience_points
350    }
351
352    /// Returns the number of levels the character has earned
353    /// this means that you should add the returned value to a class level (this must be done manually to permit multiclassing)
354    /// # Arguments
355    /// * `experience` - The experience points to add to the character
356    pub fn add_experience(&mut self, experience: u32) -> u8 {
357        //Save the level before adding experience
358        let previous_level = self.level();
359
360        // Limit the experience gotten to the experience needed to reach the next level
361        let experience_to_add = LEVELS
362            .get(self.level() as usize - 1)
363            .map_or(experience, |&next_level_points| {
364                (next_level_points - self.experience_points).min(experience)
365            });
366
367        //Add the experience
368        self.experience_points += experience_to_add;
369
370        //Save the level after adding experience
371        let current_level = self.level();
372
373        //Return the number of levels earned
374        current_level - previous_level
375    }
376
377    pub fn remove_item(
378        &mut self,
379        item: &str,
380        amount: Option<u16>,
381    ) -> anyhow::Result<(), anyhow::Error> {
382        if let Some(quantity) = self.inventory.get_mut(item) {
383            let quantity_to_remove = amount.unwrap_or(*quantity);
384
385            if *quantity <= quantity_to_remove {
386                self.inventory.remove(item);
387            } else {
388                *quantity -= quantity_to_remove;
389            }
390        } else {
391            bail!("Item not found")
392        }
393
394        Ok(())
395    }
396
397    pub fn add_item(&mut self, item: &str, amount: u16) {
398        if let Some(quantity) = self.inventory.get_mut(item) {
399            *quantity += amount;
400        } else {
401            self.inventory.insert(item.to_string(), amount);
402        }
403    }
404
405    pub fn alter_item_quantity(&mut self, item: &str, amount: i32) -> anyhow::Result<()> {
406        match amount.cmp(&0) {
407            Ordering::Greater => {
408                self.add_item(item, amount as u16);
409                Ok(())
410            }
411            Ordering::Less => self.remove_item(item, Some(amount.unsigned_abs() as u16)),
412            Ordering::Equal => {
413                bail!("Cannot alter quantity to 0")
414            }
415        }
416    }
417
418    /// Calculate the maximum HP of the character based on constitution modifier and hit dice result
419    pub fn max_hp(&self) -> u16 {
420        let constitution_modifier = self.abilities_score.borrow().constitution.modifier(0);
421
422        (constitution_modifier as i32)
423            .saturating_mul(self.level().into())
424            .saturating_add(self.hit_dice_result.into())
425            .max(0) as u16
426    }
427}