pinch-points 0.8.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Keyboard bindings (spec ยง8.4 full remapping): which key does what, for
//! each of the two keyboard seats.
//!
//! The bindings are a flat array indexed by [`Action`], so the controls
//! screen, the settings file, and the input layer all walk the same list and
//! cannot drift apart. Keys are stored under their Bevy names (`KeyW`,
//! `ArrowUp`, `Numpad0`) and shown prettier than that.

use bevy::prelude::KeyCode;

/// Seats that answer to a keyboard; the seats past these two (P3 up to
/// P6, see [`crate::sim::MAX_PLAYERS`]) are gamepad-only.
pub const BOUND_SEATS: usize = 2;

/// One thing a seat can do with a key press.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Action {
    MoveUp,
    MoveDown,
    MoveLeft,
    MoveRight,
    PlaceUp,
    PlaceDown,
    PlaceLeft,
    PlaceRight,
    Remove,
    ClearAll,
}

impl Action {
    pub const ALL: [Action; 10] = [
        Action::MoveUp,
        Action::MoveDown,
        Action::MoveLeft,
        Action::MoveRight,
        Action::PlaceUp,
        Action::PlaceDown,
        Action::PlaceLeft,
        Action::PlaceRight,
        Action::Remove,
        Action::ClearAll,
    ];

    /// Slot in a [`SeatBinds`] key list.
    pub fn index(self) -> usize {
        Action::ALL
            .iter()
            .position(|&a| a == self)
            .expect("every action is in ALL")
    }
}

pub const ACTIONS: usize = Action::ALL.len();

/// One seat's keys, in [`Action::ALL`] order.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct SeatBinds(pub [KeyCode; ACTIONS]);

impl SeatBinds {
    pub fn key(&self, action: Action) -> KeyCode {
        self.0[action.index()]
    }

    pub fn set(&mut self, action: Action, key: KeyCode) {
        self.0[action.index()] = key;
    }

    /// The stock layout for a seat (spec ยง8.2): seat 1 drives WASD plus the
    /// arrow keys, seat 2 the IJKL block plus the numpad.
    pub fn default_for(seat: usize) -> SeatBinds {
        if seat == 0 {
            SeatBinds([
                KeyCode::KeyW,
                KeyCode::KeyS,
                KeyCode::KeyA,
                KeyCode::KeyD,
                KeyCode::ArrowUp,
                KeyCode::ArrowDown,
                KeyCode::ArrowLeft,
                KeyCode::ArrowRight,
                KeyCode::Space,
                KeyCode::ShiftLeft,
            ])
        } else {
            SeatBinds([
                KeyCode::KeyI,
                KeyCode::KeyK,
                KeyCode::KeyJ,
                KeyCode::KeyL,
                KeyCode::Numpad8,
                KeyCode::Numpad5,
                KeyCode::Numpad4,
                KeyCode::Numpad6,
                KeyCode::Numpad0,
                KeyCode::NumpadEnter,
            ])
        }
    }
}

/// Every seat's bindings at their defaults.
pub fn default_binds() -> [SeatBinds; BOUND_SEATS] {
    std::array::from_fn(SeatBinds::default_for)
}

/// Which seat and action a key is already bound to, if any. Two seats share
/// one keyboard, so a clash across seats is just as broken as one within a
/// seat, so this checks the whole board.
pub fn conflict(binds: &[SeatBinds; BOUND_SEATS], key: KeyCode) -> Option<(usize, Action)> {
    for (seat, seat_binds) in binds.iter().enumerate() {
        for action in Action::ALL {
            if seat_binds.key(action) == key {
                return Some((seat, action));
            }
        }
    }
    None
}

/// Whether every action across every seat has a key to itself.
pub fn all_distinct(binds: &[SeatBinds; BOUND_SEATS]) -> bool {
    let mut names: Vec<String> = binds
        .iter()
        .flat_map(|seat| seat.0.iter().copied().map(key_name))
        .collect();
    let total = names.len();
    names.sort();
    names.dedup();
    names.len() == total
}

