teki_common/utils/
pad.rs

1use bitflags::bitflags;
2
3#[derive(Clone, Copy, PartialEq)]
4pub enum Key {
5    Space,
6    Escape,
7    Left,
8    Right,
9    Up,
10    Down,
11}
12
13bitflags! {
14    #[derive(Default)]
15    pub struct PadBit: u32 {
16        const L = 0b00000001;
17        const R = 0b00000010;
18        const U = 0b00000100;
19        const D = 0b00001000;
20        const A = 0b00010000;
21    }
22}
23
24#[derive(Clone, Default)]
25pub struct Pad {
26    key: PadBit,
27    pad: PadBit,
28    trg: PadBit,
29    last_pad: PadBit,
30}
31
32impl Pad {
33    pub fn update(&mut self) {
34        self.pad = self.key;
35        self.trg = self.pad & !self.last_pad;
36        self.last_pad = self.pad;
37    }
38
39    pub fn is_pressed(&self, btn: PadBit) -> bool {
40        self.pad.contains(btn)
41    }
42
43    pub fn is_trigger(&self, btn: PadBit) -> bool {
44        self.trg.contains(btn)
45    }
46
47    pub fn on_key(&mut self, key: Key, down: bool) {
48        let bit = get_key_bit(key);
49        if down {
50            self.key |= bit;
51        } else {
52            self.key &= !bit;
53        }
54    }
55}
56
57fn get_key_bit(key: Key) -> PadBit {
58    match key {
59        Key::Left => PadBit::L,
60        Key::Right => PadBit::R,
61        Key::Up => PadBit::U,
62        Key::Down => PadBit::D,
63        Key::Space => PadBit::A,
64        _ => PadBit::empty(),
65    }
66}