dnd_character/
classes.rs

1use crate::abilities::Abilities;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::hash::Hash;
5use std::sync::{Arc, Mutex};
6
7// Default function for abilities_modifiers during deserialization
8#[cfg(feature = "serde")]
9fn default_abilities_modifiers() -> Arc<Mutex<Abilities>> {
10    Arc::new(Mutex::new(Abilities::default()))
11}
12
13#[derive(Debug, Clone)]
14#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
15#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
16#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
17pub enum ClassSpellCasting {
18    // Wizard
19    // Ask the user to prepare spells at the start of the day
20    //
21    // TODO: Add slots and consume them instead of removing from prepared
22    // TODO: daily chosable spells = inteligence + level
23    KnowledgePrepared {
24        /// Indexes from https://www.dnd5eapi.co/api/spells/
25        spells_index: Vec<Vec<String>>,
26        /// Indexes from https://www.dnd5eapi.co/api/spells/
27        spells_prepared_index: Vec<Vec<String>>,
28        /// If the user has already prepared spells for the day
29        pending_preparation: bool,
30    },
31    // TEMP: Wizard
32    // Cleric, Paladin, Druid
33    // Ask the user to prepare spells at the start of the day
34    //
35    // TODO: Add slots and consume them instead of removing from prepared
36    // TODO: cleric/druid daily chosable spells = WISDOM + (level/2)
37    // TODO: paladin daily chosable spells = CHARISMA + (level/2)
38    AlreadyKnowPrepared {
39        /// Indexes from https://www.dnd5eapi.co/api/spells/
40        spells_prepared_index: Vec<Vec<String>>,
41        /// If the user has already prepared spells for the day
42        pending_preparation: bool,
43    },
44    // Bard, Ranger, Warlock, (Sorcerer?)
45    // No need to ask anything, at the start of the day
46    KnowledgeAlreadyPrepared {
47        /// Indexes from https://www.dnd5eapi.co/api/spells/
48        spells_index: Vec<Vec<String>>,
49        usable_slots: UsableSlots,
50    },
51}
52
53#[derive(Debug, Default, Clone)]
54#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
55#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
56#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
57pub struct UsableSlots {
58    pub cantrip_slots: u8,
59    pub level_1: u8,
60    pub level_2: u8,
61    pub level_3: u8,
62    pub level_4: u8,
63    pub level_5: u8,
64    pub level_6: u8,
65    pub level_7: u8,
66    pub level_8: u8,
67    pub level_9: u8,
68}
69
70#[derive(Debug, Default, Clone)]
71#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
72#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
73#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
74pub struct ClassProperties {
75    /// The level of the class
76    pub level: u8,
77    /// Index from https://www.dnd5eapi.co/api/subclasses/
78    pub subclass: Option<String>,
79    /// Indexes from https://www.dnd5eapi.co/api/spells/
80    pub spell_casting: Option<ClassSpellCasting>,
81    pub fighting_style: Option<String>,
82    pub hunters_prey: Option<String>,
83    pub defensive_tactics: Option<String>,
84    pub additional_fighting_style: Option<String>,
85    pub multiattack: Option<String>,
86    pub superior_hunters_defense: Option<String>,
87    pub natural_explorer_terrain_type: Option<Vec<String>>,
88    pub ranger_favored_enemy_type: Option<Vec<String>>,
89    pub sorcerer_metamagic: Option<Vec<String>>,
90    pub warlock_eldritch_invocation: Option<Vec<String>>,
91    pub sorcerer_dragon_ancestor: Option<String>,
92    #[cfg_attr(
93        feature = "serde",
94        serde(
95            skip_serializing,
96            skip_deserializing,
97            default = "default_abilities_modifiers"
98        )
99    )]
100    #[cfg_attr(feature = "utoipa", schema(ignore))]
101    pub abilities: Arc<Mutex<Abilities>>,
102}
103
104/// The key is the index of the class from https://www.dnd5eapi.co/api/classes
105#[derive(Debug)]
106#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
107#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
108#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
109pub struct Class(String, pub ClassProperties);
110
111impl Hash for Class {
112    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
113        self.0.hash(state);
114    }
115}
116
117impl PartialEq for Class {
118    fn eq(&self, other: &Self) -> bool {
119        self.0 == other.0
120    }
121}
122
123impl Eq for Class {}
124
125impl Class {
126    pub fn index(&self) -> &str {
127        &self.0
128    }
129
130    pub fn hit_dice(&self) -> u8 {
131        match self.index() {
132            "barbarian" => 12,
133            "bard" => 8,
134            "cleric" => 8,
135            "druid" => 8,
136            "fighter" => 10,
137            "monk" => 8,
138            "paladin" => 10,
139            "ranger" => 10,
140            "rogue" => 8,
141            "sorcerer" => 6,
142            "warlock" => 8,
143            "wizard" => 6,
144            // For unknown classes we will use the minimum hit dice
145            _ => 6,
146        }
147    }
148}
149
150#[derive(Default, Debug)]
151#[cfg_attr(feature = "serde", derive(Serialize))]
152#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
153#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
154pub struct Classes(pub HashMap<String, Class>);
155
156#[cfg(feature = "serde")]
157impl<'de> Deserialize<'de> for Classes {
158    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
159    where
160        D: serde::Deserializer<'de>,
161    {
162        // This is a placeholder since we'll use the custom deserializer
163        // This won't be used directly, but helps with derive macros
164        let map = HashMap::<String, Class>::deserialize(deserializer)?;
165        Ok(Classes(map))
166    }
167}
168
169impl Classes {
170    #[cfg(feature = "serde")]
171    pub fn deserialize_with_abilities(
172        value: serde_json::Value,
173        shared_abilities: Arc<Mutex<Abilities>>,
174    ) -> Result<Self, serde_json::Error> {
175        let mut result = Classes::default();
176
177        // Parse the JSON map of classes
178        let class_map = value
179            .as_object()
180            .ok_or_else(|| serde::de::Error::custom("Expected object for Classes"))?;
181
182        for (key, value) in class_map {
183            // Deserialize the basic class properties without abilities
184            let mut class_properties: ClassProperties =
185                serde_json::from_value(value.get(1).cloned().unwrap_or(serde_json::Value::Null))?;
186
187            // Set the shared abilities reference
188            class_properties.abilities = shared_abilities.clone();
189
190            // Create the class entry with the class index
191            let index = key.clone();
192            let class = Class(index, class_properties);
193
194            // Add to the map
195            result.0.insert(key.clone(), class);
196        }
197
198        Ok(result)
199    }
200
201    pub fn new(class_index: String) -> Self {
202        let mut classes = Self::default();
203
204        let spell_casting = match class_index.as_str() {
205            "cleric" | "paladin" | "druid" | "wizard" => {
206                Some(ClassSpellCasting::AlreadyKnowPrepared {
207                    spells_prepared_index: Vec::new(),
208                    pending_preparation: true,
209                })
210            }
211            "ranger" | "bard" | "warlock" | "sorcerer" => {
212                Some(ClassSpellCasting::KnowledgeAlreadyPrepared {
213                    spells_index: Vec::new(),
214                    usable_slots: UsableSlots::default(),
215                })
216            }
217            _ => None,
218        };
219
220        let class_properties = ClassProperties {
221            spell_casting,
222            ..ClassProperties::default()
223        };
224
225        // The abilities_modifiers will be set externally when creating from Character
226
227        classes
228            .0
229            .insert(class_index.clone(), Class(class_index, class_properties));
230        classes
231    }
232}