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