/// Keys the game reads whatever the bindings say, on screens where the
/// bindings are live: M toggles the music anywhere; on a puzzle H asks for
/// the hint, N and P step between stages and R restarts the run; in a
/// versus round C copies the round code. Bound to a seat, such a key would
/// do both jobs on one press, so none is offered. Escape is kept out the
/// same way, being how a capture is cancelled.
///
/// Not here, on purpose: W and S, which walk the menus but are stock
/// bindings and only read as menu keys where the seats are not playing (the
/// menus, the lobby, a paused round's card); S also steps a replay's speed;
/// V pastes a code on the menu and the replay shelf and validates in the
/// editor; T opens the lobby's chat.
pub const GLOBAL_KEYS: [KeyCode; 6] = [
    KeyCode::KeyM,
    KeyCode::KeyH,
    KeyCode::KeyN,
    KeyCode::KeyP,
    KeyCode::KeyR,
    KeyCode::KeyC,
];

/// The same six as the letters on their caps: what the game actually
/// listens for, through [`crate::app::keycaps::KeyCaps::key_for`], since a
/// mnemonic belongs to its letter and not to a position. [`GLOBAL_KEYS`]
/// is where those letters sit on QWERTY.
pub const GLOBAL_LETTERS: [char; 6] = ['M', 'H', 'N', 'P', 'R', 'C'];

/// [`key_from_name`] for the global keys, which are not bindable and so
/// not in its catalogue.
pub fn global_key_from_name(name: &str) -> Option<KeyCode> {
    GLOBAL_KEYS.into_iter().find(|&key| key_name(key) == name)
}

/// Keys a player may bind. Anything else is ignored during capture, which
/// keeps Escape (cancel), Enter, the function keys, the [`GLOBAL_KEYS`] and
/// the odd media key from being swallowed by a rebind.
pub fn bindable(key: KeyCode) -> bool {
    !GLOBAL_KEYS.contains(&key) && BINDABLE.contains(&key)
}

/// The bindable keys in the order the controls screen offers them, used
/// to read a name back into a [`KeyCode`]. The one list [`bindable`]
/// answers from too, so the two can never disagree.
pub(crate) fn all_bindable() -> impl Iterator<Item = KeyCode> {
    BINDABLE
        .iter()
        .copied()
        .filter(|key| !GLOBAL_KEYS.contains(key))
}

/// Every key a binding may use, the [`GLOBAL_KEYS`] among them since they
/// sit in the alphabet; [`bindable`] takes those back out. KeyCode has no
/// iterator of its own, so the list is written down.
const BINDABLE: [KeyCode; 82] = [
    KeyCode::KeyA,
    KeyCode::KeyB,
    KeyCode::KeyC,
    KeyCode::KeyD,
    KeyCode::KeyE,
    KeyCode::KeyF,
    KeyCode::KeyG,
    KeyCode::KeyH,
    KeyCode::KeyI,
    KeyCode::KeyJ,
    KeyCode::KeyK,
    KeyCode::KeyL,
    KeyCode::KeyM,
    KeyCode::KeyN,
    KeyCode::KeyO,
    KeyCode::KeyP,
    KeyCode::KeyQ,
    KeyCode::KeyR,
    KeyCode::KeyS,
    KeyCode::KeyT,
    KeyCode::KeyU,
    KeyCode::KeyV,
    KeyCode::KeyW,
    KeyCode::KeyX,
    KeyCode::KeyY,
    KeyCode::KeyZ,
    KeyCode::Digit0,
    KeyCode::Digit1,
    KeyCode::Digit2,
    KeyCode::Digit3,
    KeyCode::Digit4,
    KeyCode::Digit5,
    KeyCode::Digit6,
    KeyCode::Digit7,
    KeyCode::Digit8,
    KeyCode::Digit9,
    KeyCode::ArrowUp,
    KeyCode::ArrowDown,
    KeyCode::ArrowLeft,
    KeyCode::ArrowRight,
    KeyCode::Numpad0,
    KeyCode::Numpad1,
    KeyCode::Numpad2,
    KeyCode::Numpad3,
    KeyCode::Numpad4,
    KeyCode::Numpad5,
    KeyCode::Numpad6,
    KeyCode::Numpad7,
    KeyCode::Numpad8,
    KeyCode::Numpad9,
    KeyCode::NumpadEnter,
    KeyCode::NumpadAdd,
    KeyCode::NumpadSubtract,
    KeyCode::NumpadMultiply,
    KeyCode::NumpadDivide,
    KeyCode::NumpadDecimal,
    KeyCode::Space,
    KeyCode::Tab,
    KeyCode::Backspace,
    KeyCode::Insert,
    KeyCode::Delete,
    KeyCode::Home,
    KeyCode::End,
    KeyCode::PageUp,
    KeyCode::PageDown,
    KeyCode::ShiftLeft,
    KeyCode::ShiftRight,
    KeyCode::ControlLeft,
    KeyCode::ControlRight,
    KeyCode::AltLeft,
    KeyCode::AltRight,
    KeyCode::Comma,
    KeyCode::Period,
    KeyCode::Slash,
    KeyCode::Semicolon,
    KeyCode::Quote,
    KeyCode::BracketLeft,
    KeyCode::BracketRight,
    KeyCode::Backslash,
    KeyCode::Minus,
    KeyCode::Equal,
    KeyCode::Backquote,
];

