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