dndgamerolls 0.1.10

DnD Game Rolls - D&D dice roller with CLI and 3D visualization using Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! Character data types for D&D character sheets
//!
//! This module contains all types related to loading, saving, and accessing
//! character data from JSON files, including file discovery and validation.

use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

// ============================================================================
// Character Schema Types - Full D&D 5e Character Sheet
// ============================================================================

/// Complete character sheet data
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct CharacterSheet {
    pub character: CharacterInfo,
    pub attributes: Attributes,
    pub modifiers: AttributeModifiers,
    pub combat: Combat,
    #[serde(rename = "proficiencyBonus")]
    pub proficiency_bonus: i32,
    #[serde(rename = "savingThrows")]
    pub saving_throws: HashMap<String, SavingThrow>,
    pub skills: HashMap<String, Skill>,
    #[serde(default)]
    pub equipment: Option<Equipment>,
    #[serde(default)]
    pub features: Vec<Feature>,
    #[serde(default)]
    pub spells: Option<SpellCasting>,
    /// Custom fields for Basic Info group (name -> value)
    #[serde(rename = "customBasicInfo", default)]
    pub custom_basic_info: HashMap<String, String>,
    /// Custom attributes beyond the standard 6 (name -> score)
    #[serde(rename = "customAttributes", default)]
    pub custom_attributes: HashMap<String, i32>,
    /// Custom combat stats (name -> value as string)
    #[serde(rename = "customCombat", default)]
    pub custom_combat: HashMap<String, String>,
}

/// Basic character information
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct CharacterInfo {
    pub name: String,
    #[serde(rename = "alterEgo", default)]
    pub alter_ego: Option<String>,
    #[serde(rename = "familyName", default)]
    pub family_name: Option<String>,
    #[serde(rename = "shopName", default)]
    pub shop_name: Option<String>,
    pub class: String,
    #[serde(default)]
    pub subclass: Option<String>,
    pub race: String,
    pub level: i32,
    #[serde(default)]
    pub experience: i32,
    #[serde(default)]
    pub alignment: Option<String>,
    #[serde(default)]
    pub background: Option<String>,
    #[serde(default)]
    pub languages: Vec<String>,
}

/// Character ability scores
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Attributes {
    pub strength: i32,
    pub dexterity: i32,
    pub constitution: i32,
    pub intelligence: i32,
    pub wisdom: i32,
    pub charisma: i32,
}

impl Attributes {
    /// Calculate modifier from ability score (standard D&D formula)
    pub fn calculate_modifier(score: i32) -> i32 {
        (score - 10) / 2
    }

    /// Get all attributes as a vec of (name, score) tuples
    pub fn as_vec(&self) -> Vec<(&'static str, i32)> {
        vec![
            ("Strength", self.strength),
            ("Dexterity", self.dexterity),
            ("Constitution", self.constitution),
            ("Intelligence", self.intelligence),
            ("Wisdom", self.wisdom),
            ("Charisma", self.charisma),
        ]
    }
}

/// Ability score modifiers
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct AttributeModifiers {
    pub strength: i32,
    pub dexterity: i32,
    pub constitution: i32,
    pub intelligence: i32,
    pub wisdom: i32,
    pub charisma: i32,
}

/// Combat statistics
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Combat {
    #[serde(rename = "armorClass")]
    pub armor_class: i32,
    pub initiative: i32,
    #[serde(default)]
    pub speed: i32,
    #[serde(rename = "hitPoints", default)]
    pub hit_points: Option<HitPoints>,
    #[serde(rename = "hitDice", default)]
    pub hit_dice: Option<HitDice>,
    #[serde(rename = "deathSaves", default)]
    pub death_saves: Option<DeathSaves>,
}

/// Hit points tracking
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct HitPoints {
    pub current: i32,
    pub maximum: i32,
    #[serde(default)]
    pub temporary: i32,
}

/// Hit dice tracking
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct HitDice {
    pub total: String,
    pub current: i32,
}

/// Death saves tracking
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct DeathSaves {
    pub successes: i32,
    pub failures: i32,
}

/// Saving throw data
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct SavingThrow {
    pub proficient: bool,
    pub modifier: i32,
}

