From: Alexis Laferrière Date: Mon, 5 Oct 2015 14:03:38 +0000 (-0400) Subject: lib/gamnit: intro `keys` to keep track of pressed keys X-Git-Tag: v0.8~13^2 X-Git-Url: http://nitlanguage.org lib/gamnit: intro `keys` to keep track of pressed keys Signed-off-by: Alexis Laferrière --- diff --git a/lib/gamnit/keys.nit b/lib/gamnit/keys.nit new file mode 100644 index 0000000..85e9e1e --- /dev/null +++ b/lib/gamnit/keys.nit @@ -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