game_input_system/
game_input_system.rs

1//! 游戏输入系统示例
2//! 运行: cargo run --example game_input_system
3
4// use keyboard_codes::*;
5// use std::collections::HashMap;
6
7use keyboard_codes::{
8    current_platform, parse_keyboard_input, Key, KeyboardInput, Modifier, Platform,
9};
10use std::collections::HashMap;
11
12#[derive(Debug, Clone, Copy, PartialEq)]
13enum GameAction {
14    MoveForward,
15    MoveBackward,
16    MoveLeft,
17    MoveRight,
18    Jump,
19    Sprint,
20    Crouch,
21    Interact,
22    Attack,
23    Reload,
24    Weapon1,
25    Weapon2,
26    Weapon3,
27}
28
29struct GameInputMapper {
30    key_bindings: HashMap<Key, GameAction>,           // 普通键绑定
31    modifier_bindings: HashMap<Modifier, GameAction>, // 修饰键绑定
32    platform: Platform,
33}
34
35impl GameInputMapper {
36    fn new(platform: Platform) -> Self {
37        let mut key_bindings = HashMap::new();
38        let mut modifier_bindings = HashMap::new();
39
40        // 运动控制 - 普通键
41        Self::add_key_binding(&mut key_bindings, "w", GameAction::MoveForward);
42        Self::add_key_binding(&mut key_bindings, "s", GameAction::MoveBackward);
43        Self::add_key_binding(&mut key_bindings, "a", GameAction::MoveLeft);
44        Self::add_key_binding(&mut key_bindings, "d", GameAction::MoveRight);
45        Self::add_key_binding(&mut key_bindings, "space", GameAction::Jump);
46
47        // 交互控制
48        Self::add_key_binding(&mut key_bindings, "e", GameAction::Interact);
49        Self::add_key_binding(&mut key_bindings, "f", GameAction::Attack);
50        Self::add_key_binding(&mut key_bindings, "r", GameAction::Reload);
51
52        // 武器切换
53        Self::add_key_binding(&mut key_bindings, "1", GameAction::Weapon1);
54        Self::add_key_binding(&mut key_bindings, "2", GameAction::Weapon2);
55        Self::add_key_binding(&mut key_bindings, "3", GameAction::Weapon3);
56
57        // 修饰键绑定
58        Self::add_modifier_binding(&mut modifier_bindings, "shift", GameAction::Sprint);
59        Self::add_modifier_binding(&mut modifier_bindings, "ctrl", GameAction::Crouch);
60
61        Self {
62            key_bindings,
63            modifier_bindings,
64            platform,
65        }
66    }
67
68    // 添加普通键绑定
69    fn add_key_binding(bindings: &mut HashMap<Key, GameAction>, input: &str, action: GameAction) {
70        match parse_keyboard_input(input) {
71            Ok(KeyboardInput::Key(key)) => {
72                bindings.insert(key, action);
73                println!("  绑定: '{}' -> {:?}", input, action);
74            }
75            Ok(KeyboardInput::Modifier(_)) => {
76                eprintln!("警告: '{}' 是修饰键,请使用 add_modifier_binding", input);
77            }
78            Err(e) => {
79                eprintln!("警告: 无法解析键绑定 '{}': {}", input, e);
80            }
81        }
82    }
83
84    // 添加修饰键绑定
85    fn add_modifier_binding(
86        bindings: &mut HashMap<Modifier, GameAction>,
87        input: &str,
88        action: GameAction,
89    ) {
90        match parse_keyboard_input(input) {
91            Ok(KeyboardInput::Modifier(modifier)) => {
92                bindings.insert(modifier, action);
93                println!("  绑定: '{}' -> {:?}", input, action);
94            }
95            Ok(KeyboardInput::Key(_)) => {
96                eprintln!("警告: '{}' 是普通键,请使用 add_key_binding", input);
97            }
98            Err(e) => {
99                eprintln!("警告: 无法解析修饰键绑定 '{}': {}", input, e);
100            }
101        }
102    }
103
104    fn handle_key_event(&self, vk_code: usize) -> Option<GameAction> {
105        if let Some(keyboard_input) = KeyboardInput::from_code(vk_code, self.platform) {
106            match keyboard_input {
107                KeyboardInput::Key(key) => {
108                    // 查找普通键绑定
109                    if let Some(action) = self.key_bindings.get(&key) {
110                        return Some(*action);
111                    }
112                }
113                KeyboardInput::Modifier(modifier) => {
114                    // 查找修饰键绑定
115                    if let Some(action) = self.modifier_bindings.get(&modifier) {
116                        return Some(*action);
117                    }
118                }
119            }
120        }
121        None
122    }
123
124    fn list_bindings(&self) {
125        println!("\n普通键绑定:");
126        let mut keys: Vec<_> = self.key_bindings.iter().collect();
127        keys.sort_by_key(|(key, _)| key.as_str());
128        for (key, action) in keys {
129            println!("  {:15} -> {:?}", key, action);
130        }
131
132        println!("\n修饰键绑定:");
133        let mut modifiers: Vec<_> = self.modifier_bindings.iter().collect();
134        modifiers.sort_by_key(|(modifier, _)| modifier.as_str());
135        for (modifier, action) in modifiers {
136            println!("  {:15} -> {:?}", modifier, action);
137        }
138    }
139
140    // 处理组合键(例如:Shift + 某个键)
141    fn handle_combo_event(
142        &self,
143        modifier_vks: &[usize],
144        key_vk: usize,
145    ) -> Option<(Vec<Modifier>, GameAction)> {
146        let modifiers: Vec<Modifier> = modifier_vks
147            .iter()
148            .filter_map(|&code| {
149                if let Some(KeyboardInput::Modifier(modifier)) =
150                    KeyboardInput::from_code(code, self.platform)
151                {
152                    Some(modifier)
153                } else {
154                    None
155                }
156            })
157            .collect();
158
159        if let Some(KeyboardInput::Key(key)) = KeyboardInput::from_code(key_vk, self.platform) {
160            if let Some(action) = self.key_bindings.get(&key) {
161                return Some((modifiers, *action));
162            }
163        }
164
165        None
166    }
167}
168
169fn main() {
170    println!("=== 游戏输入系统示例 ===\n");
171
172    let platform = current_platform();
173    println!("当前平台: {}", platform);
174
175    let input_mapper = GameInputMapper::new(platform);
176
177    input_mapper.list_bindings();
178
179    println!("\n模拟按键事件 (Windows VK 代码):");
180    let test_keys = [
181        (0x57, "W"),     // W
182        (0x41, "A"),     // A
183        (0x20, "Space"), // Space
184        (0x31, "1"),     // 1
185        (0x10, "Shift"), // Shift
186        (0x11, "Ctrl"),  // Ctrl
187    ];
188
189    for &(vk_code, desc) in &test_keys {
190        if let Some(action) = input_mapper.handle_key_event(vk_code) {
191            println!("  VK {:02X} ({:6}) -> {:?}", vk_code, desc, action);
192        } else {
193            println!("  VK {:02X} ({:6}) -> 无绑定", vk_code, desc);
194        }
195    }
196
197    // 测试组合键
198    println!("\n模拟组合键事件:");
199    let combo_tests = [
200        (vec![0x10], 0x57, "Shift + W"), // Shift + W
201        (vec![0x11], 0x41, "Ctrl + A"),  // Ctrl + A
202    ];
203
204    for (modifiers, key, desc) in combo_tests {
205        if let Some((active_modifiers, action)) = input_mapper.handle_combo_event(&modifiers, key) {
206            let mod_names: Vec<String> = active_modifiers.iter().map(|m| m.to_string()).collect();
207            println!("  {} -> {:?} (修饰键: {:?})", desc, action, mod_names);
208        } else {
209            println!("  {} -> 无绑定", desc);
210        }
211    }
212
213    println!("\n示例完成!");
214}