/// The settings-file name for a key: Bevy's own spelling, which is stable
/// and unambiguous. [`key_from_name`] is its inverse.
pub fn key_name(key: KeyCode) -> String {
    format!("{key:?}")
}

pub fn key_from_name(name: &str) -> Option<KeyCode> {
    all_bindable().find(|&key| key_name(key) == name)
}

/// How a key reads on screen: "KeyW" is a spelling, "W" is a keycap.
pub fn key_label(key: KeyCode) -> String {
    let name = key_name(key);
    // The punctuation keys are printed on the cap, so print them here too.
    // Spelling one out ("Backquote") asks the player to translate.
    for (spelling, cap) in [
        ("Comma", ","),
        ("Period", "."),
        ("Slash", "/"),
        ("Backslash", "\\"),
        ("Semicolon", ";"),
        ("Quote", "'"),
        ("BracketLeft", "["),
        ("BracketRight", "]"),
        ("Minus", "-"),
        ("Equal", "="),
        ("Backquote", "`"),
    ] {
        if name == spelling {
            return cap.to_string();
        }
    }
    // Keycaps do not say "Key" or "Arrow"; the numpad keys do want saying.
    for (prefix, cap) in [
        ("Key", ""),
        ("Digit", ""),
        ("Arrow", ""),
        ("Numpad", "Num "),
    ] {
        if let Some(rest) = name.strip_prefix(prefix) {
            return format!("{cap}{rest}");
        }
    }
    // Bevy names the modifiers side-last ("ShiftLeft"); a keyboard names
    // them side-first, and the default clear-all binding puts one of these
    // on the controls screen for every player to read.
    for side in ["Left", "Right"] {
        if let Some(rest) = name.strip_suffix(side) {
            return format!("{side} {rest}");
        }
    }
    // Two-word names run together the same way.
    for (run_on, spaced) in [("PageUp", "Page Up"), ("PageDown", "Page Down")] {
        if name == run_on {
            return spaced.to_string();
        }
    }
    name
}

/// The whole binding table as settings-file text, one line per seat.
pub fn to_text(binds: &[SeatBinds; BOUND_SEATS]) -> String {
    let mut out = String::new();
    for (seat, seat_binds) in binds.iter().enumerate() {
        let names: Vec<String> = seat_binds.0.iter().copied().map(key_name).collect();
        out.push_str(&format!("keys_p{}: {}\n", seat + 1, names.join(" ")));
    }
    out
}

