dnd_character/
classes.rs

1use crate::abilities::Abilities;
2use serde::{Deserialize, Serialize};
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::hash::Hash;
6use std::rc::Rc;
7
8// Default function for abilities_modifiers during deserialization
9#[cfg(feature = "serde")]
10fn default_abilities_modifiers() -> Rc<RefCell<Abilities>> {
11    Rc::new(RefCell::new(Abilities::default()))
12}
13
14#[derive(Debug, Clone)]
15#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
16#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
17#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
18pub enum ClassSpellCasting {
19    // Wizard
20    // Ask the user to prepare spells at the start of the day
21    //
22    // TODO: Add slots and consume them instead of removing from prepared
23    // TODO: daily chosable spells = inteligence + level
24    KnowledgePrepared {
25        /// Indexes from https://www.dnd5eapi.co/api/spells/
26        spells_index: Vec<Vec<String>>,
27        /// Indexes from https://www.dnd5eapi.co/api/spells/
28        spells_prepared_index: Vec<Vec<String>>,
29        /// If the user has already prepared spells for the day
30        pending_preparation: bool,
31    },
32    // TEMP: Wizard
33    // Cleric, Paladin, Druid
34    // Ask the user to prepare spells at the start of the day
35    //
36    // TODO: Add slots and consume them instead of removing from prepared
37    // TODO: cleric/druid daily chosable spells = WISDOM + (level/2)
38    // TODO: paladin daily chosable spells = CHARISMA + (level/2)
39    AlreadyKnowPrepared {
40        /// Indexes from https://www.dnd5eapi.co/api/spells/
41        spells_prepared_index: Vec<Vec<String>>,
42        /// If the user has already prepared spells for the day
43        pending_preparation: bool,
44    },
45    // Bard, Ranger, Warlock, (Sorcerer?)
46    // No need to ask anything, at the start of the day
47    KnowledgeAlreadyPrepared {
48        /// Indexes from https://www.dnd5eapi.co/api/spells/
49        spells_index: Vec<Vec<String>>,
50        usable_slots: UsableSlots,
51    },
52}
53
54#[derive(Debug, Default, Clone)]
55#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
56#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
57#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
58pub struct UsableSlots {
59    pub cantrip_slots: u8,
60    pub level_1: u8,
61    pub level_2: u8,
62    pub level_3: u8,
63    pub level_4: u8,
64    pub level_5: u8,
65    pub level_6: u8,
66    pub level_7: u8,
67    pub level_8: u8,
68    pub level_9: u8,
69}
70
71#[derive(Debug, Default, Clone)]
72#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
73#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
74#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
75pub struct ClassProperties {
76    /// The level of the class
77    pub level: u8,
78    /// Index from https://www.dnd5eapi.co/api/subclasses/
79    pub subclass: Option<String>,
80    /// Indexes from https://www.dnd5eapi.co/api/spells/
81    pub spell_casting: Option<ClassSpellCasting>,
82    pub fighting_style: Option<String>,
83    pub hunters_prey: Option<String>,
84    pub defensive_tactics: Option<String>,
85    pub additional_fighting_style: Option<String>,
86    pub multiattack: Option<String>,
87    pub superior_hunters_defense: Option<String>,
88    pub natural_explorer_terrain_type: Option<Vec<String>>,
89    pub ranger_favored_enemy_type: Option<Vec<String>>,
90    pub sorcerer_metamagic: Option<Vec<String>>,
91    pub warlock_eldritch_invocation: Option<Vec<String>>,
92    pub sorcerer_dragon_ancestor: Option<String>,
93    #[cfg_attr(feature = "serde", serde(skip_serializing, skip_deserializing, default = "default_abilities_modifiers"))]
94    pub abilities_modifiers: Rc<RefCell<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: Rc<RefCell<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}