Chapter 10. Keyboard Signals
The Keyboard module defines functions for dealing with keyboard input. Elm uses KeyCode as an alias for Int and keyboard input values are expressed using that type. We can use the toChar and fromChar functions from the Char module to convert between Int values and characters (Char values).
> import Char exposing (toCode, fromCode) > toCode 'a' 97 : Int > toCode 'A' 65 : Int > toCode '2' 50 : Int > fromCode 65 'A' : Char > fromCode 97 'a' : Char
The Keyboard module defines functions which create keyboard related signals. The keysDown function creates a signal which informs what keys are currently being pressed. The signal value is a list of key codes. Try the KeyboardSignals1.elm program here (KeyboardSignals1.html)to see it in action.
File KeyboardSignals1.elm: module KeyboardSignals1 where import Keyboard import Signal exposing ((<~)) import Graphics.Element exposing (show) main = show <~ Keyboard.keysDown
The presses function returns a signal which provides the code of the last pressed key — even when the key is not currently being pressed any more. Check it out using the KeyboardSignals2.elm program here: KeyboardSignals2.html.
File KeyboardSignals2.elm: module KeyboardSignals2 where import Graphics.Element exposing (show) import Keyboard import Signal exposing ((<~)) main = show <~ Keyboard.presses
The isDown function takes a key code as its argument and returns a boolean signal indicating whether the given key is currently being pressed. There are also helper functions defined in terms of isDown for certain special keys: shift, ctrl, space and enter. Run the KeyboardSignals3.elm program (KeyboardSignals3.html) and try pressing the A key.
File KeyboardSignals3.elm: module KeyboardSignals3 where import Char import Graphics.Element exposing (show) import Keyboard import Signal exposing ((<~)) main = show <~ Keyboard.isDown (Char.toCode 'A')
The arrows function is useful for building games. It returns a signal of { x: Int, y: Int } records. Pressing the up and down arrow keys affect the y values in the output record as follows:
- when the up arrow key is pressed and the down arrow key is not, then y has the value of 1
- when the down arrow key is pressed and the up arrow key is not, then y has the value of -1
- when both up and down arrow keys are pressed or none of them, then y has the value of 0
Pressing the left and right arrow keys affect the values of the x member in a similar way. Run the KeyboardSignals4.elm program here (KeyboardSignals4.html) and try pressing the arrow keys in various combinations:
File KeyboardSignals4.elm: module KeyboardSignals4 where import Graphics.Element exposing (show) import Keyboard import Signal exposing ((<~)) main = show <~ Keyboard.arrows
There is also a similar function called wasd, which works in a similar way, but react to the W, A, S and D keys.
The next chapter presents a game which uses keyboard as input.