/// Read one `keys_pN` line. A short line, an unknown key name, or a
/// duplicate leaves that seat on its defaults rather than half-bound.
pub fn parse_seat(value: &str) -> Option<SeatBinds> {
    let names: Vec<&str> = value.split_whitespace().collect();
    if names.len() != ACTIONS {
        return None;
    }
    let mut keys = [KeyCode::Space; ACTIONS];
    for (slot, name) in keys.iter_mut().zip(&names) {
        *slot = key_from_name(name)?;
    }
    let mut seen: Vec<String> = keys.iter().copied().map(key_name).collect();
    seen.sort();
    seen.dedup();
    (seen.len() == ACTIONS).then_some(SeatBinds(keys))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn key_names_round_trip() {
        for key in all_bindable() {
            assert_eq!(key_from_name(&key_name(key)), Some(key), "{key:?}");
        }
        assert_eq!(key_from_name("NoSuchKey"), None);
        // Escape stays unbindable: it is how you back out of a capture.
        assert!(!bindable(KeyCode::Escape));
        assert_eq!(key_from_name("Escape"), None);
    }

    /// A key the game reads on its own during play cannot also be a
    /// seat's, or one press would do two things.
    #[test]
    fn global_keys_are_not_bindable() {
        for key in GLOBAL_KEYS {
            assert!(!bindable(key), "{key:?} is read whatever the bindings say");
            assert_eq!(key_from_name(&key_name(key)), None, "{key:?}");
        }
        assert!(all_bindable().all(|key| !GLOBAL_KEYS.contains(&key)));
        // And the stock layouts never used one, or the game would refuse
        // its own defaults.
        for seat in default_binds() {
            for action in Action::ALL {
                assert!(bindable(seat.key(action)), "{action:?}");
            }
        }
    }

    #[test]
    fn labels_read_like_keycaps() {
        assert_eq!(key_label(KeyCode::KeyW), "W");
        assert_eq!(key_label(KeyCode::Digit4), "4");
        assert_eq!(key_label(KeyCode::ArrowUp), "Up");
        assert_eq!(key_label(KeyCode::Numpad8), "Num 8");
        assert_eq!(key_label(KeyCode::ShiftLeft), "Left Shift");
        assert_eq!(key_label(KeyCode::ControlRight), "Right Control");
        assert_eq!(key_label(KeyCode::Backquote), "`");
        assert_eq!(key_label(KeyCode::PageUp), "Page Up");
    }

    /// The two keyboard seats share a keyboard, so no key may do two jobs.
    #[test]
    fn the_default_layout_has_no_clashes() {
        let binds = default_binds();
        for seat in 0..BOUND_SEATS {
            for action in Action::ALL {
                assert_eq!(
                    conflict(&binds, binds[seat].key(action)),
                    Some((seat, action)),
                    "{seat} {action:?} is claimed by someone else"
                );
            }
        }
        assert_eq!(conflict(&binds, KeyCode::F5), None);
    }

    #[test]
    fn bindings_round_trip_through_text() {
        let mut binds = default_binds();
        binds[0].set(Action::Remove, KeyCode::Backquote);
        binds[1].set(Action::MoveUp, KeyCode::Home);
        let text = to_text(&binds);
        for (seat, line) in text.lines().enumerate() {
            let (_, value) = line.split_once(':').expect("key: value");
            assert_eq!(parse_seat(value), Some(binds[seat]));
        }
    }

    /// A half-written or self-contradicting line is refused outright, so a
    /// hand-edited file can never leave a seat unable to move.
    #[test]
    fn broken_binding_lines_are_refused() {
        assert_eq!(parse_seat("KeyW KeyS"), None, "too few keys");
        assert_eq!(parse_seat("Bogus ".repeat(10).trim()), None, "unknown key");
        let doubled = "KeyW KeyW KeyA KeyD ArrowUp ArrowDown ArrowLeft ArrowRight Space ShiftLeft";
        assert_eq!(parse_seat(doubled), None, "one key, two jobs");
    }
}