src/actions.rs 4.3 K · 142 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 ToggleFarmTool,
20 CycleBuildTool,
21 ToggleDesignateTool,
22 Cancel,
23 NewWorld,
24 ToggleUi,
25 ZoomIn,
26 ZoomOut,
27 Save,
28 Load,
29 }
30
31 pub const KEYBINDS: [(KeyCode, Action); 16] = [
32 (KeyCode::Space, Action::TogglePause),
33 (KeyCode::Digit1, Action::SetSpeed(SimSpeed::Normal)),
34 (KeyCode::Digit2, Action::SetSpeed(SimSpeed::Fast)),
35 (KeyCode::Digit3, Action::SetSpeed(SimSpeed::Fastest)),
36 (KeyCode::Digit4, Action::SetSpeed(SimSpeed::Max)),
37 (KeyCode::KeyZ, Action::ToggleStockpileTool),
38 (KeyCode::KeyF, Action::ToggleFarmTool),
39 (KeyCode::KeyB, Action::CycleBuildTool),
40 (KeyCode::KeyX, Action::ToggleDesignateTool),
41 (KeyCode::Escape, Action::Cancel),
42 (KeyCode::KeyR, Action::NewWorld),
43 (KeyCode::KeyH, Action::ToggleUi),
44 (KeyCode::Equal, Action::ZoomIn),
45 (KeyCode::Minus, Action::ZoomOut),
46 (KeyCode::F5, Action::Save),
47 (KeyCode::F9, Action::Load),
48 ];
49
50 impl Action {
51 pub fn label(self) -> &'static str {
52 match self {
53 Action::TogglePause => "Pause",
54 Action::SetSpeed(SimSpeed::Normal) => "1x",
55 Action::SetSpeed(SimSpeed::Fast) => "3x",
56 Action::SetSpeed(SimSpeed::Fastest) => "6x",
57 Action::SetSpeed(SimSpeed::Max) => "Max",
58 Action::ToggleStockpileTool => "Stockpile",
59 Action::ToggleFarmTool => "Farm",
60 Action::CycleBuildTool => "Build",
61 Action::ToggleDesignateTool => "Mark",
62 Action::Cancel => "Cancel",
63 Action::NewWorld => "New map",
64 Action::ToggleUi => "Hide",
65 Action::ZoomIn => "+",
66 Action::ZoomOut => "-",
67 Action::Save => "Save",
68 Action::Load => "Load",
69 }
70 }
71
72 pub fn key(self) -> Option<KeyCode> {
73 KEYBINDS
74 .iter()
75 .find(|(_, action)| *action == self)
76 .map(|(key, _)| *key)
77 }
78
79 pub fn key_label(self) -> String {
80 match self.key() {
81 Some(KeyCode::Space) => "Space".into(),
82 Some(KeyCode::Escape) => "Esc".into(),
83 Some(KeyCode::Equal) => "=".into(),
84 Some(KeyCode::Minus) => "-".into(),
85 Some(key) => format!("{key:?}")
86 .trim_start_matches("Digit")
87 .trim_start_matches("Key")
88 .to_string(),
89 None => String::new(),
90 }
91 }
92 }
93
94 fn keyboard_actions(keys: Res<ButtonInput<KeyCode>>, mut actions: MessageWriter<Action>) {
95 for (key, action) in KEYBINDS {
96 if keys.just_pressed(key) {
97 actions.write(action);
98 }
99 }
100 }
101
102 #[cfg(test)]
103 mod tests {
104 use super::*;
105
106 #[test]
107 fn pressing_a_bound_key_triggers_its_action() {
108 let mut app = App::new();
109 app.init_resource::<ButtonInput<KeyCode>>()
110 .add_message::<Action>()
111 .add_systems(Update, keyboard_actions);
112 app.world_mut()
113 .resource_mut::<ButtonInput<KeyCode>>()
114 .press(KeyCode::Digit3);
115 app.update();
116 let actions: Vec<Action> = app
117 .world_mut()
118 .resource_mut::<Messages<Action>>()
119 .drain()
120 .collect();
121 assert_eq!(actions, vec![Action::SetSpeed(SimSpeed::Fastest)]);
122 }
123
124 #[test]
125 fn every_action_has_exactly_one_key() {
126 for (_, action) in KEYBINDS {
127 let bound = KEYBINDS.iter().filter(|(_, a)| *a == action).count();
128 assert_eq!(bound, 1, "{action:?}");
129 }
130 let mut keys: Vec<_> = KEYBINDS.iter().map(|(k, _)| format!("{k:?}")).collect();
131 keys.sort();
132 keys.dedup();
133 assert_eq!(keys.len(), KEYBINDS.len());
134 }
135
136 #[test]
137 fn key_labels_are_short() {
138 assert_eq!(Action::SetSpeed(SimSpeed::Fast).key_label(), "2");
139 assert_eq!(Action::ToggleStockpileTool.key_label(), "Z");
140 assert_eq!(Action::Cancel.key_label(), "Esc");
141 }
142 }