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
//! Input handling systems
//!
//! This module contains systems for keyboard input, dice rolling controls,
//! command input, and command history management.

use bevy::prelude::*;
use bevy_rapier3d::prelude::*;
use rand::Rng;

use crate::dice3d::throw_control::ThrowControlState;
use crate::dice3d::types::*;

use super::setup::{calculate_dice_position, spawn_die};

/// Handle keyboard input for rolling and resetting dice
pub fn handle_input(
    keyboard: Res<ButtonInput<KeyCode>>,
    mut roll_state: ResMut<RollState>,
    mut dice_results: ResMut<DiceResults>,
    mut dice_query: Query<(&mut Transform, &mut Velocity), With<Die>>,
    dice_config: Res<DiceConfig>,
    command_input: Res<CommandInput>,
    throw_state: Res<ThrowControlState>,
) {
    // Don't process game inputs when command input is active
    if command_input.active {
        return;
    }

    if keyboard.just_pressed(KeyCode::Space) && !roll_state.rolling {
        roll_state.rolling = true;
        dice_results.results.clear();

        let mut rng = rand::thread_rng();
        let num_dice = dice_config.dice_to_roll.len();

        // Get base throw velocity from mouse-controlled throw state
        let base_velocity = throw_state.calculate_throw_velocity();

        for (i, (mut transform, mut velocity)) in dice_query.iter_mut().enumerate() {
            let position = calculate_dice_position(i, num_dice);
            // Add slight randomness to starting position
            transform.translation = position
                + Vec3::new(
                    rng.gen_range(-0.3..0.3),
                    rng.gen_range(0.0..1.0),
                    rng.gen_range(-0.3..0.3),
                );
            transform.rotation = Quat::from_euler(
                EulerRot::XYZ,
                rng.gen_range(0.0..std::f32::consts::TAU),
                rng.gen_range(0.0..std::f32::consts::TAU),
                rng.gen_range(0.0..std::f32::consts::TAU),
            );

            // Use mouse-controlled throw direction with slight randomness
            velocity.linvel = base_velocity
                + Vec3::new(
                    rng.gen_range(-0.5..0.5),
                    rng.gen_range(-0.3..0.0),
                    rng.gen_range(-0.5..0.5),
                );
            velocity.angvel = throw_state.calculate_angular_velocity(&mut rng);
        }
    }

    if keyboard.just_pressed(KeyCode::KeyR) {
        roll_state.rolling = false;
        dice_results.results.clear();

        let num_dice = dice_config.dice_to_roll.len();

        for (i, (mut transform, mut velocity)) in dice_query.iter_mut().enumerate() {
            let mut pos = calculate_dice_position(i, num_dice);
            pos.y = 0.3; // Rest on floor
            transform.translation = pos;
            transform.rotation = Quat::IDENTITY;
            velocity.linvel = Vec3::ZERO;
            velocity.angvel = Vec3::ZERO;
        }
    }
}

