src/actions.rs 3.4 K · 117 lines · raw · history

1 use bevy::{input::InputSystems, prelude::*};
2
3 use crate::sim::SimSpeed;
4
5 pub struct ActionsPlugin;
6
7 impl Plugin for ActionsPlugin {
8 fn build(&self, app: &mut App) {
9 app.add_message::<Action>()
10 .add_systems(PreUpdate, keyboard_actions.after(InputSystems));
11 }
12 }
13
14 #[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
15 pub enum Action {
16 TogglePause,
17 SetSpeed(SimSpeed),
18 ToggleStockpileTool,
19 Cancel,
20 NewWorld,
21 ToggleUi,
22 }
23
24 pub const KEYBINDS: [(KeyCode, Action); 8] = [
25 (KeyCode::Space, Action::TogglePause),
26 (KeyCode::Digit1, Action::SetSpeed(SimSpeed::Normal)),
27 (KeyCode::Digit2, Action::SetSpeed(SimSpeed::Fast)),
28 (KeyCode::Digit3, Action::SetSpeed(SimSpeed::Fastest)),
29 (KeyCode::KeyZ, Action::ToggleStockpileTool),
30 (KeyCode::Escape, Action::Cancel),
31 (KeyCode::KeyR, Action::NewWorld),
32 (KeyCode::KeyH, Action::ToggleUi),
33 ];
34
35 impl Action {
36 pub fn label(self) -> &'static str {
37 match self {
38 Action::TogglePause => "Pause",
39 Action::SetSpeed(SimSpeed::Normal) => "1x",
40 Action::SetSpeed(SimSpeed::Fast) => "3x",
41 Action::SetSpeed(SimSpeed::Fastest) => "6x",
42 Action::ToggleStockpileTool => "Stockpile",
43 Action::Cancel => "Cancel",
44 Action::NewWorld => "New world",
45 Action::ToggleUi => "Hide UI",
46 }
47 }
48
49 pub fn key(self) -> Option<KeyCode> {
50 KEYBINDS
51 .iter()
52 .find(|(_, action)| *action == self)
53 .map(|(key, _)| *key)
54 }
55
56 pub fn key_label(self) -> String {
57 match self.key() {
58 Some(KeyCode::Space) => "Space".into(),
59 Some(KeyCode::Escape) => "Esc".into(),
60 Some(key) => format!("{key:?}")
61 .trim_start_matches("Digit")
62 .trim_start_matches("Key")
63 .to_string(),
64 None => String::new(),
65 }
66 }
67 }
68
69 fn keyboard_actions(keys: Res<ButtonInput<KeyCode>>, mut actions: MessageWriter<Action>) {
70 for (key, action) in KEYBINDS {
71 if keys.just_pressed(key) {
72 actions.write(action);
73 }
74 }
75 }
76
77 #[cfg(test)]
78 mod tests {
79 use super::*;
80
81 #[test]
82 fn pressing_a_bound_key_triggers_its_action() {
83 let mut app = App::new();
84 app.init_resource::<ButtonInput<KeyCode>>()
85 .add_message::<Action>()
86 .add_systems(Update, keyboard_actions);
87 app.world_mut()
88 .resource_mut::<ButtonInput<KeyCode>>()
89 .press(KeyCode::Digit3);
90 app.update();
91 let actions: Vec<Action> = app
92 .world_mut()
93 .resource_mut::<Messages<Action>>()
94 .drain()
95 .collect();
96 assert_eq!(actions, vec![Action::SetSpeed(SimSpeed::Fastest)]);
97 }
98
99 #[test]
100 fn every_action_has_exactly_one_key() {
101 for (_, action) in KEYBINDS {
102 let bound = KEYBINDS.iter().filter(|(_, a)| *a == action).count();
103 assert_eq!(bound, 1, "{action:?}");
104 }
105 let mut keys: Vec<_> = KEYBINDS.iter().map(|(k, _)| format!("{k:?}")).collect();
106 keys.sort();
107 keys.dedup();
108 assert_eq!(keys.len(), KEYBINDS.len());
109 }
110
111 #[test]
112 fn key_labels_are_short() {
113 assert_eq!(Action::SetSpeed(SimSpeed::Fast).key_label(), "2");
114 assert_eq!(Action::ToggleStockpileTool.key_label(), "Z");
115 assert_eq!(Action::Cancel.key_label(), "Esc");
116 }
117 }