/// Skill data
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Skill {
    pub proficient: bool,
    pub modifier: i32,
    #[serde(default)]
    pub expertise: Option<bool>,
    #[serde(rename = "proficiencyType", default)]
    pub proficiency_type: Option<String>,
}

/// Equipment and inventory
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Equipment {
    #[serde(default)]
    pub weapons: Vec<Weapon>,
    #[serde(default)]
    pub armor: Option<Armor>,
    #[serde(default)]
    pub items: Vec<String>,
    #[serde(default)]
    pub currency: Currency,
}

/// Weapon data
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Weapon {
    pub name: String,
    #[serde(rename = "attackBonus")]
    pub attack_bonus: i32,
    pub damage: String,
    #[serde(rename = "damageType")]
    pub damage_type: String,
    #[serde(default)]
    pub properties: Vec<String>,
}

/// Armor data
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Armor {
    pub name: String,
    #[serde(rename = "armorClass")]
    pub armor_class: i32,
    #[serde(rename = "armorClassWithDex", default)]
    pub armor_class_with_dex: Option<i32>,
    #[serde(rename = "type", default)]
    pub armor_type: Option<String>,
}

/// Currency tracking
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Currency {
    #[serde(default)]
    pub copper: i32,
    #[serde(default)]
    pub silver: i32,
    #[serde(default)]
    pub electrum: i32,
    #[serde(default)]
    pub gold: i32,
    #[serde(default)]
    pub platinum: i32,
}

/// Character feature or trait
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Feature {
    pub name: String,
    pub description: String,
    #[serde(default)]
    pub damage: Option<String>,
}

/// Spellcasting information
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct SpellCasting {
    #[serde(rename = "spellcastingAbility", default)]
    pub spellcasting_ability: Option<String>,
    #[serde(rename = "spellSaveDC", default)]
    pub spell_save_dc: Option<i32>,
    #[serde(rename = "spellAttackBonus", default)]
    pub spell_attack_bonus: Option<i32>,
    #[serde(rename = "spellSlots", default)]
    pub spell_slots: HashMap<String, i32>,
    #[serde(rename = "knownSpells", default)]
    pub known_spells: Vec<String>,
}

// ============================================================================
// Character File Management
// ============================================================================

/// Discovered character file info
#[derive(Debug, Clone)]
pub struct CharacterFile {
    pub path: PathBuf,
    pub name: String,
    pub is_valid: bool,
}

/// Resource for managing available characters
#[derive(Resource, Default)]
pub struct CharacterManager {
    pub available_characters: Vec<CharacterFile>,
    pub current_character_path: Option<PathBuf>,
}

impl CharacterManager {
    /// Scan directory for valid character JSON files
    pub fn scan_directory(dir: &Path) -> Vec<CharacterFile> {
        let mut characters = Vec::new();

        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().is_some_and(|ext| ext == "json") {
                    if let Some(char_file) = Self::try_load_character_file(&path) {
                        characters.push(char_file);
                    }
                }
            }
        }

        // Sort by character name
        characters.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
        characters
    }

    /// Try to load and validate a character file
    fn try_load_character_file(path: &Path) -> Option<CharacterFile> {
        match std::fs::read_to_string(path) {
            Ok(contents) => {
                let (name, is_valid) = match serde_json::from_str::<CharacterSheet>(&contents) {
                    Ok(sheet) => (sheet.character.name.clone(), true),
                    Err(_) => {
                        // Try to at least get the character name
                        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&contents) {
                            let name = val
                                .get("character")
                                .and_then(|c| c.get("name"))
                                .and_then(|n| n.as_str())
                                .unwrap_or("Unknown")
                                .to_string();
                            (name, false)
                        } else {
                            return None; // Not a valid JSON at all
                        }
                    }
                };
                Some(CharacterFile {
                    path: path.to_path_buf(),
                    name,
                    is_valid,
                })
            }
            Err(_) => None,
        }
    }

    /// Generate a snake_case filename from character name
    pub fn generate_filename(name: &str) -> String {
        let sanitized: String = name
            .chars()
            .map(|c| {
                if c.is_alphanumeric() {
                    c.to_ascii_lowercase()
                } else {
                    '_'
                }
            })
            .collect();

        // Remove consecutive underscores and trim
        let mut result = String::new();
        let mut last_was_underscore = false;
        for c in sanitized.chars() {
            if c == '_' {
                if !last_was_underscore && !result.is_empty() {
                    result.push(c);
                    last_was_underscore = true;
                }
            } else {
                result.push(c);
                last_was_underscore = false;
            }
        }

        // Trim trailing underscore
        result.trim_end_matches('_').to_string() + ".json"
    }

    /// Sanitize character name input (alphanumeric only, special chars become underscore)
    pub fn sanitize_name(input: &str) -> String {
        input
            .chars()
            .map(|c| {
                if c.is_alphanumeric() || c == ' ' {
                    c
                } else {
                    '_'
                }
            })
            .collect()
    }
}