/// Handle command input from the user
#[allow(clippy::too_many_arguments)]
pub fn handle_command_input(
    mut commands: Commands,
    keyboard: Res<ButtonInput<KeyCode>>,
    mut char_events: EventReader<bevy::input::keyboard::KeyboardInput>,
    mut command_input: ResMut<CommandInput>,
    mut command_history: ResMut<CommandHistory>,
    mut input_text_query: Query<&mut Text, With<CommandInputText>>,
    mut history_text_query: Query<&mut Text, (With<CommandHistoryList>, Without<CommandInputText>)>,
    mut dice_config: ResMut<DiceConfig>,
    mut dice_results: ResMut<DiceResults>,
    mut roll_state: ResMut<RollState>,
    character_data: Res<CharacterData>,
    // For respawning dice
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    dice_query: Query<Entity, With<Die>>,
) {
    // Handle number keys 1-9 to reroll from history (when not in input mode)
    if !command_input.active {
        let history_keys = [
            (KeyCode::Digit1, 0),
            (KeyCode::Digit2, 1),
            (KeyCode::Digit3, 2),
            (KeyCode::Digit4, 3),
            (KeyCode::Digit5, 4),
            (KeyCode::Digit6, 5),
            (KeyCode::Digit7, 6),
            (KeyCode::Digit8, 7),
            (KeyCode::Digit9, 8),
        ];

        for (key, index) in history_keys {
            if keyboard.just_pressed(key) {
                if let Some(cmd) = command_history.commands.get(index).cloned() {
                    // Execute the command from history
                    if let Some(new_config) = parse_command(&cmd, &character_data) {
                        // Remove old dice
                        for entity in dice_query.iter() {
                            commands.entity(entity).despawn_recursive();
                        }

                        // Update config
                        *dice_config = new_config;
                        dice_results.results.clear();

                        // Spawn new dice
                        for (i, die_type) in dice_config.dice_to_roll.iter().enumerate() {
                            let position =
                                calculate_dice_position(i, dice_config.dice_to_roll.len());
                            spawn_die(
                                &mut commands,
                                &mut meshes,
                                &mut materials,
                                *die_type,
                                position,
                            );
                        }

                        // Start rolling immediately
                        roll_state.rolling = true;
                    }
                    return;
                }
            }
        }
    }

    // Toggle command input with / or Enter when not active
    if !command_input.active
        && (keyboard.just_pressed(KeyCode::Slash) || keyboard.just_pressed(KeyCode::Enter))
    {
        command_input.active = true;
        command_input.text.clear();
        for mut text in input_text_query.iter_mut() {
            text.sections[0].value = "> ".to_string();
            text.sections[0].style.color = Color::srgb(1.0, 1.0, 0.5);
        }
        return;
    }

    if !command_input.active {
        return;
    }

    // Handle escape to cancel
    if keyboard.just_pressed(KeyCode::Escape) {
        command_input.active = false;
        command_input.text.clear();
        for mut text in input_text_query.iter_mut() {
            text.sections[0].value =
                "> Type command: --dice 2d6 --checkon stealth  |  Press 1-9 to reroll from history"
                    .to_string();
            text.sections[0].style.color = Color::srgba(0.7, 0.7, 0.7, 0.8);
        }
        return;
    }

    // Handle backspace
    if keyboard.just_pressed(KeyCode::Backspace) {
        command_input.text.pop();
        for mut text in input_text_query.iter_mut() {
            text.sections[0].value = format!("> {}_", command_input.text);
        }
        return;
    }

    // Handle enter to submit
    if keyboard.just_pressed(KeyCode::Enter) {
        let cmd = command_input.text.clone();
        command_input.active = false;
        command_input.text.clear();

        // Parse and apply the command
        if let Some(new_config) = parse_command(&cmd, &character_data) {
            // Add to command history (only unique commands)
            command_history.add_command(cmd.clone());

            // Update history display
            update_history_display(&command_history, &mut history_text_query);

            // Remove old dice
            for entity in dice_query.iter() {
                commands.entity(entity).despawn_recursive();
            }

            // Update config
            *dice_config = new_config;
            dice_results.results.clear();

            // Spawn new dice (spawn_die applies random initial velocities)
            for (i, die_type) in dice_config.dice_to_roll.iter().enumerate() {
                let position = calculate_dice_position(i, dice_config.dice_to_roll.len());
                spawn_die(
                    &mut commands,
                    &mut meshes,
                    &mut materials,
                    *die_type,
                    position,
                );
            }

            // Start rolling immediately - dice already have velocities from spawn_die
            roll_state.rolling = true;
        }

        for mut text in input_text_query.iter_mut() {
            text.sections[0].value =
                "> Type command: --dice 2d6 --checkon stealth  |  Press 1-9 to reroll from history"
                    .to_string();
            text.sections[0].style.color = Color::srgba(0.7, 0.7, 0.7, 0.8);
        }
        return;
    }

    // Handle character input
    for event in char_events.read() {
        if event.state == bevy::input::ButtonState::Pressed {
            // Map key codes to characters
            let c = match event.key_code {
                KeyCode::Space => ' ',
                KeyCode::Minus => '-',
                KeyCode::Equal => '=',
                KeyCode::Digit0 => '0',
                KeyCode::Digit1 => '1',
                KeyCode::Digit2 => '2',
                KeyCode::Digit3 => '3',
                KeyCode::Digit4 => '4',
                KeyCode::Digit5 => '5',
                KeyCode::Digit6 => '6',
                KeyCode::Digit7 => '7',
                KeyCode::Digit8 => '8',
                KeyCode::Digit9 => '9',
                KeyCode::KeyA => 'a',
                KeyCode::KeyB => 'b',
                KeyCode::KeyC => 'c',
                KeyCode::KeyD => 'd',
                KeyCode::KeyE => 'e',
                KeyCode::KeyF => 'f',
                KeyCode::KeyG => 'g',
                KeyCode::KeyH => 'h',
                KeyCode::KeyI => 'i',
                KeyCode::KeyJ => 'j',
                KeyCode::KeyK => 'k',
                KeyCode::KeyL => 'l',
                KeyCode::KeyM => 'm',
                KeyCode::KeyN => 'n',
                KeyCode::KeyO => 'o',
                KeyCode::KeyP => 'p',
                KeyCode::KeyQ => 'q',
                KeyCode::KeyR => 'r',
                KeyCode::KeyS => 's',
                KeyCode::KeyT => 't',
                KeyCode::KeyU => 'u',
                KeyCode::KeyV => 'v',
                KeyCode::KeyW => 'w',
                KeyCode::KeyX => 'x',
                KeyCode::KeyY => 'y',
                KeyCode::KeyZ => 'z',
                _ => continue,
            };
            command_input.text.push(c);
        }
    }

    // Update display
    for mut text in input_text_query.iter_mut() {
        text.sections[0].value = format!("> {}_", command_input.text);
    }
}

