17cupsofcoffee / tetra

🎮 A simple 2D game framework written in Rust
MIT License
909 stars 63 forks source link

Add iterators to enumerate all keys and key labels #292

Closed sumibi-yakitori closed 2 years ago

sumibi-yakitori commented 2 years ago

I am remapping the CapsLock key to the Control key. If I are remapping on OS, before #277, you could detect all control key presses by using tetra::input::is_key_modifier_down(ctx, KeyModifier::Ctrl)

277 Onwards, I can use tetra::input::get_key_with_label to check the physical key after remapping, but this method can only return a single key due to SDL2 specification.

Therefore, there is no way to detect when multiple physical keys are mapped to a single logical key.

This PR adds an iterator to Tetra that enumerates all items, and the following code solves this problem.

let is_ctrl_key_down = tetra::input::Key::all()
  .filter_map(|key| {
    tetra::input::get_key_label(ctx, key)
      .filter(|label| *label == tetra::input::KeyLabel::LeftCtrl)
      .map(|_| key)
  })
  .any(|key| tetra::input::is_key_down(ctx, key));
sumibi-yakitori commented 2 years ago

There are some extra commits mixed in, so I'll cancel these.