// ============================================================================
// Character Data Resource (existing, enhanced)
// ============================================================================

/// Resource containing the loaded character data
#[derive(Resource, Default)]
pub struct CharacterData {
    pub sheet: Option<CharacterSheet>,
    pub file_path: Option<PathBuf>,
    pub is_modified: bool,
}

impl CharacterData {
    /// Load character data from a JSON file
    /// If the file doesn't exist, tries to find any character JSON file in the current directory
    pub fn load_from_file(path: &str) -> Self {
        let path_buf = PathBuf::from(path);

        // First try the specified path
        if path_buf.exists() {
            return Self::try_load_from_path(&path_buf);
        }

        // If the specified file doesn't exist, try to find any character JSON file
        let current_dir = std::env::current_dir().unwrap_or_default();
        let available = CharacterManager::scan_directory(&current_dir);

        if let Some(first_char) = available.first() {
            println!("Loading character: '{}'", first_char.name);
            return Self::try_load_from_path(&first_char.path);
        }

        // No character files found - this is fine, user can create one
        println!(
            "No character files found. Use the Character Sheet tab to create a new character."
        );
        Self::default()
    }

    /// Try to load from a specific path
    fn try_load_from_path(path_buf: &PathBuf) -> Self {
        match std::fs::read_to_string(path_buf) {
            Ok(contents) => match serde_json::from_str(&contents) {
                Ok(sheet) => {
                    println!("Loaded character sheet from {}", path_buf.display());
                    Self {
                        sheet: Some(sheet),
                        file_path: Some(path_buf.clone()),
                        is_modified: false,
                    }
                }
                Err(e) => {
                    eprintln!(
                        "Warning: Failed to parse character sheet '{}': {}",
                        path_buf.display(),
                        e
                    );
                    Self::default()
                }
            },
            Err(e) => {
                // Only show error if the file was supposed to exist
                if path_buf.exists() {
                    eprintln!(
                        "Warning: Failed to read character file '{}': {}",
                        path_buf.display(),
                        e
                    );
                }
                Self::default()
            }
        }
    }

    /// Load from a PathBuf
    pub fn load_from_path(path: &Path) -> Self {
        Self::load_from_file(path.to_str().unwrap_or(""))
    }

    /// Save character data to file
    /// Always generates a new filename based on character name
    pub fn save(&mut self) -> Result<(), String> {
        let sheet = self
            .sheet
            .as_ref()
            .ok_or_else(|| "No character data to save".to_string())?;

        // Always use the character name for the filename
        let filename = CharacterManager::generate_filename(&sheet.character.name);
        let new_path = PathBuf::from(&filename);

        let json = serde_json::to_string_pretty(sheet)
            .map_err(|e| format!("Failed to serialize character: {}", e))?;

        std::fs::write(&new_path, json).map_err(|e| format!("Failed to write file: {}", e))?;

        // Note: We intentionally do NOT delete the old file when renaming
        // This prevents data loss and allows the user to manually clean up old files

        self.file_path = Some(new_path);
        self.is_modified = false;
        Ok(())
    }

    /// Save to a specific path
    pub fn save_to(&mut self, path: &Path) -> Result<(), String> {
        self.file_path = Some(path.to_path_buf());
        self.save()
    }

