Keyboard handling
Taking care of user input boils down to listening for proper keyboard events (keydown, keypress, keyup) and processing them. rot.js
does not offer any support methods or objects; instead, it defines a large set of ROT.VK_*
constants to distinguish between pressed keys. For a complete listing, please check out the generated docs.
There are also several general keyboard-related JavaScript guidelines:
- keydown and keyup events correspond to physical keys. Check their
keyCode
property and compare with ROT.VK_*
constants.
- keypress event corresponds to a printable character being generated. Check its
charCode
property; String.fromCharCode(x)
will create the corresponding character.
- Your mileage may vary across different browsers.
A very simple keyboard handler is shown below:
var input = document.createElement("input");
var out1 = document.createElement("div");
var out2 = document.createElement("div");
SHOW(input, out1, out2);
input.focus();
input.addEventListener("keydown", function(e) {
var code = e.keyCode;
var vk = "?"; /* find the corresponding constant */
for (var name in ROT) {
if (ROT[name] == code && name.indexOf("VK_") == 0) { vk = name; }
}
out1.innerHTML = "Keydown: code is " + code + " (" + vk + ")";
});
input.addEventListener("keypress", function(e) {
var code = e.charCode;
var ch = String.fromCharCode(code);
out2.innerHTML = "Keypress: char is " + ch;
});