lib/gamnit: intro `keys` to keep track of pressed keys
authorAlexis Laferrière <alexis.laf@xymus.net>
Mon, 5 Oct 2015 14:03:38 +0000 (10:03 -0400)
committerAlexis Laferrière <xymus@tura.tura.home.xymus.net>
Wed, 20 Jan 2016 17:10:33 +0000 (12:10 -0500)
Signed-off-by: Alexis Laferrière <alexis.laf@xymus.net>

lib/gamnit/keys.nit [new file with mode: 0644]

diff --git a/lib/gamnit/keys.nit b/lib/gamnit/keys.nit
new file mode 100644 (file)
index 0000000..85e9e1e
--- /dev/null
@@ -0,0 +1,47 @@
+# This file is part of NIT (http://www.nitlanguage.org).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Simple service keeping track of which keys are currently pressed
+#
+# This service revolves around `app.pressed_keys`, a `Set` of the names of currently pressed keys.
+# As a `Set`, `app.pressed_keys` can be iterated and queried with `has`.
+#
+# Limitations: The keys names are platform dependent.
+module keys
+
+import mnit::input
+import gamnit
+
+redef class App
+       # Currently pressed keys
+       var pressed_keys = new Set[String] is lazy
+
+       # Register `event` to update `app.pressed_keys`
+       private fun register_key_event(event: KeyEvent)
+       do
+               var key = event.name
+               if event.is_down then
+                       app.pressed_keys.add key
+               else if app.pressed_keys.has(key) then
+                       app.pressed_keys.remove key
+               end
+       end
+
+       redef fun accept_event(event)
+       do
+               if event isa KeyEvent then register_key_event event
+
+               return super
+       end
+end