    /// Create a new default character
    pub fn create_new() -> Self {
        let sheet = CharacterSheet {
            character: CharacterInfo {
                name: "New Character".to_string(),
                class: "Fighter".to_string(),
                race: "Human".to_string(),
                level: 1,
                ..Default::default()
            },
            attributes: Attributes {
                strength: 10,
                dexterity: 10,
                constitution: 10,
                intelligence: 10,
                wisdom: 10,
                charisma: 10,
            },
            modifiers: AttributeModifiers::default(),
            combat: Combat {
                armor_class: 10,
                initiative: 0,
                speed: 30,
                hit_points: Some(HitPoints {
                    current: 10,
                    maximum: 10,
                    temporary: 0,
                }),
                ..Default::default()
            },
            proficiency_bonus: 2,
            saving_throws: Self::default_saving_throws(),
            skills: Self::default_skills(),
            ..Default::default()
        };

        Self {
            sheet: Some(sheet),
            file_path: None,
            is_modified: true,
        }
    }

    fn default_saving_throws() -> HashMap<String, SavingThrow> {
        let mut saves = HashMap::new();
        for ability in &[
            "strength",
            "dexterity",
            "constitution",
            "intelligence",
            "wisdom",
            "charisma",
        ] {
            saves.insert(
                ability.to_string(),
                SavingThrow {
                    proficient: false,
                    modifier: 0,
                },
            );
        }
        saves
    }

    fn default_skills() -> HashMap<String, Skill> {
        let mut skills = HashMap::new();
        let skill_names = [
            "acrobatics",
            "animalHandling",
            "arcana",
            "athletics",
            "deception",
            "history",
            "insight",
            "intimidation",
            "investigation",
            "medicine",
            "nature",
            "perception",
            "performance",
            "persuasion",
            "religion",
            "sleightOfHand",
            "stealth",
            "survival",
        ];
        for name in skill_names {
            skills.insert(
                name.to_string(),
                Skill {
                    proficient: false,
                    modifier: 0,
                    ..Default::default()
                },
            );
        }
        skills
    }

    /// Get the modifier for a skill by name
    pub fn get_skill_modifier(&self, skill: &str) -> Option<i32> {
        self.sheet
            .as_ref()
            .and_then(|s| s.skills.get(skill).map(|sk| sk.modifier))
    }

    /// Get the modifier for an ability by name
    pub fn get_ability_modifier(&self, ability: &str) -> Option<i32> {
        self.sheet
            .as_ref()
            .map(|s| match ability.to_lowercase().as_str() {
                "str" | "strength" => s.modifiers.strength,
                "dex" | "dexterity" => s.modifiers.dexterity,
                "con" | "constitution" => s.modifiers.constitution,
                "int" | "intelligence" => s.modifiers.intelligence,
                "wis" | "wisdom" => s.modifiers.wisdom,
                "cha" | "charisma" => s.modifiers.charisma,
                _ => 0,
            })
    }

    /// Get the modifier for a saving throw by ability name
    pub fn get_saving_throw_modifier(&self, ability: &str) -> Option<i32> {
        self.sheet.as_ref().and_then(|s| {
            s.saving_throws
                .get(&ability.to_lowercase())
                .map(|st| st.modifier)
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_character_data_default() {
        let data = CharacterData::default();
        assert!(data.sheet.is_none());
        assert!(data.get_skill_modifier("stealth").is_none());
        assert!(data.get_ability_modifier("dex").is_none());
        assert!(data.get_saving_throw_modifier("dex").is_none());
    }

    #[test]
    fn test_generate_filename() {
        assert_eq!(
            CharacterManager::generate_filename("Strawberry Picker"),
            "strawberry_picker.json"
        );
        // Special characters become underscores, consecutive underscores are collapsed
        assert_eq!(
            CharacterManager::generate_filename("Test@#$Character"),
            "test_character.json"
        );
        assert_eq!(CharacterManager::generate_filename("Simple"), "simple.json");
    }

    #[test]
    fn test_sanitize_name() {
        assert_eq!(
            CharacterManager::sanitize_name("Test@Character"),
            "Test_Character"
        );
        assert_eq!(
            CharacterManager::sanitize_name("Normal Name"),
            "Normal Name"
        );
    }

    #[test]
    fn test_calculate_modifier() {
        assert_eq!(Attributes::calculate_modifier(10), 0);
        assert_eq!(Attributes::calculate_modifier(20), 5);
        assert_eq!(Attributes::calculate_modifier(8), -1);
        assert_eq!(Attributes::calculate_modifier(15), 2);
    }
}