List of keys down library

hello i don't know where to put this but this library has a block that reports a list of all the keys being pressed down

<block-definition s="initiliaze key detector" type="command" category="sensing">
<comment w="90" collapsed="false">
Initiliazes list of keys pressed. Using the "keys down" reporter before running this block will cause the other block to break.
</comment>
<header/>
<code/>
<translations/>
<inputs/>
<script>
<block s="doRun">
<block s="reportJSFunction">
<list>
<l>proc</l>
</list>
<l>
if (window.libKeyDetector === undefined) {
window.libKeyDetector = {};
window.libKeyDetector.keys = [];
window.libKeyDetector.onKeyDown = function(event) {
 if (window.libKeyDetector.keys.indexOf(event.key) == -1) {
 window.libKeyDetector.keys.push(event.key);
 proc.doBroadcast("keydown " + event.key);
 }
}
window.libKeyDetector.onKeyUp = function(event) {
 window.libKeyDetector.keys.splice(window.libKeyDetector.keys.indexOf(event.key), 1);
}

window.addEventListener("keydown", window.libKeyDetector.onKeyDown);
window.addEventListener("keyup", window.libKeyDetector.onKeyUp);
}
</l>
</block>
<list/>
</block>
</script>
</block-definition>
<block-definition s="keys down" type="reporter" category="sensing">
<comment w="90" collapsed="false">
Returns a list of all the keys currently being pressed down.
</comment>
<header/>
<code/>
<translations/>
<inputs/>
<script>
<block s="doReport">
<block s="evaluate">
<block s="reportJSFunction">
<list/>
<l>return new List(window.libKeyDetector.keys);</l>
</block>
<list/>
</block>
</block>
</script>
</block-definition>
<block-definition s="disable key detector" type="command" category="sensing">
<comment w="90" collapsed="false">Turns off key detector.</comment>
<header/>
<code/>
<translations/>
<inputs/>
<script>
<block s="doRun">
<block s="reportJSFunction">
<list/>
<l>
if (window.libKeyDetector) {
 window.removeEventListener("keydown", window.libKeyDetector.onKeyDown);
 window.removeEventListener("keyup", window.libKeyDetector.onKeyUp);
 window.libKeyDetector = undefined;
}
</l>
</block>
<list/>
</block>
</script>
</block-definition>
</blocks>
1 Like

Interesting, thanks. I'm thinking it might be better if the block reported, not all the keys down now, but a list of key events, perhaps being smart enough to distinguish shift-like keys from letter-like keys, and put in the list all the keys that are down during the downness of a letter-like key. Although also I guess you should handle rollover, which means the event handlers should always push the entire event, and the user-accessible block should pop off enough events for one letter-like key -- although not popping, exactly, because of rollover. Anyway, there's an algorithm, ask Google or something. And the user block should report in a user-friendly format, e.g. a list {control,shift,a}.

It didn't work for me

I just got a variable with all of the XML code in it.