/// Parse a command string into a DiceConfig
fn parse_command(cmd: &str, character_data: &CharacterData) -> Option<DiceConfig> {
    let parts: Vec<&str> = cmd.split_whitespace().collect();
    if parts.is_empty() {
        return None;
    }

    let mut dice_to_roll = Vec::new();
    let mut modifier = 0i32;
    let mut modifier_name = String::new();
    let mut checkon: Option<String> = None;

    let mut i = 0;
    while i < parts.len() {
        let part = parts[i];

        if part == "--dice" || part == "-d" {
            if i + 1 < parts.len() {
                i += 1;
                if let Some((count, die_type)) = parse_dice_str(parts[i]) {
                    for _ in 0..count {
                        dice_to_roll.push(die_type);
                    }
                }
            }
        } else if part == "--checkon" {
            if i + 1 < parts.len() {
                i += 1;
                checkon = Some(parts[i].to_string());
            }
        } else if part == "--modifier" || part == "-m" {
            if i + 1 < parts.len() {
                i += 1;
                if let Ok(m) = parts[i].parse::<i32>() {
                    modifier += m;
                }
            }
        } else if part.contains('d') && !part.starts_with('-') {
            // Direct dice notation like "2d6"
            if let Some((count, die_type)) = parse_dice_str(part) {
                for _ in 0..count {
                    dice_to_roll.push(die_type);
                }
            }
        }

        i += 1;
    }

    // Apply checkon modifier
    if let Some(check) = checkon {
        let check_lower = check.to_lowercase();

        if let Some(skill_mod) = character_data.get_skill_modifier(&check_lower) {
            modifier += skill_mod;
            modifier_name = check.clone();
        } else if let Some(ability_mod) = character_data.get_ability_modifier(&check_lower) {
            modifier += ability_mod;
            modifier_name = format!("{} check", check);
        } else if let Some(save_mod) = character_data.get_saving_throw_modifier(&check_lower) {
            modifier += save_mod;
            modifier_name = format!("{} save", check);
        } else {
            modifier_name = check;
        }
    }

    // Default to 1d20 if no dice specified
    if dice_to_roll.is_empty() {
        dice_to_roll.push(DiceType::D20);
    }

    Some(DiceConfig {
        dice_to_roll,
        modifier,
        modifier_name,
    })
}

/// Parse a dice string like "2d6" into a count and die type
fn parse_dice_str(s: &str) -> Option<(usize, DiceType)> {
    let s = s.to_lowercase();

    let (count_str, die_str) = if s.starts_with('d') {
        ("1", s.as_str())
    } else if let Some(pos) = s.find('d') {
        (&s[..pos], &s[pos..])
    } else {
        return None;
    };

    let count: usize = count_str.parse().ok()?;
    let die_type = DiceType::parse(die_str)?;

    Some((count, die_type))
}

