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(feature = "serde", serde(skip_serializing, skip_deserializing, default = "default_abilities_modifiers"))]
93    #[cfg_attr(feature = "utoipa", schema(ignore))]
94    pub abilities_modifiers: Arc<Mutex<Abilities>>,
95}
96
97/// The key is the index of the class from https://www.dnd5eapi.co/api/classes
98#[derive(Debug)]
99#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
100#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
101#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
102pub struct Class(String, pub ClassProperties);
103
104impl Hash for Class {
105    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
106        self.0.hash(state);
107    }
108}
109
110impl PartialEq for Class {
111    fn eq(&self, other: &Self) -> bool {
112        self.0 == other.0
113    }
114}
115
116impl Eq for Class {}
117
118impl Class {
119    pub fn index(&self) -> &str {
120        &self.0
121    }
122
123    pub fn hit_dice(&self) -> u8 {
124        match self.index() {
125            "barbarian" => 12,
126            "bard" => 8,
127            "cleric" => 8,
128            "druid" => 8,
129            "fighter" => 10,
130            "monk" => 8,
131            "paladin" => 10,
132            "ranger" => 10,
133            "rogue" => 8,
134            "sorcerer" => 6,
135            "warlock" => 8,
136            "wizard" => 6,
137            // For unknown classes we will use the minimum hit dice
138            _ => 6,
139        }
140    }
141}
142
143#[derive(Default, Debug)]
144#[cfg_attr(feature = "serde", derive(Serialize))]
145#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
146#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
147pub struct Classes(pub HashMap<String, Class>);
148
149#[cfg(feature = "serde")]
150impl<'de> Deserialize<'de> for Classes {
151    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
152    where
153        D: serde::Deserializer<'de>
154    {
155        // This is a placeholder since we'll use the custom deserializer
156        // This won't be used directly, but helps with derive macros
157        let map = HashMap::<String, Class>::deserialize(deserializer)?;
158        Ok(Classes(map))
159    }
160}
161
162impl Classes {
163    #[cfg(feature = "serde")]
164    pub fn deserialize_with_abilities(
165        value: serde_json::Value,
166        shared_abilities: Arc<Mutex<Abilities>>,
167    ) -> Result<Self, serde_json::Error> {
168        let mut result = Classes::default();
169        
170        // Parse the JSON map of classes
171        let class_map = value.as_object()
172            .ok_or_else(|| serde::de::Error::custom("Expected object for Classes"))?;
173        
174        for (key, value) in class_map {
175            // Deserialize the basic class properties without abilities
176            let mut class_properties: ClassProperties = serde_json::from_value(
177                value.get(1).cloned().unwrap_or(serde_json::Value::Null)
178            )?;
179            
180            // Set the shared abilities reference
181            class_properties.abilities_modifiers = shared_abilities.clone();
182            
183            // Create the class entry with the class index
184            let index = key.clone();
185            let class = Class(index, class_properties);
186            
187            // Add to the map
188            result.0.insert(key.clone(), class);
189        }
190        
191        Ok(result)
192    }
193
194    pub fn new(class_index: String) -> Self {
195        let mut classes = Self::default();
196
197        let spell_casting = match class_index.as_str() {
198            "cleric" | "paladin" | "druid" | "wizard" => {
199                Some(ClassSpellCasting::AlreadyKnowPrepared {
200                    spells_prepared_index: Vec::new(),
201                    pending_preparation: true,
202                })
203            }
204            "ranger" | "bard" | "warlock" | "sorcerer" => {
205                Some(ClassSpellCasting::KnowledgeAlreadyPrepared {
206                    spells_index: Vec::new(),
207                    usable_slots: UsableSlots::default(),
208                })
209            }
210            _ => None,
211        };
212
213        let class_properties = ClassProperties {
214            spell_casting,
215            ..ClassProperties::default()
216        };
217        
218        // The abilities_modifiers will be set externally when creating from Character
219
220        classes
221            .0
222            .insert(class_index.clone(), Class(class_index, class_properties));
223        classes
224    }
225}