/// Update the command history display
fn update_history_display(
    history: &CommandHistory,
    history_text_query: &mut Query<
        &mut Text,
        (With<CommandHistoryList>, Without<CommandInputText>),
    >,
) {
    let mut history_text = String::from("Command History:\n");

    if history.commands.is_empty() {
        history_text.push_str("(no commands yet)");
    } else {
        for (i, cmd) in history.commands.iter().enumerate().take(9) {
            history_text.push_str(&format!("[{}] {}\n", i + 1, cmd));
        }
    }

    for mut text in history_text_query.iter_mut() {
        text.sections[0].value = history_text.clone();
    }
}

/// Handle quick roll button clicks
pub fn handle_quick_roll_clicks(
    interaction_query: Query<(&Interaction, &QuickRollButton), Changed<Interaction>>,
    mut dice_config: ResMut<DiceConfig>,
    character_data: Res<CharacterData>,
    mut roll_state: ResMut<RollState>,
    mut dice_results: ResMut<DiceResults>,
    mut dice_query: Query<(&mut Transform, &mut Velocity), With<Die>>,
    mut command_history: ResMut<CommandHistory>,
    throw_state: Res<ThrowControlState>,
) {
    for (interaction, quick_roll) in interaction_query.iter() {
        if *interaction == Interaction::Pressed {
            // Get the modifier based on roll type
            let (modifier, modifier_name) = match &quick_roll.roll_type {
                QuickRollType::Skill(skill_name) => {
                    let mod_val = character_data.get_skill_modifier(skill_name).unwrap_or(0);
                    // Format skill name nicely - capitalize first letter
                    let display_name = skill_name
                        .chars()
                        .enumerate()
                        .map(|(i, c)| if i == 0 { c.to_ascii_uppercase() } else { c })
                        .collect::<String>();
                    (mod_val, display_name)
                }
                QuickRollType::AbilityCheck(ability_name) => {
                    let mod_val = character_data
                        .get_ability_modifier(ability_name)
                        .unwrap_or(0);
                    let display_name = format!(
                        "{} check",
                        ability_name
                            .chars()
                            .next()
                            .unwrap_or_default()
                            .to_ascii_uppercase()
                            .to_string()
                            + &ability_name[1..]
                    );
                    (mod_val, display_name)
                }
                QuickRollType::SavingThrow(ability_name) => {
                    let mod_val = character_data
                        .get_saving_throw_modifier(ability_name)
                        .unwrap_or(0);
                    let display_name = format!(
                        "{} save",
                        ability_name
                            .chars()
                            .next()
                            .unwrap_or_default()
                            .to_ascii_uppercase()
                            .to_string()
                            + &ability_name[1..]
                    );
                    (mod_val, display_name)
                }
            };

            // Update dice config
            dice_config.dice_to_roll = vec![DiceType::D20];
            dice_config.modifier = modifier;
            dice_config.modifier_name = modifier_name.clone();

            // Add to command history
            let sign = if modifier >= 0 { "+" } else { "" };
            command_history.add_command(format!(
                "1d20 --checkon {} ({}{})",
                modifier_name, sign, modifier
            ));

            // Trigger the roll
            roll_state.rolling = true;
            dice_results.results.clear();

            // Reset dice positions and add velocity using throw control
            let mut rng = rand::thread_rng();
            let base_velocity = throw_state.calculate_throw_velocity();

            for (mut transform, mut velocity) in dice_query.iter_mut() {
                transform.translation =
                    Vec3::new(rng.gen_range(-0.5..0.5), 1.0, rng.gen_range(-0.5..0.5));
                transform.rotation = Quat::from_euler(
                    EulerRot::XYZ,
                    rng.gen_range(0.0..std::f32::consts::TAU),
                    rng.gen_range(0.0..std::f32::consts::TAU),
                    rng.gen_range(0.0..std::f32::consts::TAU),
                );
                // Use mouse-controlled throw direction
                velocity.linvel = base_velocity
                    + Vec3::new(
                        rng.gen_range(-0.5..0.5),
                        rng.gen_range(-0.3..0.0),
                        rng.gen_range(-0.5..0.5),
                    );
                velocity.angvel = throw_state.calculate_angular_velocity(&mut rng);
            }
        }
    }
}